From e35e20b7faf78efcdaa75af24d2e4ff5151d1006 Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Fri, 20 Nov 2026 11:16:40 +0500 Subject: [PATCH 01/88] Draw Inside: keep the object as the clipping path, with its stroke (#8753) Draw Inside clipped by an unpainted copy of the selected object and put the object itself under the new art as clipped art, so its centred stroke lost its outer half and new art covered the rest. The object is now the clip group's clipping path and keeps its appearance: its fills paint behind the art drawn inside it and its strokes over it, unclipped (Node::clip_paint). Drawing inside it again reuses that group. --- crates/engine/src/cmd/create.rs | 28 ++++++------ crates/engine/src/tests/file.rs | 77 ++++++++++++++++++++++++++++++--- docs/roadmap.md | 5 ++- docs/target-app-parity.md | 5 ++- docs/ui-parity.md | 4 +- 5 files changed, 92 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 0ce38be40b..21f879acab 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -266,29 +266,27 @@ fn insert_look_turned( Ok(json!({ "id": id.0 })) } -/// Draw Inside's clip group for `target`, the object new art goes inside: the clip group -/// [mask copy, target, …] `target` already is the clipped object of, else one made where `target` -/// was, holding an unpainted clipping copy of it and then `target`. New art and pastes go on top -/// of its children. +/// Draw Inside's clip group for `target`, the object new art goes inside: the clip group `target` +/// already is the clipping path of, else one made where `target` was, with `target` as its +/// clipping path. `target` keeps its appearance, so its fills paint behind the art drawn inside it +/// and its strokes over that art, unclipped ([`Node::clip_paint`], #8753). New art and pastes go +/// on top of the group's children. pub(crate) fn draw_inside_group(d: &mut vectorcraft_doc::Document, target: NodeId) -> Result { if let Some(p) = d.parent_of(target) - && d.node(p).is_some_and(|pn| matches!(&pn.kind, NodeKind::Group { clip: true, children } if children.get(1).is_some_and(|c| c.id == target))) + && d.node(p) + .is_some_and(|pn| matches!(&pn.kind, NodeKind::Group { clip: true, children } if children.first().is_some_and(|c| c.id == target))) { return Ok(p); } let (par, idx, _) = d.position(target).ok_or(crate::EngineError::NoNode(target))?; - // The mask is a copy with ids of its own, its subpaths' too (a compound path's). - let original = d.node(target).cloned().ok_or(crate::EngineError::NoNode(target))?; - let mut mask = d.reid(&original); - mask.appearance = Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::None, 0.0).into(); - if let NodeKind::Path { clipping, .. } = &mut mask.kind { + let gid = d.alloc_id(); + d.insert(par, idx + 1, Node::new(gid, NodeKind::Group { children: vec![], clip: true }))?; + d.move_node(target, Some(gid), 0)?; + // A compound path or type is the clipping path by being the group's first child; a path is + // marked as well, as Make Clipping Mask marks it. + if let Some(NodeKind::Path { clipping, .. }) = d.node_mut(target).map(|n| &mut n.kind) { *clipping = true; } - let gid = d.alloc_id(); - d.insert(par, idx + 1, Node::new(gid, NodeKind::Group { children: vec![std::sync::Arc::new(mask)], clip: true }))?; - d.move_node(target, Some(gid), usize::MAX)?; - // Copied type whose layout caches `reid` dropped has them again. - super::typecmd::refresh_bounds_of(d, &[gid]); Ok(gid) } diff --git a/crates/engine/src/tests/file.rs b/crates/engine/src/tests/file.rs index c210f8cfc0..3ffdb9965d 100644 --- a/crates/engine/src/tests/file.rs +++ b/crates/engine/src/tests/file.rs @@ -134,11 +134,60 @@ fn draw_behind_and_inside() { assert_eq!(d.parent_of(NodeId(a)), Some(g)); // A second shape goes into the same clip group. s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - assert_eq!(s.doc().unwrap().doc.node(g).unwrap().children().unwrap().len(), 4); + assert_eq!(s.doc().unwrap().doc.node(g).unwrap().children().unwrap().len(), 3); s.execute("view.drawMode", &json!({"mode": "normal"})).unwrap(); assert!(s.draw_inside.is_none()); } +/// #8753: Draw Inside makes the object drawn into the clipping path, keeping its fill and stroke, +/// so its centred stroke stays whole and paints over the art drawn inside it. It used to clip by an +/// unpainted copy of the object, the object itself becoming clipped art under the new art: the +/// outer half of the stroke was cut off and the new art covered the inner half. +#[test] +fn draw_inside_keeps_the_objects_stroke_whole_and_over_the_new_art() { + use vectorcraft_geom::Affine; + use vectorcraft_render::{RenderOptions, Renderer}; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 240, "height": 240})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ebb471"})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#a8622a"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 12})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 140, "height": 140})).unwrap()["id"].as_u64().unwrap(); + let look = s.doc().unwrap().doc.node(NodeId(a)).unwrap().appearance.clone(); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + s.execute("view.drawMode", &json!({"mode": "inside"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#c89a60"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 110, "width": 220, "height": 110})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + // The clip group holds the object, its clipping path with its appearance, then the new art. + let g = d.parent_of(NodeId(a)).unwrap(); + let children: Vec = d.node(g).unwrap().children().unwrap().iter().map(|n| n.id.0).collect(); + assert_eq!(children, [a, b], "no unpainted copy of the object"); + let target = d.node(NodeId(a)).unwrap(); + assert!(matches!(target.kind, NodeKind::Path { clipping: true, .. })); + assert_eq!(target.appearance, look, "the object keeps its fill and stroke"); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let img = Renderer::new().render(d, 240, 240, Affine::IDENTITY, &opts); + let rgb = |x: u32, y: u32| { + let p = img.pixel(x, y); + [p[0], p[1], p[2]] + }; + let (stroke, fill, new) = ([0xa8, 0x62, 0x2a], [0xeb, 0xb4, 0x71], [0xc8, 0x9a, 0x60]); + // The stroke runs 6 pt either side of the edge: its outer half is not clipped away. + assert_eq!(rgb(120, 46), stroke, "outer half of the top stroke"); + assert_eq!(rgb(120, 53), stroke, "inner half of the top stroke"); + assert_eq!(rgb(120, 80), fill); + // Where the new art crosses the edge, the stroke paints over it, both halves. + for (x, y) in [(46, 150), (53, 150), (120, 186), (120, 193), (186, 150), (193, 150)] { + assert_eq!(rgb(x, y), stroke, "stroke at ({x}, {y})"); + } + // The new art shows inside the object only. + assert_eq!(rgb(120, 150), new); + assert_eq!(rgb(30, 150), [255, 255, 255]); +} + /// In Draw Inside, a double-click with a selection tool outside the object being drawn into sets /// the drawing mode to Draw Normal, and the tool still takes the double-click. Inside the object's /// bounds, grown by the selection tolerance, and with other tools, Draw Inside stays on. @@ -181,11 +230,11 @@ fn double_clicking_outside_the_draw_inside_object_returns_to_draw_normal() { /// the object drawn into, as drawn art goes, each paste one undo step; the first one makes the /// clip group and the next ones add to it, with Paste Remembers Layers on and with the object /// isolated by a double-click too. Paste in Front and Paste in Back keep their places. -/// Draw Inside a compound path: the clip group's mask is a copy whose subpaths have ids of their -/// own, so no two objects share an id. An artboard copied without art, pasted on all artboards in +/// Draw Inside a compound path: it becomes the clip group's clipping path, its first child, and no +/// two objects share an id. An artboard copied without art, pasted on all artboards in /// Draw Inside, makes no clip group. #[test] -fn draw_inside_a_compound_path_gives_its_mask_ids_of_its_own() { +fn draw_inside_a_compound_path_makes_it_the_clipping_path() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300, "artboards": 2})).unwrap(); let a = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); @@ -202,7 +251,22 @@ fn draw_inside_a_compound_path_gives_its_mask_ids_of_its_own() { ids.sort_unstable(); ids.dedup(); assert_eq!(ids.len(), all, "an id is used twice"); - assert_eq!(d.node(d.parent_of(NodeId(c)).unwrap()).unwrap().kind_label(), "Clip Group"); + let g = d.node(d.parent_of(NodeId(c)).unwrap()).unwrap(); + assert_eq!(g.kind_label(), "Clip Group"); + assert_eq!(g.children().unwrap().first().map(|n| n.id.0), Some(c), "the compound path is the clipping path"); + // Type too: it is the clipping path, keeping its paint, and drawing inside it again adds to + // the same clip group. + s.execute("view.drawMode", &json!({"mode": "normal"})).unwrap(); + let t = s.execute("text.create", &json!({"x": 100, "y": 250, "text": "Type", "size": 40})).unwrap()["id"].as_u64().unwrap(); + let look = s.doc().unwrap().doc.node(NodeId(t)).unwrap().clone(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + s.execute("view.drawMode", &json!({"mode": "inside"})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 100, "y": 220, "width": 30, "height": 30})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 110, "y": 220, "width": 30, "height": 30})).unwrap(); + let d = &s.doc().unwrap().doc; + let g = d.node(d.parent_of(NodeId(t)).unwrap()).unwrap(); + assert_eq!((g.kind_label(), g.children().unwrap().len()), ("Clip Group", 3)); + assert_eq!(**g.children().unwrap().first().unwrap(), look, "the type is the clipping path, as it was"); // An artboard alone on the clipboard: Paste on All Artboards adds nothing inside the object. let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300, "artboards": 2})).unwrap(); @@ -242,8 +306,7 @@ fn pasting_in_draw_inside_puts_the_copies_inside_the_object() { let all = pasted(s.execute("edit.pasteOnAllArtboards", &json!({})).unwrap()); assert_eq!(all.len(), 2); let children: Vec = s.doc().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id.0).collect(); - assert_eq!(children.len(), 6, "{children:?}"); - assert_eq!(children[1..], [a, ids[0], in_place[0], all[0], all[1]]); + assert_eq!(children, [a, ids[0], in_place[0], all[0], all[1]]); // Paste Remembers Layers doesn't take the copy out of the object. s.execute("layer.pasteRemembersLayers", &json!({"on": true})).unwrap(); let remembered = pasted(s.execute("edit.paste", &json!({})).unwrap()); diff --git a/docs/roadmap.md b/docs/roadmap.md index a518e3a35a..4baaaf87f3 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (M2: Draw Inside keeps the object it draws into as the clip group's clipping path with its fill and stroke, so its stroke stays whole over the art drawn inside it, #8753; scores and estimates unchanged; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -179,7 +179,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule |---|---|---|---| | M0 | Skeleton + vertical slice | ✅ done | — | | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | -| M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655) | 12–18 | +| M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655); Draw Inside keeps the object it draws into, with its fill and stroke, as the clipping path (#8753) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; in the web build an edit while the view of a heavy document moves draws only the part it changed into the last frame (#8688); dirty-region rendering, GPU backend spike pending | 15–25 | @@ -235,6 +235,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | M2: Draw Inside makes the object it draws into the clip group's clipping path, keeping its fill and stroke, instead of clipping by an unpainted copy of it: its centred stroke is no longer clipped by its own outline and paints over the art drawn inside it ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html), [archived](https://web.archive.org/web/20261111110310/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#8753). Scores and estimates unchanged. | | 2026-11-19 | minor | M1: Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | | 2026-11-19 | minor | M11: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1d981428a..68c8337757 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Draw Inside keeps the object it draws into as the clip group's clipping path with its fill and stroke, so its stroke stays whole over the art drawn inside it, #8753; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -1410,7 +1410,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Compound paths:** Make keeps the backmost object's appearance and each contour; selecting a member in Direct Selection reads and changes the compound's fill rule in Attributes. Direction remains a per-member edit. Rendered holes, unchanged contour geometry, no-op history and Undo/Redo are covered by `engine/tests/it/compound_attributes.rs` (#1197). Behaviour reference: [public compound-path documentation](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-paths.html). Make Compound Path on a group (such as outlined type) keeps the paint of its backmost path instead of drawing nothing, and compound paths joined into one keep their holes (#1537). - **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. Select ▸ Update Selection replaces the objects of the saved selection last recalled with the selected objects, in one undo step that marks the document changed (`select.update`). After Edit Selection… renames that saved selection, Update Selection replaces it under the new name; after Edit Selection… deletes it, Update Selection is disabled until another saved selection is recalled or the delete is undone. Undo and Redo do not change which saved selection is recalled. - - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). + - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). The object drawn into becomes the clip group's clipping path and keeps its appearance, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) ([archived](https://web.archive.org/web/20261111110310/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) says Draw Inside clipping masks do: its fills paint behind the art drawn inside it and its strokes over that art, unclipped, so a centred stroke stays whole (#8753, `tests::file::draw_inside_keeps_the_objects_stroke_whole_and_over_the_new_art`). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). - **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; double-click, or Alt-click on any point but an end of an open path, toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). An Alt-click on an end of a selected open path makes that end current without changing it, so the next click goes on from it, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-shapes-with-the-curvature-tool.html) describes for continuing a path; an Alt-click that starts a new path places a corner point, as later Alt-clicks do. Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners. A filled Pencil path keeps a stroke of None (#1804, part of #1679). While a Pencil or Paintbrush stroke is drawn back to within Close Paths When Ends Are Within of its start, the cursor shows the closing ring and a release there closes the path, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes for the Pencil. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). Blob Brush and Eraser Tool Options' Size is Fixed or Pressure with a Variation (#4590, #3961): with Pressure a pen stroke is Size − Variation wide where it presses lightest and Size + Variation where it presses hardest, and a mouse stroke keeps the Size. `path.blob` and `path.eraseRegion` refuse a Size outside 0.1 to 1000 pt and a Variation outside 0 to 1000 pt, also with Size set to Fixed, and the drawing commands that read pen values refuse a pressure outside 0 to 1, a tilt outside −90° to 90°, a rotation outside 0° to 360° and a point array of more than six numbers, with an error naming the key; the document, the selection and the undo history stay as they were. The pressure and tilt ranges are those of [Pointer Events](https://www.w3.org/TR/pointerevents3/); the Size, Variation and rotation ranges are VectorCraft's own values (`tests::draw2::pen_values_outside_their_ranges_are_refused`). @@ -3144,6 +3144,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Draw Inside makes the object it draws into the clip group's clipping path, keeping its fill and stroke, instead of clipping by an unpainted copy of it: its centred stroke is no longer clipped by its own outline and paints over the art drawn inside it ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html), [archived](https://web.archive.org/web/20261111110310/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#8753). Scores and estimates unchanged. | | 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | | 2026-11-19 | minor | Guides, grids, smart guides, snapping, rulers: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out their Show/Hide items; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 911f08d192..b604980629 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Draw Inside keeps the object it draws into as the clip group's clipping path with its fill and stroke, so its stroke stays whole over the art drawn inside it, #8753; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -231,6 +231,7 @@ tools, never checked side by side) isn't captured row by row. | Smooth (Object › Path › Smooth…: slider from minimum to maximum smoothing, Auto-Smooth) ([smooth slider](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html)) | done | #4115: the slider under the selection previews `object.path.smooth {level}`, Auto-Smooth picks level 50 and takes a shaky line to one smooth curve, direct-selected anchors smooth only their section, Enter or a click outside keeps one undo step and Escape restores; the smoothing rule beyond the two ends is VectorCraft's own (`tests/smooth_path.rs`, `smooth_slider_previews_auto_smooth_and_keeps_the_result`) | | Draw Inside in isolation mode: art drawn or pasted inside the isolated object takes isolation mode into its clip group, clickable and undimmed ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html), [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | done | #3705; `drawing_inside_an_isolated_object_keeps_the_new_art_in_isolation_mode` | | Draw Inside marks the object it draws into: a dotted open rectangle round its corners, in its layer's colour, while the mode lasts, selected or not | done | #4319, `canvas::tests::draw_inside_marks_the_corners_of_its_object` ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | +| Draw Inside keeps the object it draws into as the clipping path with its appearance: its fills paint behind the art drawn inside it and its strokes over that art, unclipped | done | #8753, `tests::file::draw_inside_keeps_the_objects_stroke_whole_and_over_the_new_art` ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html), [archived](https://web.archive.org/web/20261111110310/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | | Simplify (slider, auto, corner angle threshold) | partial | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, and the dialog's option to open it directly with its last settings; the slider opens at 1 pt rather than at the Auto-Simplify level, and simplifying only a Direct Selection part of a path remains missing | | Simplify (slider, auto, corner angle threshold) | partial | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, opening at the Auto-Simplify level for the selection with that result previewed, and the dialog's option to open it directly with its last settings; simplifying only a Direct Selection part of a path remains missing | @@ -626,6 +627,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Draw Inside makes the object it draws into the clip group's clipping path, keeping its fill and stroke, instead of clipping by an unpainted copy of it: its centred stroke is no longer clipped by its own outline and paints over the art drawn inside it ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html), [archived](https://web.archive.org/web/20261111110310/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#8753). Scores and estimates unchanged. | | 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible, with a smaller appearance dot inside it and a gap between them, so not targeted, targeted, with an appearance and both look different, as the target icons in [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) (Targeting items for appearance attributes) do. Before, the dot covered the ring and a targeted item with an appearance looked untargeted, #8711. Scores and estimates unchanged. | | 2026-11-19 | minor | View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid until it is off; the choices come back as they were and the rulers stay, though dragging or double-clicking them makes no guide meanwhile (#8363). Scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | From 9ffec7e72d57b8aec80d46b9e6e7efbf686b581d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:07:11 -0800 Subject: [PATCH 02/88] Scripts: perspective grid members and getPresetSettings for scripts A document in the script object model can now show and hide its perspective grid, read and set the active plane, and reset the grid to a built-in or saved preset, as the Document page lists them (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). The values come from the PerspectiveGridType and PerspectiveGridPlaneType enumerations on the scripting constants page. app.getPresetSettings returns a new DocumentPreset with the settings that a document made from the named startup preset starts with, and addDocument accepts it back without changes. - showPerspectiveGrid, hidePerspectiveGrid and setActivePlane run perspective.grid.show and perspective.plane.set. They add no undo step, and a failed run restores the grid. A run that only changes the grid's view state no longer adds an undo step. A run in which a command records its own undo step still adds one. - selectPerspectivePreset throws, and leaves the grid unchanged, when the preset name is not listed, when the preset's grid is not of gridType, when gridType is InvalidPerspectiveGridType, and when the name is longer than 4,096 bytes. A one-point grid accepts only the left and floor planes. - The workspace methods, loadColorSettings, showPresets and the perspective grid preset file methods throw an error that says they are not available yet. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/distortcmds.rs | 4 +- .../engine/src/cmd/distortcmds/perspective.rs | 29 ++ crates/engine/src/cmd/newdoc.rs | 2 +- crates/engine/src/script/dom.rs | 7 + crates/engine/src/script/dom/perspective.rs | 252 ++++++++++++++++ crates/engine/src/script/mod.rs | 6 +- crates/engine/src/tests.rs | 1 + .../src/tests/script_dom_perspective.rs | 282 ++++++++++++++++++ docs/mcp.md | 26 ++ docs/target-app-parity.md | 1 + 10 files changed, 607 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/script/dom/perspective.rs create mode 100644 crates/engine/src/tests/script_dom_perspective.rs diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index dc36e24380..516547d1a6 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -26,7 +26,9 @@ pub use perspective::perspective_click; use perspective::{ attach, edit_text, grid_set, grid_show, persp_draw, persp_move, persp_nudge, persp_transform, plane_match, plane_move, plane_set, release, }; -pub(crate) use perspective::{finish_edit_text, grid_kept, grid_of, perspective_rewrite, silent, store_grid, transform_again}; +pub(crate) use perspective::{ + finish_edit_text, grid_kept, grid_of, only_grid_view_changed, perspective_rewrite, silent, store_grid, transform_again, +}; pub fn specs() -> Vec { vec![ diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 90d58541a6..89b2327e59 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -24,6 +24,35 @@ pub(crate) fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool { serde_json::to_value(&g).is_ok_and(|v| d.unknown.get(persp::DOC_KEY) == Some(&v)) } +/// Whether `now` differs from `before` only in the view state of its perspective grid (whether it +/// shows, the active plane, the point Automatic Plane Positioning holds and the view options), the +/// changes [`silent`] makes without an undo step. +pub(crate) fn only_grid_view_changed(now: &Document, before: &Document) -> bool { + let (a, b) = (now.unknown.get(persp::DOC_KEY), before.unknown.get(persp::DOC_KEY)); + if a == b { + return false; + } + let (mut g, mut was) = (PerspectiveGrid::current(now), PerspectiveGrid::current(before)); + g.visible = was.visible; + g.plane = was.plane; + g.inferred = was.inferred; + g.locked = was.locked; + g.lock_station = was.lock_station; + g.snap = was.snap; + g.rulers = was.rulers; + g.attached.clear(); + was.attached.clear(); + if serde_json::to_value(&g).ok() != serde_json::to_value(&was).ok() { + return false; + } + let mut rest = now.clone(); + match b { + Some(v) => rest.unknown.insert(persp::DOC_KEY.to_string(), v.clone()), + None => rest.unknown.remove(persp::DOC_KEY), + }; + rest == *before +} + /// Change view state of the grid without an undo step. pub(crate) fn silent(s: &mut Session, f: impl FnOnce(&mut PerspectiveGrid)) -> Result { let st = s.doc_mut()?; diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 983ef4041d..b0de09d251 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -801,7 +801,7 @@ pub fn find(s: &Session, name: &str) -> Option { impl Session { /// New Document's starting settings: Letter in Preferences ▸ Units ▸ General. - fn default_settings(&self) -> DocSettings { + pub(crate) fn default_settings(&self) -> DocSettings { DocSettings { units: self.default_units(), ..DocSettings::default() } } } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index fadaeb133d..e0a09054fc 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -39,6 +39,7 @@ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current use crate::{DocState, Document, NodeId, NodeKind, Session}; pub(super) mod layers; +mod perspective; /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; @@ -1718,6 +1719,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } + for (name, members) in perspective::enums() { + let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + realm.define_host_object(name, items)?; + } let l = link; let mut application = named(vec![ ("typename", typename_of("Application")), @@ -1728,6 +1733,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("getIsFileOpen", method(l, app_is_open)), ]); application.push(later(l, "Application", "beep")); + application.extend(perspective::application_members(l)); let preset = { let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { @@ -1769,6 +1775,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ]); document.extend(["pathItems", "textFrames", "swatches", "symbols", "views", "saveAs", "close"].into_iter().map(|m| later(l, "Document", m))); document.extend(layers::document_members(l)); + document.extend(perspective::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", diff --git a/crates/engine/src/script/dom/perspective.rs b/crates/engine/src/script/dom/perspective.rs new file mode 100644 index 0000000000..3a0bd6bf40 --- /dev/null +++ b/crates/engine/src/script/dom/perspective.rs @@ -0,0 +1,252 @@ +//! The perspective grid of a document and the New Document settings of a startup preset in the +//! script object model, as the help pages +//! and list them, with the values of +//! . +//! +//! `showPerspectiveGrid`, `hidePerspectiveGrid` and `setActivePlane` change view state with +//! `perspective.grid.show` and `perspective.plane.set`: no undo step, and a failed run puts them +//! back with the document. `selectPerspectivePreset` runs `perspective.grid.preset`, which shows +//! the grid and makes one undo step when the grid's geometry changes. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `selectPerspectivePreset(gridType, presetName)` throws when no built-in or saved preset has +//! that name (in any case), and when the preset's grid is not of `gridType`; nothing changes then. +//! - A one-point grid takes only the left and the floor plane as its active plane, as the archived +//! scripting guide says +//! (). +//! `INVALIDGRIDPLANETYPE` makes no plane active. +//! - `showPerspectiveGrid` and `setActivePlane` give `true`, also when nothing changed; +//! `hidePerspectiveGrid` gives `false` when the grid was already hidden. +//! - `getPresetSettings(preset)` takes the names `documents.addDocument` takes, and gives a new +//! `DocumentPreset` with the settings a new document from that preset starts with, which +//! `addDocument` takes back unchanged (settings it cannot take, such as other units or more than +//! 100 artboards, are left out); changing it changes nothing else. +//! - The workspace methods, `loadColorSettings`, `showPresets` and the perspective grid preset +//! files are not available yet. + +use serde_json::json; +use vectorcraft_js::{Data, HostError, HostMember}; +use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane}; + +use super::{Answer, MAX_TEXT_BYTES, arg, later, method, named, num, on_doc, startup_preset, text, this_doc, with_doc}; +use crate::script::{Host, Link}; + +type Result = std::result::Result; + +/// The `PerspectiveGridType` values, with the grid kind (`perspective.grid.set`'s `kind`) of each. +const GRID_TYPES: &[(&str, Option)] = &[ + ("OnePointPerspectiveGridType", Some(1)), + ("TwoPointPerspectiveGridType", Some(2)), + ("ThreePointPerspectiveGridType", Some(3)), + ("InvalidPerspectiveGridType", None), +]; + +/// The `PerspectiveGridPlaneType` values, with the plane of each. +const PLANE_TYPES: &[(&str, Plane)] = &[ + ("GRIDLEFTPLANETYPE", Plane::Left), + ("GRIDRIGHTPLANETYPE", Plane::Right), + ("GRIDFLOORPLANETYPE", Plane::Ground), + ("INVALIDGRIDPLANETYPE", Plane::None), +]; + +/// The enumerations this module adds, as `dom::install` defines them. +pub(super) fn enums() -> Vec<(&'static str, Vec<&'static str>)> { + vec![ + ("PerspectiveGridType", GRID_TYPES.iter().map(|(n, _)| *n).collect()), + ("PerspectiveGridPlaneType", PLANE_TYPES.iter().map(|(n, _)| *n).collect()), + ] +} + +/// The kind a `PerspectiveGridType` value names (`None`: `InvalidPerspectiveGridType`). +fn grid_type(d: &Data) -> Result> { + let found = match d { + Data::String(s) => s.strip_prefix("PerspectiveGridType.").and_then(|m| GRID_TYPES.iter().find(|(n, _)| *n == m)), + _ => None, + }; + found.map(|(_, k)| *k).ok_or_else(|| HostError::Type("gridType must be a PerspectiveGridType value".into())) +} + +/// The plane a `PerspectiveGridPlaneType` value names. +fn plane_type(d: &Data) -> Result { + let found = match d { + Data::String(s) => s.strip_prefix("PerspectiveGridPlaneType.").and_then(|m| PLANE_TYPES.iter().find(|(n, _)| *n == m)), + _ => None, + }; + found.map(|(_, p)| *p).ok_or_else(|| HostError::Type("gridPlane must be a PerspectiveGridPlaneType value".into())) +} + +/// The document `this` names and its perspective grid. +fn grid(h: &Host, a: &[Data]) -> Result<(super::Doc, PerspectiveGrid)> { + let doc = this_doc(h, a)?; + Ok((doc, with_doc(h, doc, |_, st| PerspectiveGrid::effective(&st.doc)))) +} + +/// `showPerspectiveGrid()`: shows the document's grid (its default one when none was defined). +fn show_grid(h: &Host, a: &[Data]) -> Answer { + let (doc, g) = grid(h, a)?; + if !g.visible { + on_doc(h, doc.uid, false, |h| super::command(h, "perspective.grid.show", &json!({"visible": true})))?; + } + Ok(Data::Bool(true)) +} + +/// `hidePerspectiveGrid()`: hides the document's grid. → whether a grid was hidden. +fn hide_grid(h: &Host, a: &[Data]) -> Answer { + let (doc, g) = grid(h, a)?; + if !g.visible { + return Ok(Data::Bool(false)); + } + on_doc(h, doc.uid, false, |h| super::command(h, "perspective.grid.show", &json!({"visible": false})))?; + Ok(Data::Bool(true)) +} + +/// `getPerspectiveActivePlane()`: the grid's active plane, shown or hidden. +fn active_plane(h: &Host, a: &[Data]) -> Answer { + let (_, g) = grid(h, a)?; + let name = PLANE_TYPES.iter().find(|(_, p)| *p == g.plane).map_or("INVALIDGRIDPLANETYPE", |(n, _)| *n); + Ok(text(format!("PerspectiveGridPlaneType.{name}"))) +} + +/// `setActivePlane(gridPlane)`: makes `gridPlane` the grid's active plane. +fn set_active_plane(h: &Host, a: &[Data]) -> Answer { + let plane = plane_type(arg(a, 1))?; + let (doc, g) = grid(h, a)?; + if g.kind == 1 && plane == Plane::Right { + return Err(HostError::Range("a one-point grid has no right plane to make active".into())); + } + if g.plane != plane { + on_doc(h, doc.uid, false, |h| super::command(h, "perspective.plane.set", &json!({"plane": plane.id()})))?; + } + Ok(Data::Bool(true)) +} + +/// `selectPerspectivePreset(gridType, presetName)`: resets the grid to the preset `presetName`, +/// which must be a grid of `gridType`. +fn select_preset(h: &Host, a: &[Data]) -> Answer { + let kind = grid_type(arg(a, 1))?.ok_or_else(|| HostError::Range("InvalidPerspectiveGridType has no presets".into()))?; + let Data::String(name) = arg(a, 2) else { return Err(HostError::Type("presetName must be a string".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the preset's name is too long".into())); + } + let doc = this_doc(h, a)?; + let preset = h.session.borrow().perspective_preset(name); + let preset = preset.ok_or_else(|| HostError::Error(format!("no perspective grid preset called {name}")))?; + if preset.kind != kind { + return Err(HostError::Error(format!("the preset {} is not a grid of that type", preset.name))); + } + on_doc(h, doc.uid, false, |h| super::command(h, "perspective.grid.preset", &json!({"name": preset.name})))?; + Ok(Data::Bool(true)) +} + +/// The `RulerUnits` value of `u`, for the units `documents.addDocument` takes (`None`: other units, +/// which a preset given back to `addDocument` keeps by leaving `units` out). +fn units(u: crate::doc::Unit) -> Option<&'static str> { + use crate::doc::Unit; + Some(match u { + Unit::Points => "RulerUnits.Points", + Unit::Picas => "RulerUnits.Picas", + Unit::Inches => "RulerUnits.Inches", + Unit::Millimeters => "RulerUnits.Millimeters", + Unit::Centimeters => "RulerUnits.Centimeters", + Unit::Pixels => "RulerUnits.Pixels", + _ => return None, + }) +} + +/// `artboardRowsOrCols` as `addDocument` reads it: the rows of a grid filled by column and the +/// columns of the other layouts. `None`: a grid by column whose artboards no row count places the +/// same. +fn rows_or_cols(d: &crate::cmd::newdoc::DocSettings) -> Option { + use crate::cmd::newdoc::ArtboardLayout; + let n = d.artboards.max(1) as usize; + if d.layout != ArtboardLayout::GridByColumn { + return Some(d.grid_columns().max(1)); + } + if d.rows > 0 { + return Some((d.rows as usize).min(n)); + } + let rows = n.div_ceil(d.grid_columns().max(1)); + let by_rows = crate::cmd::newdoc::DocSettings { rows: u32::try_from(rows).ok()?, ..d.clone() }; + (by_rows.boards() == d.boards()).then_some(rows) +} + +/// `app.getPresetSettings(preset)`: a new `DocumentPreset` with the settings a document from the +/// startup preset `preset` starts with. +fn preset_settings(h: &Host, a: &[Data]) -> Answer { + use crate::cmd::newdoc::{ArtboardLayout, PreviewMode}; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("getPresetSettings needs a startup preset's name".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the startup preset's name is too long".into())); + } + let (profile, mode) = startup_preset(name).ok_or_else(|| HostError::Error(format!("no startup preset called {name}")))?; + // The settings `documents.addDocument` starts from: the first preset of the profile's category + // (found by name, as `file.new` finds it), else New Document's starting settings. + let d = { + let s = h.session.borrow(); + let first = profile.and_then(|n| crate::cmd::newdoc::category(&s, n)?.into_iter().next()); + first.map_or_else(|| s.default_settings(), |f| crate::cmd::newdoc::find(&s, &f.name).unwrap_or(f)) + }; + let cmyk = mode.map_or(d.color_mode == crate::doc::ColorMode::Cmyk, |m| m == "cmyk"); + let layout = match (d.layout, d.right_to_left) { + (ArtboardLayout::GridByRow, false) => "GridByRow", + (ArtboardLayout::GridByColumn, false) => "GridByCol", + (ArtboardLayout::Row, false) => "Row", + (ArtboardLayout::Column, _) => "Column", + (ArtboardLayout::GridByRow, true) => "RLGridByRow", + (ArtboardLayout::GridByColumn, true) => "RLGridByCol", + (ArtboardLayout::Row, true) => "RLRow", + }; + let preview = match d.preview_mode { + PreviewMode::Default => "DefaultPreview", + PreviewMode::Pixel => "PixelPreview", + PreviewMode::Overprint => "OverprintPreview", + }; + let item = |k: &str, v: Data| (k.to_string(), v); + let mut out = vec![ + item("typename", text("DocumentPreset")), + item("artboardLayout", text(format!("DocumentArtboardLayout.{layout}"))), + item("artboardSpacing", num(d.spacing)), + item("colorMode", text(if cmyk { "DocumentColorSpace.CMYK" } else { "DocumentColorSpace.RGB" })), + item("height", num(d.height)), + item("previewMode", text(format!("DocumentPreviewMode.{preview}"))), + item("width", num(d.width)), + ]; + // The artboard count and `artboardRowsOrCols` are left out when `addDocument` cannot take them + // back exactly (more than `MAX_ARTBOARDS`, or a grid by column set by its columns that no row + // count lays out the same), so `addDocument` with the same preset keeps the preset's own. + if f64::from(d.artboards.max(1)) <= super::MAX_ARTBOARDS { + out.push(item("numArtboards", num(f64::from(d.artboards.max(1))))); + if let Some(n) = rows_or_cols(&d) { + out.push(item("artboardRowsOrCols", num(super::float(n as u64)))); + } + } + if let Some(u) = units(d.units) { + out.push(item("units", text(u))); + } + let resolutions = [(72.0, "ScreenResolution"), (150.0, "MediumResolution"), (300.0, "HighResolution")]; + if let Some((_, r)) = resolutions.iter().find(|(ppi, _)| (d.raster_effects_ppi - ppi).abs() < 1e-9) { + out.push(item("rasterResolution", text(format!("DocumentRasterResolution.{r}")))); + } + Ok(Data::Object(out)) +} + +/// The members this module adds to `Document`'s. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + let mut m = named(vec![ + ("showPerspectiveGrid", method(l, show_grid)), + ("hidePerspectiveGrid", method(l, hide_grid)), + ("getPerspectiveActivePlane", method(l, active_plane)), + ("setActivePlane", method(l, set_active_plane)), + ("selectPerspectivePreset", method(l, select_preset)), + ]); + m.extend(["exportPerspectiveGridPreset", "importPerspectiveGridPreset"].into_iter().map(|n| later(l, "Document", n))); + m +} + +/// The members this module adds to `Application`'s. +pub(super) fn application_members(l: &Link) -> Vec<(String, HostMember)> { + let mut m = named(vec![("getPresetSettings", method(l, preset_settings))]); + let missing = ["saveWorkspace", "switchWorkspace", "deleteWorkspace", "resetWorkspace", "loadColorSettings", "showPresets"]; + m.extend(missing.into_iter().map(|n| later(l, "Application", n))); + m +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 34779c7b5e..6292be8727 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2249,7 +2249,11 @@ impl Session { changed_names.push(st.title()); continue; }; - let changed = !st.same_content(&b.doc); + // The perspective grid's view state changes without an undo step, as it does outside a + // run, when no command in the run recorded an undo step of its own on the working copy. + let (now, was) = (&st.history.undo, &b.history.undo); + let recorded = now.len() != was.len() || !now.last().zip(was.last()).map_or(now.is_empty(), |(x, y)| Arc::ptr_eq(&x.doc, &y.doc)); + let changed = !st.same_content(&b.doc) && (recorded || !cmd::distortcmds::only_grid_view_changed(&st.doc, &b.doc)); st.history = std::mem::take(&mut b.history); st.recovery.clone_from(&b.recovery); if changed { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index adcaefd59d..4736063a3a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -173,6 +173,7 @@ mod script_console; mod script_dialogs; mod script_dollar; mod script_dom; +mod script_dom_perspective; mod script_engines; mod script_folder; mod script_include; diff --git a/crates/engine/src/tests/script_dom_perspective.rs b/crates/engine/src/tests/script_dom_perspective.rs new file mode 100644 index 0000000000..c9398ffd4c --- /dev/null +++ b/crates/engine/src/tests/script_dom_perspective.rs @@ -0,0 +1,282 @@ +//! The script object model's perspective grid members and `app.getPresetSettings`. + +use serde_json::{Value, json}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +fn grid(s: &mut Session) -> Value { + s.execute("perspective.grid.get", &json!({})).unwrap()["grid"].clone() +} + +#[test] +fn show_and_hide_change_the_view_without_an_undo_step() { + let mut s = doc(); + let before = undo_steps(&s); + let out = + log(&mut s, "var d = app.activeDocument; vc.log(d.hidePerspectiveGrid()); vc.log(d.showPerspectiveGrid()); vc.log(d.showPerspectiveGrid());"); + assert_eq!(out, vec![json!(false), json!(true), json!(true)]); + assert_eq!(grid(&mut s)["visible"], true); + assert_eq!(undo_steps(&s), before); + let out = log(&mut s, "var d = app.activeDocument; vc.log(d.hidePerspectiveGrid()); vc.log(d.hidePerspectiveGrid());"); + assert_eq!(out, vec![json!(true), json!(false)]); + assert_eq!(grid(&mut s)["visible"], false); + assert_eq!(undo_steps(&s), before); +} + +#[test] +fn grid_view_commands_in_a_run_add_no_undo_step_but_an_edit_still_does() { + let mut s = doc(); + let before = undo_steps(&s); + run(&mut s, "vc.run('perspective.grid.show', {visible: true}); vc.run('perspective.plane.set', {plane: 'ground'});").unwrap(); + assert_eq!((grid(&mut s)["visible"].clone(), grid(&mut s)["plane"].clone()), (json!(true), json!("ground"))); + assert_eq!(undo_steps(&s), before); + run(&mut s, "app.activeDocument.hidePerspectiveGrid(); vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});").unwrap(); + assert_eq!(undo_steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(grid(&mut s)["visible"], true); +} + +#[test] +fn a_grid_edit_that_changes_only_view_fields_keeps_its_undo_step_in_a_run() { + let mut s = doc(); + let before = undo_steps(&s); + s.execute("perspective.grid.set", &json!({"locked": true})).unwrap(); + assert_eq!(undo_steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + let mut s = doc(); + let source = "vc.run('perspective.grid.set', {locked: true}); app.activeDocument.setActivePlane(PerspectiveGridPlaneType.GRIDFLOORPLANETYPE);"; + run(&mut s, source).unwrap(); + assert_eq!(undo_steps(&s), before + 1); + assert_eq!((grid(&mut s)["locked"].clone(), grid(&mut s)["plane"].clone()), (json!(true), json!("ground"))); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!grid(&mut s).get("locked").and_then(Value::as_bool).unwrap_or(false)); +} + +#[test] +fn the_active_plane_round_trips_and_a_failed_run_puts_it_back() { + let mut s = doc(); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log(d.getPerspectiveActivePlane());\ + vc.log(d.setActivePlane(PerspectiveGridPlaneType.GRIDFLOORPLANETYPE)); vc.log(d.getPerspectiveActivePlane());\ + d.setActivePlane(PerspectiveGridPlaneType.INVALIDGRIDPLANETYPE); vc.log(d.getPerspectiveActivePlane());", + ); + let expected = ["PerspectiveGridPlaneType.GRIDLEFTPLANETYPE", "PerspectiveGridPlaneType.GRIDFLOORPLANETYPE"]; + assert_eq!(out[..3], [json!(expected[0]), json!(true), json!(expected[1])]); + assert_eq!(out[3], json!("PerspectiveGridPlaneType.INVALIDGRIDPLANETYPE")); + assert_eq!(grid(&mut s)["plane"], "none"); + failure(&mut s, "var d = app.activeDocument; d.setActivePlane(PerspectiveGridPlaneType.GRIDRIGHTPLANETYPE); d.showPerspectiveGrid(); throw 1;"); + assert_eq!(grid(&mut s)["plane"], "none"); + assert_eq!(grid(&mut s)["visible"], false); +} + +#[test] +fn a_bad_plane_or_a_right_plane_on_a_one_point_grid_throws() { + let mut s = doc(); + for bad in ["'left'", "0", "PerspectiveGridType.OnePointPerspectiveGridType", "undefined"] { + let e = failure(&mut s, &format!("app.activeDocument.setActivePlane({bad});")); + assert!(e.contains("PerspectiveGridPlaneType"), "{bad}: {e}"); + } + s.execute("perspective.grid.preset", &json!({"kind": 1})).unwrap(); + let e = failure(&mut s, "app.activeDocument.setActivePlane(PerspectiveGridPlaneType.GRIDRIGHTPLANETYPE);"); + assert!(e.contains("one-point grid"), "{e}"); + assert_eq!(grid(&mut s)["plane"], "left"); + let out = log( + &mut s, + "var d = app.activeDocument; d.setActivePlane(PerspectiveGridPlaneType.GRIDFLOORPLANETYPE); vc.log(d.getPerspectiveActivePlane());", + ); + assert_eq!(out, vec![json!("PerspectiveGridPlaneType.GRIDFLOORPLANETYPE")]); +} + +#[test] +fn select_perspective_preset_checks_the_type_and_the_name() { + let mut s = doc(); + let one = s.execute("perspective.presets.list", &json!({})).unwrap()["presets"] + .as_array() + .unwrap() + .iter() + .find(|p| p["kind"] == 1) + .map(|p| p["name"].as_str().unwrap().to_string()) + .unwrap(); + let before = undo_steps(&s); + for (call, message) in [ + (format!("PerspectiveGridType.TwoPointPerspectiveGridType, '{one}'"), "not a grid of that type"), + (format!("PerspectiveGridType.InvalidPerspectiveGridType, '{one}'"), "has no presets"), + ("PerspectiveGridType.OnePointPerspectiveGridType, 'No Such Preset'".to_string(), "no perspective grid preset called"), + (format!("'one', '{one}'"), "PerspectiveGridType value"), + ("PerspectiveGridType.OnePointPerspectiveGridType, 7".to_string(), "presetName must be a string"), + (format!("PerspectiveGridType.OnePointPerspectiveGridType, '{}'", "x".repeat(5000)), "too long"), + ] { + let e = failure(&mut s, &format!("app.activeDocument.selectPerspectivePreset({call});")); + assert!(e.contains(message), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), before); + assert_eq!(grid(&mut s)["kind"], 2); + let out = log( + &mut s, + &format!("vc.log(app.activeDocument.selectPerspectivePreset(PerspectiveGridType.OnePointPerspectiveGridType, '{}'));", one.to_uppercase()), + ); + assert_eq!(out, vec![json!(true)]); + let g = grid(&mut s); + assert_eq!((g["kind"].clone(), g["visible"].clone()), (json!(1), json!(true))); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn hostile_names_and_numbers_throw_with_nothing_changed() { + let mut s = doc(); + s.execute("perspective.presets.save", &json!({"name": "Mine"})).unwrap(); + let before = (undo_steps(&s), grid(&mut s)); + for name in ["../Mine", "..\\\\Mine", "/Mine", "C:\\\\Mine", "Mine/..", "Mi\\u0000ne", "~/Mine"] { + for call in [ + format!("app.activeDocument.selectPerspectivePreset(PerspectiveGridType.TwoPointPerspectiveGridType, '{name}');"), + format!("app.getPresetSettings('{name}');"), + ] { + let e = failure(&mut s, &call); + assert!(e.contains("no perspective grid preset called") || e.contains("no startup preset called"), "{call}: {e}"); + } + } + // The script host refuses a number that is not finite before the member runs. + for value in ["NaN", "Infinity", "-1e308", "1e308", "2"] { + let refused = |e: &str, message: &str| e.contains(message) || e.contains("is not a finite number"); + let e = failure(&mut s, &format!("app.activeDocument.selectPerspectivePreset({value}, 'Mine');")); + assert!(refused(&e, "PerspectiveGridType value"), "{value}: {e}"); + let e = failure(&mut s, &format!("app.activeDocument.setActivePlane({value});")); + assert!(refused(&e, "PerspectiveGridPlaneType value"), "{value}: {e}"); + let e = failure(&mut s, &format!("app.activeDocument.selectPerspectivePreset(PerspectiveGridType.TwoPointPerspectiveGridType, {value});")); + assert!(refused(&e, "presetName must be a string"), "{value}: {e}"); + } + assert_eq!((undo_steps(&s), grid(&mut s)), before); +} + +#[test] +fn a_closed_document_throws_on_every_grid_member() { + let mut s = doc(); + run(&mut s, "#targetengine keep\nvar held = app.activeDocument;").unwrap(); + let e = failure(&mut s, "#targetengine keep\nheld.showPerspectiveGrid();"); + assert!(e.contains("Stale document"), "{e}"); + let e = failure(&mut s, "var d = app.activeDocument; vc.run('file.close', {}); d.hidePerspectiveGrid();"); + assert!(e.contains("Stale document"), "{e}"); + let e = failure(&mut s, "Document.prototype.getPerspectiveActivePlane.call({});"); + assert!(e.contains("not a Document"), "{e}"); +} + +#[test] +fn get_preset_settings_gives_a_copy_add_document_takes() { + let mut s = Session::new(); + let out = log( + &mut s, + "var p = app.getPresetSettings('Basic CMYK'); vc.log(p.typename); vc.log(p.colorMode); vc.log(p.width); vc.log(p.height);\ + vc.log(p.numArtboards); p.width = 100; vc.log(app.getPresetSettings('Basic CMYK').width);\ + var d = app.documents.addDocument('Basic CMYK', p); vc.log(d.width); vc.log(d.documentColorSpace);\ + vc.log(app.getPresetSettings(DocumentPresetType.BasicRGB).colorMode);", + ); + let expected = [json!("DocumentPreset"), json!("DocumentColorSpace.CMYK"), json!(612), json!(792), json!(1), json!(612)]; + assert_eq!(out[..6], expected); + assert_eq!(out[6..], [json!(100), json!("DocumentColorSpace.CMYK"), json!("DocumentColorSpace.RGB")]); + for (call, message) in [("'No Such Preset'", "no startup preset called"), ("3", "startup preset's name"), ("undefined", "startup preset's name")] + { + let e = failure(&mut s, &format!("app.getPresetSettings({call});")); + assert!(e.contains(message), "{call}: {e}"); + } + let e = failure(&mut s, &format!("app.getPresetSettings('{}');", "x".repeat(5000))); + assert!(e.contains("too long"), "{e}"); +} + +#[test] +fn get_preset_settings_of_a_profile_gives_what_add_document_starts_from() { + let mut s = Session::new(); + for preset in ["Video", "Web", "Mobile", "Print", "DocumentPresetType.Video"] { + let out = log( + &mut s, + &format!( + "var p = app.getPresetSettings('{preset}'); var d = app.documents.addDocument('{preset}');\ + vc.log([p.width, p.height, p.units, p.colorMode]); vc.log([d.width, d.height, d.rulerUnits, d.documentColorSpace]);" + ), + ); + assert_eq!(out[0], out[1], "{preset}"); + } + let out = log(&mut s, "var p = app.getPresetSettings('Video'); vc.log([p.width, p.height]);"); + assert_ne!(out[0], json!([612, 792])); +} + +#[test] +fn get_preset_settings_given_back_to_add_document_makes_the_same_document() { + let mut s = Session::new(); + s.execute("prefs.set", &json!({"key": "unitsGeneral", "value": "feet"})).unwrap(); + let layout = json!({"layout": "gridByColumn", "rows": 3, "spacing": 30}); + s.execute("file.newPresets.save", &json!({"name": "Letter", "artboards": 5, "artboardLayout": layout})).unwrap(); + let out = log( + &mut s, + "var p = app.getPresetSettings('Print'); vc.log(p.artboardRowsOrCols); vc.log(p.units === undefined);\ + function boards(d) { var r = []; for (var i = 0; i < d.artboards.length; i++) r.push(d.artboards[i].artboardRect); return r; }\ + var a = app.documents.addDocument('Print'); var b = app.documents.addDocument('Print', p);\ + vc.log(boards(a)); vc.log(boards(b)); vc.log(a.rulerUnits === b.rulerUnits);", + ); + assert_eq!(out[..2], [json!(3), json!(true)]); + assert_eq!(out[2], out[3]); + assert_eq!(out[2].as_array().map(Vec::len), Some(5)); + assert_eq!(out[4], json!(true)); + // Settings a DocumentPreset cannot hold are left out, and addDocument keeps the preset's own. + for (artboards, layout, has_count, has_rows) in [ + (6, json!({"layout": "gridByColumn", "columns": 4}), true, true), + (5, json!({"layout": "gridByColumn", "columns": 4, "spacing": 7.3}), true, true), + (6, json!({"layout": "gridByColumn", "columns": 3}), true, true), + (150, json!({"layout": "gridByRow", "columns": 12}), false, false), + (7, json!({"layout": "gridByRow", "columns": 3, "rightToLeft": true}), true, true), + ] { + s.execute("file.newPresets.save", &json!({"name": "Letter", "artboards": artboards, "artboardLayout": layout})).unwrap(); + let out = log( + &mut s, + "var p = app.getPresetSettings('Print'); vc.log(p.numArtboards !== undefined); vc.log(p.artboardRowsOrCols !== undefined);\ + function boards(d) { var r = []; for (var i = 0; i < d.artboards.length; i++) r.push(d.artboards[i].artboardRect); return r; }\ + vc.log(boards(app.documents.addDocument('Print'))); vc.log(boards(app.documents.addDocument('Print', p)));", + ); + assert_eq!(out[..2], [json!(has_count), json!(has_rows)], "{artboards} {layout}"); + assert_eq!(out[2].as_array().map(Vec::len), Some(artboards), "{layout}"); + assert_eq!(out[2], out[3], "{artboards} {layout}"); + } +} + +#[test] +fn members_not_built_yet_say_so() { + let mut s = doc(); + for (owner, member) in [ + ("app", "saveWorkspace"), + ("app", "switchWorkspace"), + ("app", "deleteWorkspace"), + ("app", "resetWorkspace"), + ("app", "loadColorSettings"), + ("app", "showPresets"), + ("app.activeDocument", "exportPerspectiveGridPreset"), + ("app.activeDocument", "importPerspectiveGridPreset"), + ] { + let e = failure(&mut s, &format!("{owner}.{member}('x');")); + assert!(e.contains(&format!("{member} is not available yet")), "{member}: {e}"); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 2b6b988f91..583af55a11 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2728,6 +2728,32 @@ app through the global object `vc`, and writes to the Script Console and runs ot `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and `GroupItems.createFromFile` throw an error that says they are not available yet. +- A document also has `showPerspectiveGrid()`, `hidePerspectiveGrid()`, `getPerspectiveActivePlane()`, + `setActivePlane(gridPlane)` and `selectPerspectivePreset(gridType, presetName)` + (https://ai-scripting.docsforadobe.dev/jsobjref/Document/), and `app` has `getPresetSettings(preset)` + (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `showPerspectiveGrid` and `hidePerspectiveGrid` + run `perspective.grid.show`, and `setActivePlane` runs `perspective.plane.set`; none of them adds an undo step, and + a failed run puts the grid back. `selectPerspectivePreset` runs `perspective.grid.preset` with a built-in or saved + preset of `perspective.presets.list` (its name in any case), which shows the grid and is part of the run's undo + step when the grid changes. The enumerations `PerspectiveGridType` (`OnePointPerspectiveGridType`, + `TwoPointPerspectiveGridType`, `ThreePointPerspectiveGridType`, `InvalidPerspectiveGridType`) and + `PerspectiveGridPlaneType` (`GRIDLEFTPLANETYPE`, `GRIDRIGHTPLANETYPE`, `GRIDFLOORPLANETYPE`, + `INVALIDGRIDPLANETYPE`) come from https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/. A + one-point grid takes only the left and the floor plane as its active plane, as the archived scripting guide + describes + (https://web.archive.org/web/20170622004549/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/AI_ScriptGd.pdf). + `getPresetSettings` takes the names `addDocument` takes and gives a new `DocumentPreset` with the settings a + document from that preset starts with, which `addDocument` takes back unchanged. It leaves out `units` when the + preset's units are not one of the six `RulerUnits` values a new document takes, and `numArtboards` and + `artboardRowsOrCols` when the preset has more than 100 artboards, so `addDocument` with the same preset keeps the + preset's own. + VectorCraft's own rules: `showPerspectiveGrid` and `setActivePlane` give `true`, and `hidePerspectiveGrid` gives + `false` when the grid was already hidden. `INVALIDGRIDPLANETYPE` makes no plane active. A preset name that is not + listed, a preset whose grid is not of `gridType`, `InvalidPerspectiveGridType` and a name of more than 4,096 bytes + throw an error with nothing changed. Changing the `DocumentPreset` `getPresetSettings` gives changes nothing else. + `app.saveWorkspace`, `switchWorkspace`, `deleteWorkspace`, `resetWorkspace`, `loadColorSettings` and + `showPresets`, and `Document.exportPerspectiveGridPreset` and `importPerspectiveGridPreset`, throw an error that + says they are not available yet. - `object.newGroup {parent?, index?}` adds an empty group to a shown, unlocked layer or group (`parent`; default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, index 0 puts it directly above the clipping path), as one undo step named Group, and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6edddf19b3..2d098d4977 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,6 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Paths, type and the other classes are not there yet, except that `CompoundPathItem.pathItems` reads the paths of a compound path. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks and new empty groups, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. + - Scripts: a document's perspective grid is shown, hidden, given its active plane and reset to a built-in or saved preset of the type the script names, and `app.getPresetSettings` gives the settings of a startup preset as a `DocumentPreset`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and https://ai-scripting.docsforadobe.dev/jsobjref/Application/ list them (`docs/mcp.md`). Showing, hiding and the active plane add no undo step in a script run, as outside one. Workspaces, `loadColorSettings`, `showPresets` and perspective grid preset files are not there yet. `crates/engine/src/tests/script_dom_perspective.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - 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`. From 8b31227089aca76ef50904eb309aac4e22194c26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:20:04 -0800 Subject: [PATCH 03/88] Scripts: docs give the grid members' return values and every omitted preset setting docs/mcp.md and the perspective module doc now say that the Document page describes the return values of showPerspectiveGrid, setActivePlane and hidePerspectiveGrid; only the true result when nothing changed is VectorCraft's own rule. They also list every setting getPresetSettings leaves out: rasterResolution for a PPI other than 72, 150 or 300, and artboardRowsOrCols for a grid by column that no row count lays out the same. --- crates/engine/src/script/dom/perspective.rs | 14 +++++++++----- docs/mcp.md | 13 ++++++++----- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/script/dom/perspective.rs b/crates/engine/src/script/dom/perspective.rs index 3a0bd6bf40..0df2dc3cfa 100644 --- a/crates/engine/src/script/dom/perspective.rs +++ b/crates/engine/src/script/dom/perspective.rs @@ -6,7 +6,10 @@ //! `showPerspectiveGrid`, `hidePerspectiveGrid` and `setActivePlane` change view state with //! `perspective.grid.show` and `perspective.plane.set`: no undo step, and a failed run puts them //! back with the document. `selectPerspectivePreset` runs `perspective.grid.preset`, which shows -//! the grid and makes one undo step when the grid's geometry changes. +//! the grid and makes one undo step when the grid's geometry changes. As the Document page +//! describes, `showPerspectiveGrid` and `setActivePlane` give `true` on success, and +//! `hidePerspectiveGrid` gives `true` when it hides a grid and `false` when the grid was already +//! hidden. //! //! VectorCraft's own rules, which the help pages do not state: //! - `selectPerspectivePreset(gridType, presetName)` throws when no built-in or saved preset has @@ -15,12 +18,13 @@ //! scripting guide says //! (). //! `INVALIDGRIDPLANETYPE` makes no plane active. -//! - `showPerspectiveGrid` and `setActivePlane` give `true`, also when nothing changed; -//! `hidePerspectiveGrid` gives `false` when the grid was already hidden. +//! - `showPerspectiveGrid` and `setActivePlane` also give `true` when nothing changed. //! - `getPresetSettings(preset)` takes the names `documents.addDocument` takes, and gives a new //! `DocumentPreset` with the settings a new document from that preset starts with, which -//! `addDocument` takes back unchanged (settings it cannot take, such as other units or more than -//! 100 artboards, are left out); changing it changes nothing else. +//! `addDocument` takes back unchanged. Settings it cannot take are left out: units other than +//! the six `RulerUnits` values, a PPI other than 72, 150 or 300, the artboard count and layout +//! of more than 100 artboards, and the layout of a grid by column that no row count lays out the +//! same. Changing the result changes nothing else. //! - The workspace methods, `loadColorSettings`, `showPresets` and the perspective grid preset //! files are not available yet. diff --git a/docs/mcp.md b/docs/mcp.md index 583af55a11..7cdca29574 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2744,11 +2744,14 @@ app through the global object `vc`, and writes to the Script Console and runs ot (https://web.archive.org/web/20170622004549/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/AI_ScriptGd.pdf). `getPresetSettings` takes the names `addDocument` takes and gives a new `DocumentPreset` with the settings a document from that preset starts with, which `addDocument` takes back unchanged. It leaves out `units` when the - preset's units are not one of the six `RulerUnits` values a new document takes, and `numArtboards` and - `artboardRowsOrCols` when the preset has more than 100 artboards, so `addDocument` with the same preset keeps the - preset's own. - VectorCraft's own rules: `showPerspectiveGrid` and `setActivePlane` give `true`, and `hidePerspectiveGrid` gives - `false` when the grid was already hidden. `INVALIDGRIDPLANETYPE` makes no plane active. A preset name that is not + preset's units are not one of the six `RulerUnits` values a new document takes, `rasterResolution` when the + preset's PPI is not 72, 150 or 300, `numArtboards` and `artboardRowsOrCols` when the preset has more than 100 + artboards, and `artboardRowsOrCols` alone for a grid by column that no row count lays out the same, so + `addDocument` with the same preset keeps the preset's own. As the Document page describes, + `showPerspectiveGrid` and `setActivePlane` give `true` on success, and `hidePerspectiveGrid` gives `true` when it + hides a grid and `false` when the grid was already hidden. + VectorCraft's own rules: `showPerspectiveGrid` and `setActivePlane` also give `true` when nothing changed. + `INVALIDGRIDPLANETYPE` makes no plane active. A preset name that is not listed, a preset whose grid is not of `gridType`, `InvalidPerspectiveGridType` and a name of more than 4,096 bytes throw an error with nothing changed. Changing the `DocumentPreset` `getPresetSettings` gives changes nothing else. `app.saveWorkspace`, `switchWorkspace`, `deleteWorkspace`, `resetWorkspace`, `loadColorSettings` and From 7ac929f2e4a8cc174d6541be03affba1c701c314 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 19:40:23 -0800 Subject: [PATCH 04/88] Scripts: a grid view run after an edit adds no undo step, host names listed A run that only showed the perspective grid or set its active plane added a Run Script undo step when the document already had an undo step, because the check compared the working copy's history with the document's own. The working copy starts with no undo steps, so the check now asks whether it holds any. The host name inventory lists the perspective grid enumerations and the new Application and Document members, including the setter rows of the members that are not available yet. --- crates/engine/src/script/mod.rs | 5 +++-- .../src/tests/script_dom_perspective.rs | 13 ++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 21 ++++++++++++------- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 6292be8727..c2c70ae0f8 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2251,8 +2251,9 @@ impl Session { }; // The perspective grid's view state changes without an undo step, as it does outside a // run, when no command in the run recorded an undo step of its own on the working copy. - let (now, was) = (&st.history.undo, &b.history.undo); - let recorded = now.len() != was.len() || !now.last().zip(was.last()).map_or(now.is_empty(), |(x, y)| Arc::ptr_eq(&x.doc, &y.doc)); + // The working copy starts with no undo steps (`World::working`), so any step it holds now + // was recorded in the run. + let recorded = !st.history.undo.is_empty(); let changed = !st.same_content(&b.doc) && (recorded || !cmd::distortcmds::only_grid_view_changed(&st.doc, &b.doc)); st.history = std::mem::take(&mut b.history); st.recovery.clone_from(&b.recovery); diff --git a/crates/engine/src/tests/script_dom_perspective.rs b/crates/engine/src/tests/script_dom_perspective.rs index c9398ffd4c..eebea33e7e 100644 --- a/crates/engine/src/tests/script_dom_perspective.rs +++ b/crates/engine/src/tests/script_dom_perspective.rs @@ -61,6 +61,19 @@ fn grid_view_commands_in_a_run_add_no_undo_step_but_an_edit_still_does() { assert_eq!(grid(&mut s)["visible"], true); } +#[test] +fn a_grid_view_run_after_an_edit_adds_no_undo_step() { + let mut s = doc(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + let before = undo_steps(&s); + let drawn = s.active().unwrap().doc.node_count(); + run(&mut s, "app.activeDocument.showPerspectiveGrid(); vc.run('perspective.plane.set', {plane: 'ground'});").unwrap(); + assert_eq!((grid(&mut s)["visible"].clone(), grid(&mut s)["plane"].clone()), (json!(true), json!("ground"))); + assert_eq!(undo_steps(&s), before); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.node_count(), drawn - 1); +} + #[test] fn a_grid_edit_that_changes_only_view_fields_keeps_its_undo_step_in_a_run() { let mut s = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 881cb64d04..95a8607329 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -42,7 +42,8 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// The names the host adds that stay inside the document and the run, by the object that has them. /// Reading a file or a folder, a file dialog and a message to the person do not change anything /// outside it. The document model (`app`, its classes and the enumerations) acts on the open -/// documents; `Document.saveAs` and `close` throw "not available yet". +/// documents; `Document.saveAs`, `close` and the perspective grid preset files, and the workspace +/// methods, `loadColorSettings` and `showPresets` of `Application`, throw "not available yet". const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), @@ -75,14 +76,16 @@ const INSIDE: &[(&str, &str)] = &[ "", "app Application Artboard Artboards CompoundPathItem CompoundPathItems CoordinateSystem Document \ DocumentArtboardLayout DocumentColorSpace DocumentPresetType DocumentPreviewMode DocumentRasterResolution \ - DocumentTransparencyGrid Documents ElementPlacement GroupItem GroupItems Layer Layers PageItem PageItems RulerUnits \ - ZOrderMethod", + DocumentTransparencyGrid Documents ElementPlacement GroupItem GroupItems Layer Layers PageItem PageItems \ + PerspectiveGridPlaneType PerspectiveGridType RulerUnits ZOrderMethod", ), ("Application.", "prototype"), ( "Application.prototype.", - "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= deleteWorkspace \ + deleteWorkspace= documents getIsFileOpen getPresetSettings loadColorSettings loadColorSettings= resetWorkspace \ + resetWorkspace= saveWorkspace saveWorkspace= selection showPresets showPresets= switchWorkspace switchWorkspace= \ + typename", ), ("Documents.", "prototype"), ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), @@ -90,8 +93,10 @@ const INSIDE: &[(&str, &str)] = &[ ( "Document.prototype.", "activeLayer activeLayer= artboards close close= compoundPathItems constructor convertCoordinate \ - documentColorSpace groupItems height layers name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ + documentColorSpace exportPerspectiveGridPreset exportPerspectiveGridPreset= getPerspectiveActivePlane groupItems \ + height hidePerspectiveGrid importPerspectiveGridPreset importPerspectiveGridPreset= layers name pageItems parent \ + pathItems pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selectPerspectivePreset selection \ + selection= setActivePlane showPerspectiveGrid swatches swatches= symbols symbols= textFrames textFrames= typename \ views views= width", ), ("Layer.", "prototype"), @@ -153,6 +158,8 @@ const INSIDE: &[(&str, &str)] = &[ TransparencyGridNone TransparencyGridOrange TransparencyGridPurple TransparencyGridRed", ), ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), + ("PerspectiveGridPlaneType.", "GRIDFLOORPLANETYPE GRIDLEFTPLANETYPE GRIDRIGHTPLANETYPE INVALIDGRIDPLANETYPE"), + ("PerspectiveGridType.", "InvalidPerspectiveGridType OnePointPerspectiveGridType ThreePointPerspectiveGridType TwoPointPerspectiveGridType"), ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ]; From cf181a0a4256cd3b6967e2573e44a48c4d038355 Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Sun, 22 Nov 2026 12:26:17 +0500 Subject: [PATCH 05/88] docs: Draw Inside keeps fills and strokes; effects are cut at the outline --- 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 1a1e341131..44416babd9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1429,7 +1429,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Compound paths:** Make keeps the backmost object's appearance and each contour; selecting a member in Direct Selection reads and changes the compound's fill rule in Attributes. Direction remains a per-member edit. Rendered holes, unchanged contour geometry, no-op history and Undo/Redo are covered by `engine/tests/it/compound_attributes.rs` (#1197). Behaviour reference: [public compound-path documentation](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-paths.html). Make Compound Path on a group (such as outlined type) keeps the paint of its backmost path instead of drawing nothing, and compound paths joined into one keep their holes (#1537). - **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. Select ▸ Update Selection replaces the objects of the saved selection last recalled with the selected objects, in one undo step that marks the document changed (`select.update`). After Edit Selection… renames that saved selection, Update Selection replaces it under the new name; after Edit Selection… deletes it, Update Selection is disabled until another saved selection is recalled or the delete is undone. Undo and Redo do not change which saved selection is recalled. - - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). The object drawn into becomes the clip group's clipping path and keeps its appearance, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) ([archived](https://web.archive.org/web/20261111110310/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) says Draw Inside clipping masks do: its fills paint behind the art drawn inside it and its strokes over that art, unclipped, so a centred stroke stays whole (#8753, `tests::file::draw_inside_keeps_the_objects_stroke_whole_and_over_the_new_art`). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). In Draw Behind, an Alt-drag copy made with the Selection or Direct Selection tool goes directly below its original and is selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists duplicating by Alt-drag among the actions the mode applies to; with several objects, each copy goes below its own original in that original's group or layer, the copy of the clipping path of a clip group or a clipping layer goes directly above it so the clipping path stays the bottom object, and in Draw Normal and Draw Inside, and for the transform dialogs' Copy, Duplicate and Transform Again, copies still go above (VectorCraft's own rules). In Draw Behind, a placed symbol instance (Place Symbol Instance in the Symbols panel, and a symbol dragged onto the canvas from the Symbols panel or a symbol library) goes directly below the selected object, or at the bottom of the current layer with nothing selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) describes for placing symbols; below the bottommost of several selected objects, beside the compound path that holds a selected path, and above a clipping path are VectorCraft's own rules. Draw Normal and Draw Inside keep it on top of the current layer. + - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). The object drawn into becomes the clip group's clipping path and keeps its fills and strokes, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) ([archived](https://web.archive.org/web/20261111110310/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) says Draw Inside clipping masks do: its fills paint behind the art drawn inside it and its strokes over that art, unclipped, so a centred stroke stays whole (#8753, `tests::file::draw_inside_keeps_the_objects_stroke_whole_and_over_the_new_art`). Its effects draw with its fills inside the clip group, so the part of a drop shadow that falls outside its outline is cut, as in any clip group. In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). In Draw Behind, an Alt-drag copy made with the Selection or Direct Selection tool goes directly below its original and is selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists duplicating by Alt-drag among the actions the mode applies to; with several objects, each copy goes below its own original in that original's group or layer, the copy of the clipping path of a clip group or a clipping layer goes directly above it so the clipping path stays the bottom object, and in Draw Normal and Draw Inside, and for the transform dialogs' Copy, Duplicate and Transform Again, copies still go above (VectorCraft's own rules). In Draw Behind, a placed symbol instance (Place Symbol Instance in the Symbols panel, and a symbol dragged onto the canvas from the Symbols panel or a symbol library) goes directly below the selected object, or at the bottom of the current layer with nothing selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) describes for placing symbols; below the bottommost of several selected objects, beside the compound path that holds a selected path, and above a clipping path are VectorCraft's own rules. Draw Normal and Draw Inside keep it on top of the current layer. - **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; double-click, or Alt-click on any point but an end of an open path, toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). An Alt-click on an end of a selected open path makes that end current without changing it, so the next click goes on from it, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-shapes-with-the-curvature-tool.html) describes for continuing a path; an Alt-click that starts a new path places a corner point, as later Alt-clicks do. Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners. A filled Pencil path keeps a stroke of None (#1804, part of #1679). While a Pencil or Paintbrush stroke is drawn back to within Close Paths When Ends Are Within of its start, the cursor shows the closing ring and a release there closes the path, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes for the Pencil. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). Blob Brush and Eraser Tool Options' Size is Fixed or Pressure with a Variation (#4590, #3961): with Pressure a pen stroke is Size − Variation wide where it presses lightest and Size + Variation where it presses hardest, and a mouse stroke keeps the Size. `path.blob` and `path.eraseRegion` refuse a Size outside 0.1 to 1000 pt and a Variation outside 0 to 1000 pt, also with Size set to Fixed, and the drawing commands that read pen values refuse a pressure outside 0 to 1, a tilt outside −90° to 90°, a rotation outside 0° to 360° and a point array of more than six numbers, with an error naming the key; the document, the selection and the undo history stay as they were. The pressure and tilt ranges are those of [Pointer Events](https://www.w3.org/TR/pointerevents3/); the Size, Variation and rotation ranges are VectorCraft's own values (`tests::draw2::pen_values_outside_their_ranges_are_refused`). From 6af735865376fce14669cfc38aa12fdda616733a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 02:24:17 -0800 Subject: [PATCH 06/88] Scripts: getPresetSettings gives a DocumentPreset that addDocument takes app.getPresetSettings returned a plain object with a typename of DocumentPreset, which addDocument refuses since it takes only an object of the DocumentPreset class. It now makes a DocumentPreset of the run with the preset's settings, through the same storage new DocumentPreset() uses, so addDocument takes it back and the result counts toward the run's limit of 10,000 DocumentPreset objects. Docs: docs/mcp.md. --- crates/engine/src/script/dom.rs | 27 ++++++++++++++------- crates/engine/src/script/dom/perspective.rs | 6 ++--- docs/mcp.md | 2 ++ 3 files changed, 23 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 5ec1172a54..ca687f6ba3 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -948,19 +948,28 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { /// left out. The settings stay with the run, which hands the script an object of the /// `DocumentPreset` class. fn new_preset(h: &Host) -> Answer { + let item = |k: &str, v: Data| (k.to_string(), v); + add_preset( + h, + vec![ + item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), + item("artboardRowsOrCols", num(1.0)), + item("artboardSpacing", num(20.0)), + item("height", num(792.0)), + item("numArtboards", num(1.0)), + item("width", num(612.0)), + ], + ) +} + +/// A new `DocumentPreset` of the run with the settings `fields`, which `new DocumentPreset()` and +/// `app.getPresetSettings` both make. +fn add_preset(h: &Host, fields: Vec<(String, Data)>) -> Answer { let mut presets = h.dom.presets.borrow_mut(); if presets.len() >= MAX_PRESETS { return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets"))); } - let item = |k: &str, v: Data| (k.to_string(), v); - presets.push(vec![ - item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), - item("artboardRowsOrCols", num(1.0)), - item("artboardSpacing", num(20.0)), - item("height", num(792.0)), - item("numArtboards", num(1.0)), - item("width", num(612.0)), - ]); + presets.push(fields); Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) } diff --git a/crates/engine/src/script/dom/perspective.rs b/crates/engine/src/script/dom/perspective.rs index 0df2dc3cfa..6a697234d4 100644 --- a/crates/engine/src/script/dom/perspective.rs +++ b/crates/engine/src/script/dom/perspective.rs @@ -24,7 +24,8 @@ //! `addDocument` takes back unchanged. Settings it cannot take are left out: units other than //! the six `RulerUnits` values, a PPI other than 72, 150 or 300, the artboard count and layout //! of more than 100 artboards, and the layout of a grid by column that no row count lays out the -//! same. Changing the result changes nothing else. +//! same. Changing the result changes nothing else. Each result counts toward the run's limit +//! of `DocumentPreset` objects, as `new DocumentPreset()` does. //! - The workspace methods, `loadColorSettings`, `showPresets` and the perspective grid preset //! files are not available yet. @@ -207,7 +208,6 @@ fn preset_settings(h: &Host, a: &[Data]) -> Answer { }; let item = |k: &str, v: Data| (k.to_string(), v); let mut out = vec![ - item("typename", text("DocumentPreset")), item("artboardLayout", text(format!("DocumentArtboardLayout.{layout}"))), item("artboardSpacing", num(d.spacing)), item("colorMode", text(if cmyk { "DocumentColorSpace.CMYK" } else { "DocumentColorSpace.RGB" })), @@ -231,7 +231,7 @@ fn preset_settings(h: &Host, a: &[Data]) -> Answer { if let Some((_, r)) = resolutions.iter().find(|(ppi, _)| (d.raster_effects_ppi - ppi).abs() < 1e-9) { out.push(item("rasterResolution", text(format!("DocumentRasterResolution.{r}")))); } - Ok(Data::Object(out)) + super::add_preset(h, out) } /// The members this module adds to `Document`'s. diff --git a/docs/mcp.md b/docs/mcp.md index 917c5d1837..b879148df5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2765,6 +2765,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `INVALIDGRIDPLANETYPE` makes no plane active. A preset name that is not listed, a preset whose grid is not of `gridType`, `InvalidPerspectiveGridType` and a name of more than 4,096 bytes throw an error with nothing changed. Changing the `DocumentPreset` `getPresetSettings` gives changes nothing else. + A run makes at most 10,000 `DocumentPreset` objects, those of `new DocumentPreset()` and `getPresetSettings` + together; one more throws a `RangeError`. `app.saveWorkspace`, `switchWorkspace`, `deleteWorkspace`, `resetWorkspace`, `loadColorSettings` and `showPresets`, and `Document.exportPerspectiveGridPreset` and `importPerspectiveGridPreset`, throw an error that says they are not available yet. From b41cd40be92b5551e30d91ecdc64cfcf2aba7ae3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 10:20:23 -0800 Subject: [PATCH 07/88] Scripts: app.startupPresetsList lists the startup presets addDocument takes app.startupPresetsList gives a new array of the startup preset names each read: the New Document profiles in the order the New Document dialog lists them, then Basic CMYK and Basic RGB. documents.addDocument and app.getPresetSettings take every name in it. --- crates/engine/src/script/dom/perspective.rs | 16 ++++++++++++-- .../src/tests/script_dom_perspective.rs | 22 +++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 3 ++- docs/mcp.md | 10 ++++++--- docs/target-app-parity.md | 2 +- 5 files changed, 46 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/dom/perspective.rs b/crates/engine/src/script/dom/perspective.rs index 6a697234d4..8521fff8f1 100644 --- a/crates/engine/src/script/dom/perspective.rs +++ b/crates/engine/src/script/dom/perspective.rs @@ -26,6 +26,10 @@ //! of more than 100 artboards, and the layout of a grid by column that no row count lays out the //! same. Changing the result changes nothing else. Each result counts toward the run's limit //! of `DocumentPreset` objects, as `new DocumentPreset()` does. +//! - `startupPresetsList` is an array of the startup preset names, each of which +//! `documents.addDocument` and `getPresetSettings` take: the New Document profiles in the order +//! the New Document dialog lists them, then `Basic CMYK` and `Basic RGB`. Each read gives a new +//! array, so changing it changes nothing else. //! - The workspace methods, `loadColorSettings`, `showPresets` and the perspective grid preset //! files are not available yet. @@ -33,7 +37,7 @@ use serde_json::json; use vectorcraft_js::{Data, HostError, HostMember}; use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane}; -use super::{Answer, MAX_TEXT_BYTES, arg, later, method, named, num, on_doc, startup_preset, text, this_doc, with_doc}; +use super::{Answer, MAX_TEXT_BYTES, arg, get, later, method, named, num, on_doc, startup_preset, text, this_doc, with_doc}; use crate::script::{Host, Link}; type Result = std::result::Result; @@ -234,6 +238,14 @@ fn preset_settings(h: &Host, a: &[Data]) -> Answer { super::add_preset(h, out) } +/// The startup presets besides the New Document profiles, which give a document of one color mode. +const BASIC_PRESETS: [&str; 2] = ["Basic CMYK", "Basic RGB"]; + +/// `app.startupPresetsList`: the names of the startup presets, as a new array. +fn startup_presets(_: &Host, _: &[Data]) -> Answer { + Ok(Data::Array(crate::cmd::newdoc::profile_names().chain(BASIC_PRESETS).map(text).collect())) +} + /// The members this module adds to `Document`'s. pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { let mut m = named(vec![ @@ -249,7 +261,7 @@ pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { /// The members this module adds to `Application`'s. pub(super) fn application_members(l: &Link) -> Vec<(String, HostMember)> { - let mut m = named(vec![("getPresetSettings", method(l, preset_settings))]); + let mut m = named(vec![("getPresetSettings", method(l, preset_settings)), ("startupPresetsList", get(l, startup_presets))]); let missing = ["saveWorkspace", "switchWorkspace", "deleteWorkspace", "resetWorkspace", "loadColorSettings", "showPresets"]; m.extend(missing.into_iter().map(|n| later(l, "Application", n))); m diff --git a/crates/engine/src/tests/script_dom_perspective.rs b/crates/engine/src/tests/script_dom_perspective.rs index eebea33e7e..f8196d6663 100644 --- a/crates/engine/src/tests/script_dom_perspective.rs +++ b/crates/engine/src/tests/script_dom_perspective.rs @@ -276,6 +276,28 @@ fn get_preset_settings_given_back_to_add_document_makes_the_same_document() { } } +#[test] +fn startup_presets_list_names_presets_add_document_takes() { + let mut s = Session::new(); + let out = log( + &mut s, + "var l = app.startupPresetsList; vc.log(l); l.push('Mine'); l[0] = 'x'; vc.log(app.startupPresetsList.length === l.length - 1);\ + vc.log(app.startupPresetsList[0] !== 'x');\ + for (var i = 0; i < l.length - 1; i++) { var n = app.startupPresetsList[i]; var p = app.getPresetSettings(n);\ + var d = app.documents.addDocument(n); vc.log([n, d.width === p.width && d.documentColorSpace === p.colorMode]); }", + ); + let names: Vec<&str> = out[0].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + for name in ["Print", "Web", "Basic CMYK", "Basic RGB"] { + assert!(names.contains(&name), "{name}: {names:?}"); + } + assert_eq!(out[1..3], [json!(true), json!(true)]); + assert_eq!(out.len(), 3 + names.len()); + for (name, made) in names.iter().zip(&out[3..]) { + assert_eq!(made, &json!([name, true]), "{name}"); + } + assert_eq!(s.documents().len(), names.len()); +} + #[test] fn members_not_built_yet_say_so() { let mut s = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index b76b8fb37a..7ac23d41ae 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -84,7 +84,8 @@ const INSIDE: &[(&str, &str)] = &[ "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= deleteWorkspace \ deleteWorkspace= documents getIsFileOpen getPresetSettings loadColorSettings loadColorSettings= resetWorkspace \ - resetWorkspace= saveWorkspace saveWorkspace= selection showPresets showPresets= switchWorkspace switchWorkspace= \ + resetWorkspace= saveWorkspace saveWorkspace= selection showPresets showPresets= startupPresetsList switchWorkspace \ + switchWorkspace= \ typename", ), ("DocumentPreset.", "prototype"), diff --git a/docs/mcp.md b/docs/mcp.md index b879148df5..39a91da05b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2741,8 +2741,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `GroupItems.createFromFile` throw an error that says they are not available yet. - A document also has `showPerspectiveGrid()`, `hidePerspectiveGrid()`, `getPerspectiveActivePlane()`, `setActivePlane(gridPlane)` and `selectPerspectivePreset(gridType, presetName)` - (https://ai-scripting.docsforadobe.dev/jsobjref/Document/), and `app` has `getPresetSettings(preset)` - (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `showPerspectiveGrid` and `hidePerspectiveGrid` + (https://ai-scripting.docsforadobe.dev/jsobjref/Document/), and `app` has `getPresetSettings(preset)` and + `startupPresetsList` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `showPerspectiveGrid` and `hidePerspectiveGrid` run `perspective.grid.show`, and `setActivePlane` runs `perspective.plane.set`; none of them adds an undo step, and a failed run puts the grid back. `selectPerspectivePreset` runs `perspective.grid.preset` with a built-in or saved preset of `perspective.presets.list` (its name in any case), which shows the grid and is part of the run's undo @@ -2758,7 +2758,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot preset's units are not one of the six `RulerUnits` values a new document takes, `rasterResolution` when the preset's PPI is not 72, 150 or 300, `numArtboards` and `artboardRowsOrCols` when the preset has more than 100 artboards, and `artboardRowsOrCols` alone for a grid by column that no row count lays out the same, so - `addDocument` with the same preset keeps the preset's own. As the Document page describes, + `addDocument` with the same preset keeps the preset's own. `startupPresetsList` is a read-only array of the + startup preset names, each of which `addDocument` and `getPresetSettings` take: the New Document profiles in the + order the New Document dialog lists them (`Mobile`, `Web`, `Print`, `Film & Video`, `Art & Illustration`, + `Branding`, `Social`), then `Basic CMYK` and `Basic RGB`. This order is VectorCraft's own. Each read gives a new + array, so changing it changes nothing else. As the Document page describes, `showPerspectiveGrid` and `setActivePlane` give `true` on success, and `hidePerspectiveGrid` gives `true` when it hides a grid and `false` when the grid was already hidden. VectorCraft's own rules: `showPerspectiveGrid` and `setActivePlane` also give `true` when nothing changed. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2d098d4977..0e25ded443 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,7 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Paths, type and the other classes are not there yet, except that `CompoundPathItem.pathItems` reads the paths of a compound path. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks and new empty groups, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - - Scripts: a document's perspective grid is shown, hidden, given its active plane and reset to a built-in or saved preset of the type the script names, and `app.getPresetSettings` gives the settings of a startup preset as a `DocumentPreset`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and https://ai-scripting.docsforadobe.dev/jsobjref/Application/ list them (`docs/mcp.md`). Showing, hiding and the active plane add no undo step in a script run, as outside one. Workspaces, `loadColorSettings`, `showPresets` and perspective grid preset files are not there yet. `crates/engine/src/tests/script_dom_perspective.rs`. + - Scripts: a document's perspective grid is shown, hidden, given its active plane and reset to a built-in or saved preset of the type the script names, and `app.getPresetSettings` gives the settings of a startup preset as a `DocumentPreset`, and `app.startupPresetsList` lists the startup presets' names, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and https://ai-scripting.docsforadobe.dev/jsobjref/Application/ list them (`docs/mcp.md`). Showing, hiding and the active plane add no undo step in a script run, as outside one. Workspaces, `loadColorSettings`, `showPresets` and perspective grid preset files are not there yet. `crates/engine/src/tests/script_dom_perspective.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - 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`. From 2f931e0444bbf7274aa76ee8922da09e6adc3f69 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 11:21:13 -0800 Subject: [PATCH 08/88] Tests: startupPresetsList keeps the New Document dialog's order The test now compares app.startupPresetsList with the New Document profiles in the dialog's order followed by Basic CMYK and Basic RGB, the order docs/mcp.md gives, instead of checking that four names are present. --- crates/engine/src/tests/script_dom_perspective.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/script_dom_perspective.rs b/crates/engine/src/tests/script_dom_perspective.rs index f8196d6663..e0b8d4c4c9 100644 --- a/crates/engine/src/tests/script_dom_perspective.rs +++ b/crates/engine/src/tests/script_dom_perspective.rs @@ -287,9 +287,9 @@ fn startup_presets_list_names_presets_add_document_takes() { var d = app.documents.addDocument(n); vc.log([n, d.width === p.width && d.documentColorSpace === p.colorMode]); }", ); let names: Vec<&str> = out[0].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); - for name in ["Print", "Web", "Basic CMYK", "Basic RGB"] { - assert!(names.contains(&name), "{name}: {names:?}"); - } + // The New Document profiles in the dialog's order, then the Basic presets. + let listed: Vec<&str> = crate::cmd::newdoc::profile_names().chain(["Basic CMYK", "Basic RGB"]).collect(); + assert_eq!(names, listed); assert_eq!(out[1..3], [json!(true), json!(true)]); assert_eq!(out.len(), 3 + names.len()); for (name, made) in names.iter().zip(&out[3..]) { From d7ba04760d1f9b134fdbb0908ae6c7102d36e2ce Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 12:22:32 -0800 Subject: [PATCH 09/88] Scripts: app.startupPresetsList lists Print first Scripts read app.startupPresetsList[0] as the print preset. The list now starts with Print, then Web, Mobile, Film & Video, Art & Illustration, Branding and Social, then Basic CMYK and Basic RGB. The order is VectorCraft's own. The test now checks that Print comes first and that the list holds each New Document profile and both Basic presets once, instead of comparing with the profiles' order in the New Document dialog. docs/mcp.md states the new order and that a script which changes the array a read gave does not change the list a later read gives. --- crates/engine/src/script/dom/perspective.rs | 13 +++++++------ crates/engine/src/tests/script_dom_perspective.rs | 11 ++++++++--- docs/mcp.md | 12 ++++++------ docs/target-app-parity.md | 2 +- 4 files changed, 22 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/script/dom/perspective.rs b/crates/engine/src/script/dom/perspective.rs index 8521fff8f1..33d2c821b4 100644 --- a/crates/engine/src/script/dom/perspective.rs +++ b/crates/engine/src/script/dom/perspective.rs @@ -27,9 +27,9 @@ //! same. Changing the result changes nothing else. Each result counts toward the run's limit //! of `DocumentPreset` objects, as `new DocumentPreset()` does. //! - `startupPresetsList` is an array of the startup preset names, each of which -//! `documents.addDocument` and `getPresetSettings` take: the New Document profiles in the order -//! the New Document dialog lists them, then `Basic CMYK` and `Basic RGB`. Each read gives a new -//! array, so changing it changes nothing else. +//! `documents.addDocument` and `getPresetSettings` take: `Print` first, then the other New +//! Document profiles, then `Basic CMYK` and `Basic RGB`. Each read gives a new +//! array; a script that changes that array does not change the list a later read gives. //! - The workspace methods, `loadColorSettings`, `showPresets` and the perspective grid preset //! files are not available yet. @@ -238,12 +238,13 @@ fn preset_settings(h: &Host, a: &[Data]) -> Answer { super::add_preset(h, out) } -/// The startup presets besides the New Document profiles, which give a document of one color mode. -const BASIC_PRESETS: [&str; 2] = ["Basic CMYK", "Basic RGB"]; +/// The startup presets in the order `app.startupPresetsList` gives them: `Print` first, then the +/// other New Document profiles, then the presets that give a document of one color mode. +const STARTUP_PRESETS: [&str; 9] = ["Print", "Web", "Mobile", "Film & Video", "Art & Illustration", "Branding", "Social", "Basic CMYK", "Basic RGB"]; /// `app.startupPresetsList`: the names of the startup presets, as a new array. fn startup_presets(_: &Host, _: &[Data]) -> Answer { - Ok(Data::Array(crate::cmd::newdoc::profile_names().chain(BASIC_PRESETS).map(text).collect())) + Ok(Data::Array(STARTUP_PRESETS.into_iter().map(text).collect())) } /// The members this module adds to `Document`'s. diff --git a/crates/engine/src/tests/script_dom_perspective.rs b/crates/engine/src/tests/script_dom_perspective.rs index e0b8d4c4c9..8d533349bf 100644 --- a/crates/engine/src/tests/script_dom_perspective.rs +++ b/crates/engine/src/tests/script_dom_perspective.rs @@ -287,9 +287,14 @@ fn startup_presets_list_names_presets_add_document_takes() { var d = app.documents.addDocument(n); vc.log([n, d.width === p.width && d.documentColorSpace === p.colorMode]); }", ); let names: Vec<&str> = out[0].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); - // The New Document profiles in the dialog's order, then the Basic presets. - let listed: Vec<&str> = crate::cmd::newdoc::profile_names().chain(["Basic CMYK", "Basic RGB"]).collect(); - assert_eq!(names, listed); + // Scripts take `startupPresetsList[0]` as the print preset. + assert_eq!(names.first(), Some(&"Print")); + // Every New Document profile and both Basic presets, each once. + let mut sorted = names.clone(); + sorted.sort_unstable(); + let mut listed: Vec<&str> = crate::cmd::newdoc::profile_names().chain(["Basic CMYK", "Basic RGB"]).collect(); + listed.sort_unstable(); + assert_eq!(sorted, listed); assert_eq!(out[1..3], [json!(true), json!(true)]); assert_eq!(out.len(), 3 + names.len()); for (name, made) in names.iter().zip(&out[3..]) { diff --git a/docs/mcp.md b/docs/mcp.md index 39a91da05b..18e1839727 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2742,8 +2742,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot - A document also has `showPerspectiveGrid()`, `hidePerspectiveGrid()`, `getPerspectiveActivePlane()`, `setActivePlane(gridPlane)` and `selectPerspectivePreset(gridType, presetName)` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/), and `app` has `getPresetSettings(preset)` and - `startupPresetsList` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `showPerspectiveGrid` and `hidePerspectiveGrid` - run `perspective.grid.show`, and `setActivePlane` runs `perspective.plane.set`; none of them adds an undo step, and + `startupPresetsList` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `showPerspectiveGrid` + and `hidePerspectiveGrid` run `perspective.grid.show`, and `setActivePlane` runs `perspective.plane.set`; none of them adds an undo step, and a failed run puts the grid back. `selectPerspectivePreset` runs `perspective.grid.preset` with a built-in or saved preset of `perspective.presets.list` (its name in any case), which shows the grid and is part of the run's undo step when the grid changes. The enumerations `PerspectiveGridType` (`OnePointPerspectiveGridType`, @@ -2759,10 +2759,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot preset's PPI is not 72, 150 or 300, `numArtboards` and `artboardRowsOrCols` when the preset has more than 100 artboards, and `artboardRowsOrCols` alone for a grid by column that no row count lays out the same, so `addDocument` with the same preset keeps the preset's own. `startupPresetsList` is a read-only array of the - startup preset names, each of which `addDocument` and `getPresetSettings` take: the New Document profiles in the - order the New Document dialog lists them (`Mobile`, `Web`, `Print`, `Film & Video`, `Art & Illustration`, - `Branding`, `Social`), then `Basic CMYK` and `Basic RGB`. This order is VectorCraft's own. Each read gives a new - array, so changing it changes nothing else. As the Document page describes, + startup preset names, each of which `addDocument` and `getPresetSettings` take: `Print`, `Web`, `Mobile`, + `Film & Video`, `Art & Illustration`, `Branding`, `Social`, `Basic CMYK` and `Basic RGB`, in that order, so + `app.startupPresetsList[0]` is `Print`. This order is VectorCraft's own. Each read gives a new array; a script + that changes that array does not change the list a later read gives. As the Document page describes, `showPerspectiveGrid` and `setActivePlane` give `true` on success, and `hidePerspectiveGrid` gives `true` when it hides a grid and `false` when the grid was already hidden. VectorCraft's own rules: `showPerspectiveGrid` and `setActivePlane` also give `true` when nothing changed. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0e25ded443..afd314657f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,7 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Paths, type and the other classes are not there yet, except that `CompoundPathItem.pathItems` reads the paths of a compound path. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks and new empty groups, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - - Scripts: a document's perspective grid is shown, hidden, given its active plane and reset to a built-in or saved preset of the type the script names, and `app.getPresetSettings` gives the settings of a startup preset as a `DocumentPreset`, and `app.startupPresetsList` lists the startup presets' names, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and https://ai-scripting.docsforadobe.dev/jsobjref/Application/ list them (`docs/mcp.md`). Showing, hiding and the active plane add no undo step in a script run, as outside one. Workspaces, `loadColorSettings`, `showPresets` and perspective grid preset files are not there yet. `crates/engine/src/tests/script_dom_perspective.rs`. + - Scripts: a document's perspective grid is shown, hidden, given its active plane and reset to a built-in or saved preset of the type the script names; `app.getPresetSettings` gives the settings of a startup preset as a `DocumentPreset`; and `app.startupPresetsList` lists the startup presets' names, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and https://ai-scripting.docsforadobe.dev/jsobjref/Application/ list them (`docs/mcp.md`). Showing, hiding and the active plane add no undo step in a script run, as outside one. Workspaces, `loadColorSettings`, `showPresets` and perspective grid preset files are not there yet. `crates/engine/src/tests/script_dom_perspective.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - 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`. From 74bea71d0fc17e2477a6104865727822c00feed1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 12:34:33 -0800 Subject: [PATCH 10/88] Docs: rewrap the perspective grid paragraph in docs/mcp.md The startupPresetsList test comment now says that Print first is VectorCraft's own order. The Application.prototype member list in the scriptcheck table keeps switchWorkspace= and typename on one line. --- crates/engine/src/tests/script_dom_perspective.rs | 2 +- crates/engine/tests/it/script_host_vs_scriptcheck.rs | 3 +-- docs/mcp.md | 9 +++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/tests/script_dom_perspective.rs b/crates/engine/src/tests/script_dom_perspective.rs index 8d533349bf..c0c1bdbc80 100644 --- a/crates/engine/src/tests/script_dom_perspective.rs +++ b/crates/engine/src/tests/script_dom_perspective.rs @@ -287,7 +287,7 @@ fn startup_presets_list_names_presets_add_document_takes() { var d = app.documents.addDocument(n); vc.log([n, d.width === p.width && d.documentColorSpace === p.colorMode]); }", ); let names: Vec<&str> = out[0].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); - // Scripts take `startupPresetsList[0]` as the print preset. + // VectorCraft's own order puts Print first. assert_eq!(names.first(), Some(&"Print")); // Every New Document profile and both Basic presets, each once. let mut sorted = names.clone(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 7ac23d41ae..e528c675e1 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -85,8 +85,7 @@ const INSIDE: &[(&str, &str)] = &[ "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= deleteWorkspace \ deleteWorkspace= documents getIsFileOpen getPresetSettings loadColorSettings loadColorSettings= resetWorkspace \ resetWorkspace= saveWorkspace saveWorkspace= selection showPresets showPresets= startupPresetsList switchWorkspace \ - switchWorkspace= \ - typename", + switchWorkspace= typename", ), ("DocumentPreset.", "prototype"), ( diff --git a/docs/mcp.md b/docs/mcp.md index 18e1839727..7509ba8832 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2743,10 +2743,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot `setActivePlane(gridPlane)` and `selectPerspectivePreset(gridType, presetName)` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/), and `app` has `getPresetSettings(preset)` and `startupPresetsList` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `showPerspectiveGrid` - and `hidePerspectiveGrid` run `perspective.grid.show`, and `setActivePlane` runs `perspective.plane.set`; none of them adds an undo step, and - a failed run puts the grid back. `selectPerspectivePreset` runs `perspective.grid.preset` with a built-in or saved - preset of `perspective.presets.list` (its name in any case), which shows the grid and is part of the run's undo - step when the grid changes. The enumerations `PerspectiveGridType` (`OnePointPerspectiveGridType`, + and `hidePerspectiveGrid` run `perspective.grid.show`, and `setActivePlane` runs `perspective.plane.set`; none of + them adds an undo step, and a failed run puts the grid back. `selectPerspectivePreset` runs + `perspective.grid.preset` with a built-in or saved preset of `perspective.presets.list` (its name in any case), + which shows the grid and is part of the run's undo step when the grid changes. The enumerations + `PerspectiveGridType` (`OnePointPerspectiveGridType`, `TwoPointPerspectiveGridType`, `ThreePointPerspectiveGridType`, `InvalidPerspectiveGridType`) and `PerspectiveGridPlaneType` (`GRIDLEFTPLANETYPE`, `GRIDRIGHTPLANETYPE`, `GRIDFLOORPLANETYPE`, `INVALIDGRIDPLANETYPE`) come from https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/. A From 333f49139de6b60425c8cd71eab8febe2087a4bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:51:20 -0800 Subject: [PATCH 11/88] Scripts: a layer's or group's removeAll refuses art on a locked artboard The removeAll() of a layer's or group's pageItems, and of groupItems and compoundPathItems, checked only for hidden or locked objects, so it deleted art on a locked artboard that remove() and the document's pageItems.removeAll() refuse. It now refuses those objects with the same error before anything is deleted, and records no undo step. --- crates/engine/src/script/dom.rs | 2 +- crates/engine/src/script/dom/layers.rs | 21 +++++++++----- crates/engine/src/tests/script_dom.rs | 40 ++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index ca687f6ba3..6b43d6b887 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1581,7 +1581,7 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { } /// The error of `remove()` and `removeAll()` for an object on a locked artboard. -const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; +pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; /// The error of `move` and `duplicate` given an object of another document. pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available"; diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index bd0046a4b4..2d6993f860 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -37,9 +37,9 @@ use serde_json::{Value, json}; use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts}; use super::{ - Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, arg, boolean, command, doc_of, - doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, later, method, named, num, number, on_doc, - page_items, placement_of, property, text, typename, whole, with_doc, + Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, arg, + boolean, command, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, later, method, named, + num, number, on_doc, page_items, placement_of, property, text, typename, whole, with_doc, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -654,11 +654,12 @@ fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer { } /// `removeAll()`: deletes every object the collection lists (those inside another listed one go -/// with it) in one command. A hidden or locked one, or one in a hidden or locked layer or group, -/// stops it before anything is deleted. +/// with it) in one command. A hidden or locked one, one in a hidden or locked layer or group, or +/// one on a locked artboard stops it before anything is deleted, as the document's +/// `pageItems.removeAll()` is stopped. fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let all = art_list(h, st, kind, c)?; let d = &st.doc; let listed: std::collections::HashSet = all.iter().copied().collect(); @@ -666,12 +667,18 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { all.iter().copied().filter(|i| !d.ancestry(*i).is_some_and(|a| a.iter().any(|x| *x != *i && listed.contains(x)))).collect(); let whole = |id: &NodeId| editable(d, *id) && d.node(*id).is_some_and(super::all_editable); let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused)) + let locks = d.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + Ok::<_, HostError>((ids, refused, on_locked)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index c44ecb4887..6ff113bef5 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -997,6 +997,46 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { assert_eq!(out, vec![json!(0)]); } +/// The `removeAll()` of a layer's or group's collections, and of `groupItems` and +/// `compoundPathItems`, refuses art on a locked artboard as the document's `pageItems.removeAll()` +/// does, and deletes nothing. +#[test] +fn scoped_remove_all_refuses_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + let e = rect(&mut s, 250.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + for scope in [ + "app.activeDocument.layers[0].pageItems", + "app.activeDocument.layers[0].groupItems", + "app.activeDocument.groupItems", + "app.activeDocument.groupItems[0].pageItems", + "app.activeDocument.layers[0].compoundPathItems", + "app.activeDocument.compoundPathItems", + ] { + let err = failure(&mut s, &format!("{scope}.removeAll();")); + assert!(err.contains("cannot delete objects on a locked artboard"), "{scope}: {err}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{scope}"); + assert_eq!(undo_steps(&s), steps, "{scope}"); + } + lock(&mut s, false); + let out = log(&mut s, "var d = app.activeDocument; d.layers[0].pageItems.removeAll(); vc.log(d.pageItems.length);"); + assert_eq!(out, vec![json!(0)]); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); From 71f6414cf0a704474a9571d11c9398300a94c586 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:12:51 -0800 Subject: [PATCH 12/88] Scripts: a loop over groups and their page items lists each collection once The object model kept only the last list of art it built, so a loop that read doc.groupItems[i] and then that group's pageItems rebuilt the document-wide list of groups on every step. It now keeps the last four lists, each while its document is unchanged, and drops a document's older lists when it builds one for a newer version of that document. --- crates/engine/src/script/dom.rs | 6 +++--- crates/engine/src/script/dom/layers.rs | 29 ++++++++++++++++++-------- crates/engine/src/tests/script_dom.rs | 24 +++++++++++++++++++++ 3 files changed, 47 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 6b43d6b887..ff97c2fa7b 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -95,9 +95,9 @@ pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, - /// The last list of art one of [`layers`]' collections gave, kept while its document is - /// unchanged. - art: RefCell>, + /// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently + /// used first, each kept while its document is unchanged. + art: RefCell>, /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_artboards: RefCell>, presets: RefCell>>, diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 2d6993f860..973270c07a 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -572,17 +572,23 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option)> { /// and the ids it listed then. pub(super) type ArtList = (u64, Arc, u8, Option, Rc>); +/// How many lists of art [`super::State`] keeps at once. +pub(super) const ART_LISTS: usize = 4; + /// The objects of `kind` in `container` (directly), or in the whole document at any depth, in -/// paint order. The last list is kept while the document is unchanged, and each new one is charged -/// by the objects it looks at. +/// paint order. The last [`ART_LISTS`] lists are kept while their documents are unchanged, so a +/// loop over groups that reads each group's `pageItems` builds each list once. Each new list is +/// charged by the objects it looks at. fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> Result>> { - if let Some((uid, doc, k, c, ids)) = &*h.dom.art.borrow() - && *uid == st.uid - && Arc::ptr_eq(doc, &st.doc) - && *k == kind as u8 - && *c == container { - return Ok(ids.clone()); + let mut lists = h.dom.art.borrow_mut(); + let at = lists.iter().position(|(uid, doc, k, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *k == kind as u8 && *c == container); + if let Some(at) = at { + let list = lists.remove(at); + let ids = list.4.clone(); + lists.push(list); + return Ok(ids); + } } let ids: Vec = match container { None => { @@ -597,7 +603,12 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> R } }; let ids = Rc::new(ids); - *h.dom.art.borrow_mut() = Some((st.uid, st.doc.clone(), kind as u8, container, ids.clone())); + let mut lists = h.dom.art.borrow_mut(); + lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); + if lists.len() >= ART_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), kind as u8, container, ids.clone())); Ok(ids) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 6ff113bef5..f2203a8ea5 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1290,6 +1290,30 @@ fn art_collections_follow_edits_between_reads() { assert_eq!(out, [json!(2), json!(0), json!(3), json!("GroupItem"), json!(1), json!(2), json!("PathItem")]); } +#[test] +fn a_loop_over_groups_and_their_items_lists_each_collection_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for i in 0..5 { + let x = f64::from(i) * 20.0; + let (a, b) = (rect(&mut s, x, 0.0, 10.0, 10.0), rect(&mut s, x, 20.0, 10.0, 10.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + } + // Both scripts make the same calls. The first reads the groups and each group's items in + // turn; the second reads every group before any group's items, so it builds each list once. + let nested = "var gs = app.activeDocument.groupItems, n = 0;\ + for (var i = 0; i < gs.length; i++) { var p = gs[i].pageItems; for (var j = 0; j < p.length; j++) { p[j]; n++; } }\ + vc.log(n);"; + let in_order = "var gs = app.activeDocument.groupItems, all = [], n = 0;\ + for (var i = 0; i < gs.length; i++) { all.push(gs[i]); }\ + for (var k = 0; k < all.length; k++) { var p = all[k].pageItems; for (var j = 0; j < p.length; j++) { p[j]; n++; } }\ + vc.log(n);"; + let (a, b) = (run(&mut s, nested).unwrap(), run(&mut s, in_order).unwrap()); + assert_eq!((a["log"].clone(), b["log"].clone()), (json!([10]), json!([10]))); + assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}"); +} + #[test] fn group_items_remove_all_refuses_locked_groups() { let (mut s, a, b) = doc(); From 68de13f3454d8ac6cda8cf664b9cec5a36e79bd9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 15:23:44 -0800 Subject: [PATCH 13/88] Scripts: the report and the Artboard tool follow the active artboard a run moves - script.run's report lists a document whose active artboard has another index at the end of the run because artboards were inserted, removed or reordered before it. - After a run, the Artboard tool takes the active artboard as its only selected one, as choosing it in the Artboards panel does. - layers.add, groupItems.add and artboards.add read the new object's id from the command's own result, so ids above 2^53 stay exact. --- crates/engine/src/script/dom.rs | 7 ++++ crates/engine/src/script/dom/layers.rs | 44 +++++++++++++++----------- crates/engine/src/script/mod.rs | 4 +-- crates/engine/src/tests/script_dom.rs | 32 +++++++++++++++++++ crates/ui-egui/src/script_runs.rs | 9 +++++- crates/ui-egui/src/tests/script_run.rs | 18 +++++++++++ docs/mcp.md | 3 +- 7 files changed, 95 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index ff97c2fa7b..896f454931 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -100,10 +100,17 @@ pub(super) struct State { art: RefCell>, /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_artboards: RefCell>, + /// Each open document's uid and the index of its active artboard when the run started. + pub(super) boards_at_start: Vec<(u64, usize)>, presets: RefCell>>, } impl State { + /// The state of a run that starts with the documents `docs` open. + pub(super) fn new(docs: &[DocState]) -> Self { + Self { boards_at_start: docs.iter().map(|st| (st.uid, active_artboard(st))).collect(), ..Self::default() } + } + /// Whether a call's own savepoint is open: its commands take none of their own. pub(super) fn saving(&self) -> bool { self.saving.get() diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 973270c07a..1251972f64 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -28,7 +28,9 @@ //! - `Artboard.rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down; with global //! rulers, setting it moves the document's zero point. //! - `setActiveArtboardIndex` changes the view's active artboard: no undo step, and the run's report -//! lists it in `activeArtboards` for the app to show. +//! lists it in `activeArtboards` for the app to show. The report also lists a document whose +//! active artboard has another index at the end of the run, because artboards were inserted, +//! removed or reordered before it. use std::rc::Rc; use std::sync::Arc; @@ -38,8 +40,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_ use super::{ Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, arg, - boolean, command, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, later, method, named, - num, number, on_doc, page_items, placement_of, property, text, typename, whole, with_doc, + boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, later, + method, named, num, number, on_doc, page_items, placement_of, property, text, typename, whole, with_doc, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -86,13 +88,10 @@ fn type_error(what: &str) -> HostError { HostError::Type(format!("this is not a {what}")) } -/// The id a command's result gives under `key`. -fn result_id(d: &Data, key: &str) -> Option { - let Data::Object(o) = d else { return None }; - match o.iter().find(|(k, _)| k == key).map(|(_, v)| v) { - Some(Data::Number(n)) => whole(*n), - _ => None, - } +/// The whole number under `key` in a command's own result (not the script's copy, whose numbers +/// are exact only up to 2^53), such as the id of the object it made. +fn result_id(v: &Value, key: &str) -> Option { + v.get(key).and_then(Value::as_u64) } // ---- Layer ---- @@ -523,9 +522,9 @@ fn layers_add(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("the layer is hidden or locked".into())); } } - let r = on_doc(h, doc.uid, true, |h| match parent { - None => command(h, "layer.new", &json!({"top": true})), - Some(p) => command(h, "layer.newSublayer", &json!({"parent": p.0})), + let (_, r) = on_doc(h, doc.uid, true, |h| match parent { + None => command_value(h, "layer.new", &json!({"top": true})), + Some(p) => command_value(h, "layer.newSublayer", &json!({"parent": p.0})), })?; let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the layer was not made".into()))?; Ok(layer_ref(h, doc.uid, NodeId(id))) @@ -783,7 +782,7 @@ fn groups_add(h: &Host, a: &[Data]) -> Answer { } } let params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0})); - let r = on_doc(h, doc.uid, true, |h| command(h, "object.newGroup", ¶ms))?; + let (_, r) = on_doc(h, doc.uid, true, |h| command_value(h, "object.newGroup", ¶ms))?; let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the group was not made".into()))?; let s = h.session.borrow(); let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; @@ -1201,7 +1200,7 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { } let id = super::atomically(h, |h| { on_doc(h, doc.uid, true, |h| { - let made = command(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; + let (_, made) = command_value(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; let index = result_id(&made, "index") .and_then(|i| usize::try_from(i).ok()) .ok_or_else(|| HostError::Error("the artboard was not made".into()))?; @@ -1265,9 +1264,18 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer { /// The documents whose active artboard the run changed, as `script.run`'s report gives them: /// `[{document, artboard}]`, each an index, with the active artboard each document has at the end -/// of the run, or `None` when there are none. -pub(crate) fn active_artboards(moved: &[u64], docs: &[DocState]) -> Option { - let list: Vec = moved +/// of the run, or `None` when there are none. They are the documents in `moved`, then those whose +/// active artboard's index differs from the one in `start` (an artboard added, inserted, removed or +/// reordered before it). +pub(crate) fn active_artboards(moved: &[u64], start: &[(u64, usize)], docs: &[DocState]) -> Option { + let mut uids = moved.to_vec(); + for (uid, at) in start { + let shifted = docs.iter().find(|d| d.uid == *uid).is_some_and(|st| active_artboard(st) != *at); + if shifted && !uids.contains(uid) { + uids.push(*uid); + } + } + let list: Vec = uids .iter() .filter_map(|uid| { let document = docs.iter().position(|d| d.uid == *uid)?; diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 28d36f030d..3b2614fd9e 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2108,7 +2108,7 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), - dom: dom::State::default(), + dom: dom::State::new(self.documents()), run_docs: RefCell::new( self.docs .iter() @@ -2349,7 +2349,7 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); - if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), self.documents()) { + if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &host.dom.boards_at_start, self.documents()) { report["activeArtboards"] = boards; } close_run(self, host, &mut report, console::Ending::Finished); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index f2203a8ea5..99fd7ae784 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1133,6 +1133,22 @@ fn layers_list_top_first_and_add_makes_the_new_layer_current() { assert_eq!(s.active().unwrap().doc.layer_containing(a), Some(lid)); } +#[test] +fn a_new_layer_or_group_with_a_large_id_is_the_new_one() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // The new ids, 2^53 + 1 and 2^53 + 3, are not exact as numbers. + for (id, source) in + [(1, "var l = app.activeDocument.layers.add(); l.name = 'made';"), (3, "var g = app.activeDocument.groupItems.add(); g.name = 'made';")] + { + let big = (1u64 << 53) + id; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + run(&mut s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + let d = &s.active().unwrap().doc; + assert_eq!(d.node(NodeId(big)).and_then(|n| n.name.clone()).as_deref(), Some("made"), "{source}"); + } +} + #[test] fn layer_properties_round_trip_and_reject_bad_values() { let (mut s, _, _) = doc(); @@ -1442,6 +1458,22 @@ fn the_report_gives_the_active_artboard_the_run_leaves() { assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": active}])); } +#[test] +fn the_report_gives_the_active_artboards_new_index_after_an_insert_or_remove() { + let (mut s, _, _) = doc(); + run(&mut s, "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]); A.setActiveArtboardIndex(1);").unwrap(); + // An artboard inserted or removed before the active one moves it to another index. + let r = run(&mut s, "var A = app.activeDocument.artboards; A.insert([800, 300, 900, 100], 0); vc.log(A.getActiveArtboardIndex());").unwrap(); + assert_eq!(r["log"], json!([2])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 2}])); + let r = run(&mut s, "var A = app.activeDocument.artboards; A.remove(0); vc.log(A.getActiveArtboardIndex());").unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + // One added after it leaves its index as it was. + let r = run(&mut s, "app.activeDocument.artboards.add([1000, 300, 1100, 100]);").unwrap(); + assert!(r.get("activeArtboards").is_none(), "{r}"); +} + #[test] fn an_artboard_rectangle_stays_inside_the_canvas() { let (mut s, _, _) = doc(); diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 8cfc7e4c4b..d0454658ef 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -38,7 +38,9 @@ pub fn poll(app: &mut VectorcraftApp) { } /// Makes each artboard a run's `setActiveArtboardIndex` chose the active one of its document's view -/// (`activeArtboards` in the run's report: `{document, artboard}`, both indexes). +/// (`activeArtboards` in the run's report: `{document, artboard}`, both indexes). The end of a run +/// starts the tool afresh, so the Artboard tool then takes the active document's active artboard as +/// its only selected one, as choosing it in the Artboards panel does. fn show_artboards(app: &mut VectorcraftApp, boards: &[serde_json::Value]) { for b in boards { let index = |k: &str| b[k].as_u64().and_then(|i| usize::try_from(i).ok()); @@ -50,6 +52,11 @@ fn show_artboards(app: &mut VectorcraftApp, boards: &[serde_json::Value]) { view.artboard = board; } } + if app.session.tool_id() == "artboard" + && let Some(n) = app.session.active().map(|d| d.doc.artboards.len()).filter(|n| *n > 0) + { + crate::panels::artboards::select(app, crate::panels::artboards::selected(app, n)); + } } /// Opens what the run waits at, once no other dialog is open: the script's own dialog, or the diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 877875077d..9e30323364 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -156,6 +156,24 @@ fn set_active_artboard_index_shows_the_artboard_in_the_view() { assert_eq!(app.views[0].artboard, 1); } +#[test] +fn the_artboard_tool_follows_the_artboard_a_script_makes_active() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + app.run("artboard.new", json!({"x": 1000, "y": 0, "width": 100, "height": 100})).unwrap(); + app.run("artboard.new", json!({"x": 2000, "y": 0, "width": 100, "height": 100})).unwrap(); + app.select_tool("artboard"); + crate::panels::artboards::select(&mut app, 2); + // A run starts the tool afresh; it keeps the view's active artboard, then the one the script chose. + for (source, active) in [("vc.log(1);", 2), ("app.activeDocument.artboards.setActiveArtboardIndex(1);", 1)] { + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(app.views[0].artboard, active, "{source}"); + assert_eq!(app.session.tool_options()["active"], json!(active), "{source}"); + assert_eq!(app.session.tool_options()["selected"], json!([active]), "{source}"); + } +} + #[test] fn a_canceled_pick_does_not_take_a_dropped_script() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index c3f5a33db2..22a0eda208 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2765,7 +2765,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot past the artboard count that no other artboard's name uses. `rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down. `setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the - run leaves it). An index outside the list throws a + run leaves it). The report also lists a document whose active artboard has another index when the run ends because + artboards were inserted, removed or reordered before it. An index outside the list throws a `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and `GroupItems.createFromFile` throw an error that says they are not available yet. From b249beb9176fa70ab2e487f162d02df2fbdc3fb0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:01:37 -0800 Subject: [PATCH 14/88] New Document: picking the selected Grid by Column keeps a preset's rows Picking the layout that is already selected in More Settings removed the rows of a preset made with file.new's rows and kept only the columns they showed, so Create put a different number of artboards in each column. With five artboards and rows 4, the first column got three artboards instead of four. A different layout or a new column count still replaces the rows. --- crates/ui-egui/src/dialogs/new_document.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 0852e55bec..09253c1a91 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -480,8 +480,12 @@ fn shown_columns(s: &DocSettings) -> u32 { s.columns.max(1).min(s.artboards.max(1)) } -/// Picks the artboard layout `l`. A preset's rows give way to the column count they showed. +/// Picks the artboard layout `l`. A preset's rows give way to the column count they showed; +/// picking the layout that is already selected keeps them. fn pick_layout(s: &mut DocSettings, l: ArtboardLayout) { + if l == s.layout { + return; + } if by_rows(s) { s.columns = shown_columns(s); } @@ -812,7 +816,7 @@ mod tests { /// showed. Under a grid by row the dialog shows the stored columns, and they stay. #[test] fn a_new_layout_keeps_the_columns_a_presets_rows_showed() { - for to in ArtboardLayout::ALL { + for to in ArtboardLayout::ALL.into_iter().filter(|l| *l != ArtboardLayout::GridByColumn) { for rows in [json!(4), json!(4.0), json!(3.6)] { let mut s = settings(json!({"artboards": 9, "artboardLayout": {"layout": "gridByColumn", "columns": 2, "rows": rows}})); assert_eq!(shown_columns(&s), 3, "9 artboards in rows {rows}"); @@ -827,6 +831,18 @@ mod tests { assert_eq!(shown_columns(&s), 2); } + /// Picking the grid by column that is already selected keeps a preset's rows, so Create puts + /// as many artboards in each column as before. + #[test] + fn picking_the_selected_layout_keeps_a_presets_rows() { + let mut s = settings(json!({"artboards": 5, "artboardLayout": {"layout": "gridByColumn", "columns": 2, "rows": 4, "spacing": 10}})); + let before = s.to_json()["artboardLayout"].clone(); + assert_eq!(before["rows"], json!(4)); + pick_layout(&mut s, ArtboardLayout::GridByColumn); + assert_eq!(s.to_json()["artboardLayout"], before); + assert_eq!(shown_columns(&s), 2); + } + /// Columns shows what a preset's rows give the current number of artboards; the dialog's /// fields list the rows with those columns. #[test] From 3b1058b7e532f5085735b23d6f7df3eb553a4077 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 00:36:21 -0800 Subject: [PATCH 15/88] Scripts: fix review findings in preset settings, removeAll, artboard insert and grid view getPresetSettings leaves out previewMode for a Pixel Preview preset, which addDocument does not take. removeAll releases the clip of a group or layer whose clipping mask it deletes. Inserting an artboard keeps the active artboard by id, and the run report gives its new index, also in a document the run opened. Scoped name lookups charge for the entries they scan. Showing or hiding the perspective grid of an older document adds no undo step for the attachment migration alone. --- .../engine/src/cmd/distortcmds/perspective.rs | 6 +- crates/engine/src/script/dom.rs | 11 ++- crates/engine/src/script/dom/layers.rs | 36 +++++++- crates/engine/src/script/dom/perspective.rs | 10 ++- crates/engine/src/script/mod.rs | 3 +- crates/engine/src/tests/script_dom.rs | 83 +++++++++++++++++++ .../src/tests/script_dom_perspective.rs | 39 +++++++++ docs/mcp.md | 3 +- 8 files changed, 178 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index a1928a19d6..7c2b633af3 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -46,11 +46,13 @@ pub(crate) fn only_grid_view_changed(now: &Document, before: &Document) -> bool return false; } let mut rest = now.clone(); - match b { + let mut normalized_before = before.clone(); + PerspectiveGrid::current(before).store(&mut normalized_before); + match normalized_before.unknown.get(persp::DOC_KEY) { Some(v) => rest.unknown.insert(persp::DOC_KEY.to_string(), v.clone()), None => rest.unknown.remove(persp::DOC_KEY), }; - rest == *before + rest == normalized_before } /// Change view state of the grid without an undo step. diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 9f60bd6cc5..bd0ef91f4b 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -178,8 +178,9 @@ pub(super) struct State { art: RefCell>, /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_artboards: RefCell>, - /// Each open document's uid and the index of its active artboard when the run started. - pub(super) boards_at_start: Vec<(u64, usize)>, + /// Each open document's uid and the index of its active artboard when the run started, and for + /// a document the run opened, the index before the run first added an artboard to it. + pub(super) boards_at_start: RefCell>, text: text::TextState, presets: RefCell>>, preset_bytes: Cell, @@ -190,7 +191,11 @@ pub(super) struct State { impl State { /// The state of a run whose heap is `heap_bytes` and that starts with the documents `docs` open. pub(super) fn new(heap_bytes: usize, docs: &[DocState]) -> Self { - Self { preset_limit: heap_bytes as u64, boards_at_start: docs.iter().map(|st| (st.uid, active_artboard(st))).collect(), ..Self::default() } + Self { + preset_limit: heap_bytes as u64, + boards_at_start: RefCell::new(docs.iter().map(|st| (st.uid, active_artboard(st))).collect()), + ..Self::default() + } } /// Whether a call's own savepoint is open: its commands take none of their own. diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 1e43abfbd7..3f16b07e2f 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -690,7 +690,9 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { let ids = art_list(h, st, kind, c)?; - let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + let at = ids.iter().position(|i| st.doc.node(*i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + h.charge_call(at.map_or(ids.len(), |i| i + 1) as u64)?; + let id = at.map(|i| &ids[i]); id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) }) } @@ -724,6 +726,18 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); Ok::<_, HostError>((ids, refused, on_locked)) })?; + // A container whose clipping mask is deleted is no longer clipped, so its next child does not become the mask. + let masked: Vec = with_doc(h, doc, |_, st| { + let d = &st.doc; + Ok::<_, HostError>( + ids.iter() + .filter_map(|id| { + let p = d.parent_of(*id)?; + d.node(p).filter(|n| n.clips() && n.children().and_then(|c| c.first()).is_some_and(|f| f.id == *id)).map(|_| p) + }) + .collect(), + ) + })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); @@ -733,7 +747,12 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } if !ids.is_empty() { - on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + on_doc(h, doc.uid, true, |h| { + for p in &masked { + command(h, "layer.clippingMask.toggle", &json!({"id": p.0}))?; + } + command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})) + })?; } Ok(Data::Undefined) } @@ -1249,8 +1268,21 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { if len >= max { return Err(HostError::Range(format!("a document has at most {max} artboards"))); } + // A document the run opened is compared from the index it had before its first new artboard. + let active = with_doc(h, doc, |_, st| Ok::<_, HostError>(active_artboard(st)))?; + { + let mut start = h.dom.boards_at_start.borrow_mut(); + if !start.iter().any(|(uid, _)| *uid == doc.uid) { + start.push((doc.uid, active)); + } + } let id = super::atomically(h, |h| { on_doc(h, doc.uid, true, |h| { + { + let mut s = h.session.borrow_mut(); + let st = s.document_mut(doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + st.active_artboard = st.doc.artboards.get(active_artboard(st)).map(|ab| ab.id); + } let (_, made) = command_value(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; let index = result_id(&made, "index") .and_then(|i| usize::try_from(i).ok()) diff --git a/crates/engine/src/script/dom/perspective.rs b/crates/engine/src/script/dom/perspective.rs index c3b0d2658b..18ebb1d10e 100644 --- a/crates/engine/src/script/dom/perspective.rs +++ b/crates/engine/src/script/dom/perspective.rs @@ -208,9 +208,9 @@ fn preset_settings(h: &Host, a: &[Data]) -> Answer { (ArtboardLayout::Row, true) => "RLRow", }; let preview = match d.preview_mode { - PreviewMode::Default => "DefaultPreview", - PreviewMode::Pixel => "PixelPreview", - PreviewMode::Overprint => "OverprintPreview", + PreviewMode::Default => Some("DefaultPreview"), + PreviewMode::Pixel => None, + PreviewMode::Overprint => Some("OverprintPreview"), }; let item = |k: &str, v: Data| (k.to_string(), v); let mut out = vec![ @@ -218,9 +218,11 @@ fn preset_settings(h: &Host, a: &[Data]) -> Answer { item("artboardSpacing", num(d.spacing)), item("colorMode", text(if cmyk { "DocumentColorSpace.CMYK" } else { "DocumentColorSpace.RGB" })), item("height", num(d.height)), - item("previewMode", text(format!("DocumentPreviewMode.{preview}"))), item("width", num(d.width)), ]; + if let Some(preview) = preview { + out.push(item("previewMode", text(format!("DocumentPreviewMode.{preview}")))); + } // The artboard count and `artboardRowsOrCols` are left out when `addDocument` cannot take them // back exactly (more than `MAX_ARTBOARDS`, or a grid by column set by its columns that no row // count lays out the same), so `addDocument` with the same preset keeps the preset's own. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index c012b317c2..cb4538f8b1 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2606,7 +2606,8 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); - if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &host.dom.boards_at_start, self.documents()) { + if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &host.dom.boards_at_start.borrow(), self.documents()) + { report["activeArtboards"] = boards; } let rejections = rejections_report(host, &job.realm); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 1a52f80111..0f6371d0f0 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -2382,6 +2382,29 @@ fn a_loop_over_groups_and_their_items_lists_each_collection_once() { assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}"); } +#[test] +fn scoped_name_lookups_charge_for_every_scan_of_a_cached_list() { + for grouped in [false, true] { + let (mut s, a, b) = doc(); + if grouped { + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + } + let scope = if grouped { "app.activeDocument.groupItems[0]" } else { "app.activeDocument.layers[0]" }; + run(&mut s, &format!("{scope}.pageItems[0].name = 'target';")).unwrap(); + let mut costs = Vec::new(); + for key in ["0", "'target'"] { + let mut calls = Vec::new(); + for lookups in [1, 2] { + let r = run(&mut s, &format!("var p = {scope}.pageItems; p.length; for (var i = 0; i < {lookups}; i++) p.index({key});")).unwrap(); + calls.push(r["hostCalls"].as_u64().unwrap()); + } + costs.push(calls[1] - calls[0]); + } + assert!(costs[1] > costs[0], "{costs:?}"); + } +} + #[test] fn group_items_remove_all_refuses_locked_groups() { let (mut s, a, b) = doc(); @@ -2397,6 +2420,30 @@ fn group_items_remove_all_refuses_locked_groups() { assert!(d.node(NodeId(g)).is_none() && d.node(a).is_none() && d.node(b).is_some()); } +#[test] +fn scoped_remove_all_clears_clipping_and_undo_restores_the_mask() { + for grouped in [false, true] { + let (mut s, a, b) = doc(); + let container = if grouped { + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()) + } else { + s.active().unwrap().doc.layer_containing(a).unwrap() + }; + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(container).unwrap().set_clips(true); + let scope = if grouped { "app.activeDocument.groupItems[0]" } else { "app.activeDocument.layers[0]" }; + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + run(&mut s, &format!("var c = {scope}; c.pageItems.removeAll(); c.groupItems.add();")).unwrap(); + let n = s.active().unwrap().doc.node(container).unwrap(); + assert!(!n.clips()); + assert_eq!(n.children().unwrap().len(), 1); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, before); + } +} + #[test] fn new_group_command_checks_its_parent() { let (mut s, a, _) = doc(); @@ -2510,6 +2557,42 @@ fn the_report_gives_the_active_artboard_the_run_leaves() { assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": active}])); } +#[test] +fn inserting_before_the_default_active_artboard_preserves_its_id_and_origin() { + { + let (mut s, _, _) = doc(); + let original = s.active().unwrap().doc.artboards[0].id; + assert!(s.active().unwrap().active_artboard.is_none()); + let r = run( + &mut s, + "var A = app.activeDocument.artboards; app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;\ + var before = A[0].artboardRect; A.insert([800, 0, 900, 100], 0);\ + vc.log(A.getActiveArtboardIndex()); vc.log(before); vc.log(A[1].artboardRect);", + ) + .unwrap(); + assert_eq!(s.active().unwrap().active_artboard, Some(original)); + assert_eq!(r["log"][0], 1); + assert_eq!(r["log"][1], r["log"][2]); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + } +} + +#[test] +fn the_report_gives_the_active_artboard_shift_in_a_document_created_during_the_run() { + let mut s = Session::new(); + let r = run( + &mut s, + "var d = app.documents.add(DocumentColorSpace.RGB, 100, 100);\ + var original = d.artboards[0]; d.artboards.insert([200, 0, 300, -100], 0);\ + vc.log(d.artboards.getActiveArtboardIndex()); vc.log(d.artboards[1].name === original.name);", + ) + .unwrap(); + assert_eq!(r["log"], json!([1, true])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + let st = s.active().unwrap(); + assert_eq!(st.active_artboard, Some(st.doc.artboards[1].id)); +} + #[test] fn the_report_gives_the_active_artboards_new_index_after_an_insert_or_remove() { let (mut s, _, _) = doc(); diff --git a/crates/engine/src/tests/script_dom_perspective.rs b/crates/engine/src/tests/script_dom_perspective.rs index c0c1bdbc80..b53f66d4cd 100644 --- a/crates/engine/src/tests/script_dom_perspective.rs +++ b/crates/engine/src/tests/script_dom_perspective.rs @@ -48,6 +48,31 @@ fn show_and_hide_change_the_view_without_an_undo_step() { assert_eq!(undo_steps(&s), before); } +#[test] +fn grid_view_migrates_legacy_attachments_without_an_undo_step() { + use vectorcraft_tools::distort::perspective::{self as persp, PerspectiveGrid, Plane}; + + for (call, edit) in [("showPerspectiveGrid", false), ("hidePerspectiveGrid", false), ("showPerspectiveGrid", true), ("hidePerspectiveGrid", true)] + { + let mut s = doc(); + let made = s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap(); + let id = NodeId(made["id"].as_u64().unwrap()); + let st = s.doc_mut().unwrap(); + let d = std::sync::Arc::make_mut(&mut st.doc); + let mut g = PerspectiveGrid::current(d); + g.visible = call == "hidePerspectiveGrid"; + g.attached.insert(id.0.to_string(), Plane::Right); + d.unknown.insert(persp::DOC_KEY.into(), serde_json::to_value(&g).unwrap()); + let before = undo_steps(&s); + let draw = if edit { "vc.run('shape.rectangle', {x: 50, y: 50, width: 10, height: 10});" } else { "" }; + run(&mut s, &format!("app.activeDocument.{call}(); {draw}")).unwrap(); + assert_eq!(undo_steps(&s), before + usize::from(edit)); + let d = &s.active().unwrap().doc; + assert_eq!(PerspectiveGrid::current(d).attachment_of(d, id), Some((Plane::Right, 0.0))); + assert!(d.node(id).unwrap().extras().perspective.is_some()); + } +} + #[test] fn grid_view_commands_in_a_run_add_no_undo_step_but_an_edit_still_does() { let mut s = doc(); @@ -276,6 +301,20 @@ fn get_preset_settings_given_back_to_add_document_makes_the_same_document() { } } +#[test] +fn pixel_preview_preset_settings_can_be_given_back_to_add_document() { + let mut s = Session::new(); + s.execute("file.newPresets.save", &json!({"name": "Letter", "previewMode": "pixel"})).unwrap(); + let out = log( + &mut s, + "var p = app.getPresetSettings('Print'); vc.log(p.previewMode === undefined);\ + var a = app.documents.addDocument('Print'); var b = app.documents.addDocument('Print', p);\ + vc.log([a.width, a.height, a.documentColorSpace]); vc.log([b.width, b.height, b.documentColorSpace]);", + ); + assert_eq!(out[0], json!(true)); + assert_eq!(out[1], out[2]); +} + #[test] fn startup_presets_list_names_presets_add_document_takes() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index dd31cd0e06..f707d0b75f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3167,7 +3167,8 @@ through `$`: document from that preset starts with, which `addDocument` takes back unchanged. It leaves out `units` when the preset's units are not one of the six `RulerUnits` values a new document takes, `rasterResolution` when the preset's PPI is not 72, 150 or 300, `numArtboards` and `artboardRowsOrCols` when the preset has more than 100 - artboards, and `artboardRowsOrCols` alone for a grid by column that no row count lays out the same, so + artboards, `previewMode` when the preset uses Pixel Preview, and `artboardRowsOrCols` alone for a grid by + column that no row count lays out the same, so `addDocument` with the same preset keeps the preset's own. `startupPresetsList` is a read-only array of the startup preset names, each of which `addDocument` and `getPresetSettings` take: `Print`, `Web`, `Mobile`, `Film & Video`, `Art & Illustration`, `Branding`, `Social`, `Basic CMYK` and `Basic RGB`, in that order, so From dbbd39963c2ea22a38b92361534e2ac6d22d8c74 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 10:48:25 -0800 Subject: [PATCH 16/88] Color Effects: Create Screen Print Marks draws registration targets and ink lines MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Object › Plug-ins › Color Effects › Create Screen Print Marks… (`addon.color.screenMarks`) draws marks for screen printing inside an artboard as document art, so they print, separate and export with the rest of the art. - Registration targets (a circle half the target's width with a cross through it) go at any of the four corners and four side centers, with a set size, stroke weight and inset, stroked in [Registration] or a spot swatch. - An optional line names the document's spot inks, each name filled with its own ink (tints and [Registration] left out), and an optional line gives the file name and the date and time in UTC, at the top or bottom, left or right, starting past a corner target. - The marks of each artboard are one group on a "Screen Print Marks" layer, made locked at the bottom of the stack. Running it again replaces that artboard's group and keeps the other artboards' groups and the selection. One undo step, none when the marks come out the same. - Unknown or repeated positions, values out of range or of the wrong type, an ink that is not [Registration] or a spot swatch, nothing to draw, and marks past the canvas edge are errors that leave the document unchanged. - The dialog previews on the canvas; its OK is off while nothing would be drawn. Plug-ins may call the command. - Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/addons/color.rs | 9 +- .../src/cmd/addons/color/screen_marks.rs | 379 ++++++++++++++++++ .../cmd/addons/color/screen_marks/tests.rs | 297 ++++++++++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/ui-egui/src/addons/color.rs | 6 +- .../ui-egui/src/addons/color/screen_marks.rs | 119 ++++++ .../src/addons/color/screen_marks/tests.rs | 145 +++++++ crates/ui-egui/src/addons/dialogs.rs | 1 + docs/mcp.md | 38 ++ docs/target-app-parity.md | 4 + 10 files changed, 994 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/addons/color/screen_marks.rs create mode 100644 crates/engine/src/cmd/addons/color/screen_marks/tests.rs create mode 100644 crates/ui-egui/src/addons/color/screen_marks.rs create mode 100644 crates/ui-egui/src/addons/color/screen_marks/tests.rs diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index c12eb2fa64..fa97d0bf56 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -4,13 +4,15 @@ //! objects that use spot colours, carry a live colour adjustment, or are images of a colour model, //! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest //! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend -//! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply -//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across. Its panel and its submenu, -//! Object › Plug-ins › Color Effects, are the UI's. +//! ([`legend`]) draws labelled chips of the document's swatches, Create Screen Print Marks +//! ([`screen_marks`]) draws registration targets and ink and file lines on the artboard, and Apply +//! Fill to Stroke and Apply Stroke to Fill ([`copy_paint`]) copy each object's own paint across. Its +//! panel and its submenu, Object › Plug-ins › Color Effects, are the UI's. pub mod legend; mod nearest; mod print_fixes; +pub mod screen_marks; #[cfg(test)] mod tests; @@ -95,6 +97,7 @@ pub fn specs() -> Vec { ] .into_iter() .chain(legend::specs()) + .chain(screen_marks::specs()) .collect() } diff --git a/crates/engine/src/cmd/addons/color/screen_marks.rs b/crates/engine/src/cmd/addons/color/screen_marks.rs new file mode 100644 index 0000000000..ceba23ec7d --- /dev/null +++ b/crates/engine/src/cmd/addons/color/screen_marks.rs @@ -0,0 +1,379 @@ +//! Create Screen Print Marks (`addon.color.screenMarks`; Object › Plug-ins › Color Effects › +//! Create Screen Print Marks…): registration targets at chosen corners and side centers of an +//! artboard, in [Registration] or a spot ink, with optional lines that list the document's spot +//! inks (each name in its own ink) and give the file name with the date and time. The marks are +//! document art, one group per artboard on a locked "Screen Print Marks" layer at the bottom of the +//! stack, so they print and export with the rest. Running it again replaces that artboard's marks, +//! in one undo step, and makes none when the marks would come out the same. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::Paint; +use vectorcraft_color::swatch::REGISTRATION; +use vectorcraft_doc::{Appearance, CharStyle, Document, LAYER_COLORS, LayerColor, MAX_COORD, Node, NodeId, NodeKind, TextObject, TextRun}; +use vectorcraft_geom::{Affine, Point, Rect, shapes}; + +use super::super::super::{CommandSpec, bad, clock_date, cmd, date_param, has_doc, index_opt, switch_or, text_param}; +use crate::{DocState, Result, Session}; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.color.screenMarks", + "Create Screen Print Marks", + ["Object", "Plug-ins", "Color Effects"], + None, + "{positions?: [topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight…] (each at most once; default: [top, bottom, left, right]; [] draws no targets), size?: target width in pt 4..1000 (36), weight?: stroke weight in pt 0.1..20 (1), inset?: pt from the artboard's edge to the target's outer edge -1000..1000 (18; below 0 the targets sit outside the artboard), ink?: \"[Registration]\" (default) or a spot swatch's name (the targets and the file line), inks?: false (a line naming the document's spot inks, each name in its own ink; tints and [Registration] left out), info?: false (a line with the file name, or the title of a document never saved, and the date and time in UTC), time?: Unix seconds (default: now; null, or no clock as on the web: no date), textSize?: pt 4..72 (9), textPlace?: \"top\"|\"bottom\" (default), textAlign?: \"left\" (default)|\"right\" (the lines start past a target ticked in that corner), artboard?: index (default: the active artboard), allArtboards?: false} draw registration targets (a circle half the target's width with a cross through it, stroked) inside each artboard, and the lines asked for, as one group per artboard on the layer \"Screen Print Marks\", which is made locked at the bottom of the stack when there is none; running it again replaces that artboard's group. One undo step, none when the marks come out the same; the selection is kept → {changed, layer, ids: [group id…], inks: [spot ink name…]}", + has_doc, + screen_marks + )] +} + +/// The command. +pub const COMMAND: &str = "addon.color.screenMarks"; + +/// Where a target can go, in the order the command draws them. +pub const POSITIONS: [&str; 8] = ["topLeft", "top", "topRight", "left", "right", "bottomLeft", "bottom", "bottomRight"]; +/// The targets drawn when `positions` is left out. +pub const DEFAULT_POSITIONS: [&str; 4] = ["top", "bottom", "left", "right"]; +/// The name of the layer the marks go on, and of each artboard's group. +pub const LAYER_NAME: &str = "Screen Print Marks"; +/// The object data key that marks the layer (`layer`) and each artboard's group (the artboard's id). +pub const KEY: &str = "vc-screen-print-marks"; +/// Most spot inks one line names. +const MAX_INKS: usize = 256; + +fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive) -> Result { + match p.get(key) { + None | Some(Value::Null) => Ok(default), + Some(v) => v + .as_f64() + .filter(|n| n.is_finite() && range.contains(n)) + .ok_or_else(|| bad(COMMAND, format!("`{key}` must be a number {}..{}", range.start(), range.end()))), + } +} + +/// One of `options` for `key`, else `default`. +fn choice(p: &Value, key: &str, options: [&'static str; 2], default: &'static str) -> Result<&'static str> { + match text_param(p, key, COMMAND)? { + None => Ok(default), + Some(v) => options.into_iter().find(|o| *o == v).ok_or_else(|| bad(COMMAND, format!("`{key}` must be {} or {}", options[0], options[1]))), + } +} + +/// The target positions `p` asks for, in [`POSITIONS`] order. +fn positions(p: &Value) -> Result> { + let asked: Vec<&str> = match p.get("positions") { + None | Some(Value::Null) => return Ok(POSITIONS.into_iter().filter(|w| DEFAULT_POSITIONS.contains(w)).collect()), + Some(Value::Array(a)) => { + a.iter().map(|v| v.as_str().ok_or_else(|| bad(COMMAND, "`positions` must be a list of position names"))).collect::>()? + } + Some(_) => return Err(bad(COMMAND, "`positions` must be a list of position names")), + }; + for (i, w) in asked.iter().enumerate() { + if !POSITIONS.contains(w) { + return Err(bad(COMMAND, format!("`{w}` is not a position: give {}", POSITIONS.join(", ")))); + } + if asked[..i].contains(w) { + return Err(bad(COMMAND, format!("`positions` names `{w}` twice"))); + } + } + Ok(POSITIONS.into_iter().filter(|w| asked.contains(w)).collect()) +} + +/// The paint of ink `name`: [Registration], or a spot swatch linked to it. +fn ink_paint(doc: &Document, name: &str) -> Result { + if name == REGISTRATION { + return Ok(Paint::registration()); + } + let w = doc.swatch(name).ok_or_else(|| bad(COMMAND, format!("no swatch named `{name}`")))?; + if !w.spot || w.tint_of().is_some() || w.paint.color().is_none() { + return Err(bad(COMMAND, format!("`{name}` is not a spot color swatch: give [Registration] or a spot swatch"))); + } + super::super::super::paint::swatch_solid(doc, name, None).map_err(|e| bad(COMMAND, e)) +} + +/// The document's spot inks in panel order, each with the paint that links to it: spot color +/// swatches that are not tints, [Registration] left out. +fn spot_inks(doc: &Document) -> Vec<(String, Paint)> { + doc.swatches_iter() + .filter(|w| w.spot && w.name != REGISTRATION && w.tint_of().is_none() && w.paint.color().is_some()) + .map(|w| (w.name.clone(), super::super::super::paint::swatch_solid(doc, &w.name, None).unwrap_or_else(|_| w.paint.clone()))) + .collect() +} + +/// The index of the view's active artboard: when the document no longer has it, the one the +/// document opened on, else the first. +fn active_artboard(st: &DocState) -> Option { + let d = &st.doc; + let at = |id: Option| id.and_then(|id| d.artboards.iter().position(|a| a.id == id)); + at(st.active_artboard).or_else(|| at(d.opened_artboard)).or((!d.artboards.is_empty()).then_some(0)) +} + +/// The settings every artboard's marks are drawn with. +struct Marks { + positions: Vec<&'static str>, + size: f64, + weight: f64, + inset: f64, + ink: Paint, + /// The lines of type, top to bottom: each a list of (text, fill) runs. + lines: Vec>, + style: CharStyle, + system_layout: bool, + top: bool, + left: bool, +} + +impl Marks { + /// The center of the target at `position` on artboard `r`. + fn center(&self, r: Rect, position: &str) -> Point { + let near = self.inset + self.size / 2.0; + let x = if position.ends_with("Left") || position == "left" { + r.x0 + near + } else if position.ends_with("Right") || position == "right" { + r.x1 - near + } else { + r.center().x + }; + let y = if position.starts_with("top") { + r.y0 + near + } else if position.starts_with("bottom") { + r.y1 - near + } else { + r.center().y + }; + Point::new(x, y) + } + + /// The target at `c`: a circle half the target's width and a cross the target's width, stroked. + fn target(&self, c: Point, alloc: &mut dyn FnMut() -> NodeId) -> Node { + let ap = Appearance::basic(Paint::None, self.ink.clone(), self.weight); + let (half, ring) = (self.size / 2.0, self.size / 4.0); + let paths = [ + shapes::ellipse(Rect::new(c.x - ring, c.y - ring, c.x + ring, c.y + ring)), + shapes::line(Point::new(c.x - half, c.y), Point::new(c.x + half, c.y)), + shapes::line(Point::new(c.x, c.y - half), Point::new(c.x, c.y + half)), + ]; + let children = paths.into_iter().map(|path| Arc::new(Node::path(alloc(), path, ap.clone()))).collect(); + let mut g = Node::group(alloc(), children); + g.name = Some("Registration Target".into()); + g + } + + /// A point type line of `runs` placed with its box's top-left (or top-right) corner at `at`, or + /// its bottom corner there when `from_bottom`. + fn line(&self, runs: &[(String, Paint)], at: Point, from_bottom: bool) -> (TextObject, f64) { + let runs: Vec = runs + .iter() + .map(|(text, fill)| { + let mut style = self.style.clone(); + style.fill = fill.clone(); + style.stroke = Paint::None; + TextRun::new(text.clone(), style) + }) + .collect(); + let mut t = TextObject::point(Point::ZERO, "", self.style.clone()); + t.runs = runs; + t.para = super::super::super::create::new_type_para(); + t.system_layout = self.system_layout; + super::super::super::typecmd::refresh_bounds(&mut t); + let b = t.cached_bounds.unwrap_or(Rect::new(0.0, -self.style.size * 0.8, 0.0, self.style.size * 0.2)); + let dx = if self.left { at.x - b.x0 } else { at.x - b.x1 }; + let dy = if from_bottom { at.y - b.y1 } else { at.y - b.y0 }; + t.xf = Affine::translate((dx, dy)); + (t, b.height()) + } + + /// The marks of artboard `r` (id `board`) as one group, with ids from `alloc` (the group's last). + fn group(&self, r: Rect, board: u32, alloc: &mut dyn FnMut() -> NodeId) -> Node { + let mut children: Vec> = self.positions.iter().map(|w| Arc::new(self.target(self.center(r, w), alloc))).collect(); + if !self.lines.is_empty() { + // The lines start past a target in the corner they start from. + let corner = match (self.top, self.left) { + (true, true) => "topLeft", + (true, false) => "topRight", + (false, true) => "bottomLeft", + (false, false) => "bottomRight", + }; + let skip = if self.positions.contains(&corner) { self.size + self.style.size } else { 0.0 }; + let x = if self.left { r.x0 + self.inset + skip } else { r.x1 - self.inset - skip }; + let gap = self.style.size * 0.25; + let mut placed = Vec::with_capacity(self.lines.len()); + if self.top { + let mut y = r.y0 + self.inset; + for runs in &self.lines { + let (t, h) = self.line(runs, Point::new(x, y), false); + y += h + gap; + placed.push(t); + } + } else { + let mut y = r.y1 - self.inset; + for runs in self.lines.iter().rev() { + let (t, h) = self.line(runs, Point::new(x, y), true); + y -= h + gap; + placed.insert(0, t); + } + } + children.extend(placed.into_iter().map(|t| Arc::new(Node::new(alloc(), NodeKind::Text(Box::new(t)))))); + } + let mut g = Node::group(alloc(), children); + g.name = Some(LAYER_NAME.into()); + g.edit_attrs(|a| a.data.push((KEY.into(), board.to_string()))); + g + } +} + +/// The marks layer: the top-level layer whose data says so. +fn marks_layer(doc: &Document) -> Option<&Arc> { + doc.layers.iter().find(|l| tag(l) == Some("layer")) +} + +/// What `n`'s data holds under [`KEY`]. +fn tag(n: &Node) -> Option<&str> { + n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str()) +} + +/// `n` with every object's id 0: marks drawn again compare equal to marks drawn the same way. +fn without_ids(n: &Node) -> Node { + let mut n = n.clone(); + n.id = NodeId(0); + if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + *c = Arc::new(without_ids(c)); + } + } + n +} + +fn screen_marks(s: &mut Session, p: &Value) -> Result { + const C: &str = COMMAND; + let positions = positions(p)?; + let size = number(p, "size", 36.0, 4.0..=1000.0)?; + let weight = number(p, "weight", 1.0, 0.1..=20.0)?; + let inset = number(p, "inset", 18.0, -1000.0..=1000.0)?; + let text_size = number(p, "textSize", 9.0, 4.0..=72.0)?; + let top = choice(p, "textPlace", ["top", "bottom"], "bottom")? == "top"; + let left = choice(p, "textAlign", ["left", "right"], "left")? == "left"; + let want_inks = switch_or(p, "inks", false, C)?; + let want_info = switch_or(p, "info", false, C)?; + let all = switch_or(p, "allArtboards", false, C)?; + let given_time = date_param(p, "time", C)?; + let ink_name = text_param(p, "ink", C)?.unwrap_or(REGISTRATION).to_string(); + let artboard = index_opt(p, "artboard", C)?; + if all && artboard.is_some() { + return Err(bad(C, "give `artboard` or `allArtboards`, not both")); + } + let st = s.doc()?; + let doc = &st.doc; + if doc.artboards.is_empty() { + return Err(bad(C, "the document has no artboards")); + } + let boards: Vec<(Rect, u32)> = if all { + doc.artboards.iter().map(|a| (a.rect, a.id)).collect() + } else { + let i = match artboard { + Some(i) => i, + None => active_artboard(st).unwrap_or(0), + }; + let a = doc.artboards.get(i).ok_or_else(|| bad(C, format!("there is no artboard {i}")))?; + vec![(a.rect, a.id)] + }; + let ink = ink_paint(doc, &ink_name)?; + let inks = if want_inks { spot_inks(doc) } else { vec![] }; + if inks.len() > MAX_INKS { + return Err(bad(C, format!("a line names at most {MAX_INKS} spot inks"))); + } + let file = st + .path + .as_deref() + .and_then(|path| std::path::Path::new(path).file_name()) + .map(|f| f.to_string_lossy().into_owned()) + .unwrap_or_else(|| doc.title.clone()); + let system_layout = doc.setup.system_layout; + if positions.is_empty() && inks.is_empty() && !want_info { + let why = if want_inks { "the document has no spot inks" } else { "give `positions`, `inks` or `info`" }; + return Err(bad(C, format!("nothing to draw: {why}"))); + } + let mut lines: Vec> = vec![]; + if !inks.is_empty() { + let last = inks.len() - 1; + lines.push( + inks.iter().enumerate().map(|(i, (name, paint))| (if i < last { format!("{name} ") } else { name.clone() }, paint.clone())).collect(), + ); + } + if want_info { + let date = clock_date(s, "time", given_time).map(|t| { + let [y, mo, d, h, mi, _] = vectorcraft_doc::metadata::civil(t); + format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02} UTC") + }); + let text = match date { + Some(date) => format!("{file} {date}"), + None => file, + }; + lines.push(vec![(text, ink.clone())]); + } + let style = super::super::super::create::new_type_style(s, &json!({ "size": text_size }), C)?; + let marks = Marks { positions, size, weight, inset, ink, lines, style, system_layout, top, left }; + let names: Vec = inks.into_iter().map(|(name, _)| name).collect(); + + // The marks as they would come out, to tell whether anything changes. + let st = s.doc()?; + let layer = marks_layer(&st.doc).map(|l| (l.id, l.children().cloned().unwrap_or_default())); + let drawn: Vec = boards.iter().map(|(r, board)| marks.group(*r, *board, &mut || NodeId(0))).collect(); + let reach = marks.weight; + let beyond = |b: Rect| [b.x0 - reach, b.y0 - reach, b.x1 + reach, b.y1 + reach].iter().any(|v| !v.is_finite() || v.abs() > MAX_COORD); + if drawn.iter().any(|g| g.geometric_bounds().is_some_and(beyond)) { + return Err(bad(C, format!("the marks would reach past the edge of the canvas (±{MAX_COORD} pt)"))); + } + if let Some((layer, kids)) = &layer { + let old = |board: u32| kids.iter().filter(|k| tag(k) == Some(board.to_string().as_str())).collect::>(); + let same = boards.iter().zip(&drawn).all(|((_, board), new)| matches!(old(*board).as_slice(), [one] if without_ids(one) == *new)); + if same { + let ids: Vec = boards.iter().filter_map(|(_, board)| old(*board).first().map(|g| g.id.0)).collect(); + return Ok(json!({ "changed": false, "layer": layer.0, "ids": ids, "inks": names })); + } + } + let (layer, ids) = s.edit("Create Screen Print Marks", |d, sel| { + let layer = match marks_layer(d).map(|l| l.id) { + Some(id) => id, + None => { + let id = d.alloc_id(); + let color = LayerColor::Preset((d.layers.len() % LAYER_COLORS.len()) as u8); + let mut l = Node::layer(id, LAYER_NAME, color); + l.locked = true; + l.edit_attrs(|a| a.data.push((KEY.into(), "layer".into()))); + d.insert(None, 0, l)?; + id + } + }; + let mut ids = Vec::with_capacity(boards.len()); + for (r, board) in &boards { + let board_tag = board.to_string(); + let kids = d.children(Some(layer)).cloned().unwrap_or_default(); + let old: Vec = kids.iter().filter(|k| tag(k) == Some(board_tag.as_str())).map(|k| k.id).collect(); + let at = kids.iter().position(|k| old.first() == Some(&k.id)).unwrap_or(usize::MAX); + // Only what the selection holds of the marks leaves it; the rest of the selection stays as it is. + let mut held = vec![]; + for k in kids.iter().filter(|k| old.contains(&k.id)) { + k.walk(&mut |n: &Node| { + if sel.objects.contains(&n.id) || sel.anchors.contains_key(&n.id) || sel.segments.contains_key(&n.id) { + held.push(n.id); + } + }); + } + if !held.is_empty() { + sel.remove_all(held); + } + d.remove_many(&old)?; + let g = marks.group(*r, *board, &mut || d.alloc_id()); + ids.push(g.id.0); + d.insert(Some(layer), at, g)?; + } + Ok((layer, ids)) + })?; + Ok(json!({ "changed": true, "layer": layer.0, "ids": ids, "inks": names })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs new file mode 100644 index 0000000000..7d356efd46 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs @@ -0,0 +1,297 @@ +use serde_json::{Value, json}; +use vectorcraft_color::Paint; +use vectorcraft_doc::{Node, NodeId, NodeKind}; +use vectorcraft_geom::Rect; + +use super::{COMMAND, LAYER_NAME}; +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +fn run(s: &mut Session, p: Value) -> Value { + s.execute(COMMAND, &p).unwrap() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn node(s: &Session, id: u64) -> Node { + s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone() +} + +/// The targets of group `g`: each one's three paths. +fn targets(g: &Node) -> Vec> { + g.children() + .unwrap() + .iter() + .filter(|n| n.name.as_deref() == Some("Registration Target")) + .map(|t| t.children().unwrap().iter().map(|p| (**p).clone()).collect()) + .collect() +} + +/// The type lines of group `g`, top to bottom as stored. +fn lines(g: &Node) -> Vec { + g.children() + .unwrap() + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some((**t).clone()), + _ => None, + }) + .collect() +} + +fn bounds(n: &Node) -> Rect { + n.geometric_bounds().unwrap() +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +/// The swatch solid paint `p` links to. +fn swatch_of(p: &Paint) -> Option { + match p { + Paint::Solid { swatch, .. } => swatch.clone(), + _ => None, + } +} + +#[test] +fn default_targets_go_on_a_locked_bottom_layer_in_registration_in_one_undo_step() { + let mut s = session(); + let art = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let undo = undo_len(&s); + let r = run(&mut s, json!({})); + assert_eq!(r["changed"], json!(true)); + assert_eq!(undo_len(&s), undo + 1, "one undo step"); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(art)], "the selection is kept"); + let doc = &s.doc().unwrap().doc; + let layer = &doc.layers[0]; + assert_eq!(layer.id.0, r["layer"].as_u64().unwrap(), "the marks layer is at the bottom of the stack"); + assert_eq!(layer.name.as_deref(), Some(LAYER_NAME)); + assert!(layer.locked && layer.visible, "the marks layer is locked"); + assert_eq!(doc.layers.len(), 2); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1, "one group for the active artboard"); + let g = node(&s, ids[0].as_u64().unwrap()); + assert_eq!(super::tag(&g), Some(doc.artboards[0].id.to_string().as_str())); + let t = targets(&g); + assert_eq!(t.len(), 4, "top, bottom, left and right by default"); + assert!(lines(&g).is_empty(), "no type lines unless asked for"); + for paths in &t { + assert_eq!(paths.len(), 3, "a ring and two cross lines"); + for p in paths { + assert!(p.appearance.stroke_paint().is_registration(), "stroked in [Registration]"); + assert!(p.appearance.fill_paint().is_none()); + assert!(close(p.appearance.stroke_width(), 1.0)); + } + } + // The top target: its 36 pt box 18 pt in from the top edge, centered across. + let top = &t[0]; + let ring = bounds(&top[0]); + assert!(close(ring.width(), 18.0) && close(ring.center().x, 300.0) && close(ring.center().y, 36.0), "{ring:?}"); + let across = bounds(&top[1]); + assert!(close(across.x0, 282.0) && close(across.x1, 318.0), "{across:?}"); + let down = bounds(&top[2]); + assert!(close(down.y0, 18.0) && close(down.y1, 54.0), "{down:?}"); + // Left, right and bottom. + let centers: Vec<_> = t.iter().map(|p| bounds(&p[0]).center()).collect(); + assert!(close(centers[1].x, 36.0) && close(centers[1].y, 200.0), "left: {:?}", centers[1]); + assert!(close(centers[2].x, 564.0) && close(centers[2].y, 200.0), "right: {:?}", centers[2]); + assert!(close(centers[3].x, 300.0) && close(centers[3].y, 364.0), "bottom: {:?}", centers[3]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers.len(), 1, "undo removes the layer and its marks"); +} + +#[test] +fn positions_size_weight_inset_and_a_spot_ink_shape_the_targets() { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap(); + let p = json!({"positions": ["bottomRight", "topLeft"], "size": 20, "weight": 0.5, "inset": -30, "ink": "Plate Red"}); + let r = run(&mut s, p); + let g = node(&s, r["ids"][0].as_u64().unwrap()); + let t = targets(&g); + assert_eq!(t.len(), 2); + // Drawn in POSITIONS order: top left first. A negative inset puts the targets outside. + let tl = bounds(&t[0][0]).center(); + let br = bounds(&t[1][0]).center(); + assert!(close(tl.x, -20.0) && close(tl.y, -20.0), "{tl:?}"); + assert!(close(br.x, 620.0) && close(br.y, 420.0), "{br:?}"); + assert!(close(bounds(&t[0][0]).width(), 10.0), "the ring is half the target's width"); + assert!(close(bounds(&t[0][1]).width(), 20.0)); + for p in t.iter().flatten() { + assert_eq!(swatch_of(&p.appearance.stroke_paint()).as_deref(), Some("Plate Red"), "the stroke links to the spot swatch"); + assert!(close(p.appearance.stroke_width(), 0.5)); + } +} + +#[test] +fn a_second_run_replaces_the_marks_and_an_unchanged_run_adds_no_undo_step() { + let mut s = session(); + let first = run(&mut s, json!({"size": 30})); + let layer = first["layer"].clone(); + let undo = undo_len(&s); + let again = run(&mut s, json!({"size": 30})); + assert_eq!(again["changed"], json!(false)); + assert_eq!(again["ids"], first["ids"], "the same group stays"); + assert_eq!(undo_len(&s), undo, "nothing changed: no undo step"); + let r = run(&mut s, json!({"size": 40, "positions": ["top"]})); + assert_eq!(r["changed"], json!(true)); + assert_eq!(r["layer"], layer, "the same layer is reused"); + assert_eq!(undo_len(&s), undo + 1); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.layers.len(), 2, "no second marks layer"); + let kids = doc.layers[0].children().unwrap(); + assert_eq!(kids.len(), 1, "the earlier marks are replaced"); + let t = targets(&kids[0]); + assert_eq!(t.len(), 1); + assert!(close(bounds(&t[0][1]).width(), 40.0)); + assert!(doc.node(NodeId(first["ids"][0].as_u64().unwrap())).is_none(), "the earlier group is gone"); +} + +#[test] +fn replacing_the_marks_keeps_a_selected_slice_selected() { + let mut s = session(); + run(&mut s, json!({})); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap(); + s.execute("object.slice.make", &json!({})).unwrap(); + s.execute("select.object.slices", &json!({})).unwrap(); + let before = s.doc().unwrap().selection.clone(); + assert!(!before.slices.is_empty()); + let r = run(&mut s, json!({"size": 50})); + assert_eq!(r["changed"], json!(true)); + assert!(s.doc().unwrap().selection == before, "the selection is kept as it was"); +} + +#[test] +fn marks_past_the_canvas_edge_are_refused() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 3999000, "y": 0, "width": 900, "height": 100})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let err = s.execute(COMMAND, &json!({"artboard": 1, "positions": ["right"], "inset": -1000})).unwrap_err().to_string(); + assert!(err.contains("edge of the canvas"), "{err}"); + assert!(s.doc().unwrap().doc == before); + run(&mut s, json!({"artboard": 1, "positions": ["right"]})); +} + +#[test] +fn every_artboard_gets_its_group_and_one_artboard_rerun_keeps_the_others() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 800, "y": 0, "width": 200, "height": 100})).unwrap(); + let r = run(&mut s, json!({"allArtboards": true, "positions": ["top"]})); + assert_eq!(r["ids"].as_array().unwrap().len(), 2); + let second = node(&s, r["ids"][1].as_u64().unwrap()); + let c = bounds(&targets(&second)[0][0]).center(); + assert!(close(c.x, 900.0) && close(c.y, 36.0), "the second artboard's own target: {c:?}"); + let only = run(&mut s, json!({"artboard": 1, "positions": ["bottom"]})); + assert_eq!(only["ids"].as_array().unwrap().len(), 1); + let doc = &s.doc().unwrap().doc; + let kids = doc.layers[0].children().unwrap(); + assert_eq!(kids.len(), 2, "the first artboard's marks stay"); + assert!(kids.iter().any(|k| k.id.0 == r["ids"][0].as_u64().unwrap())); + let c = bounds(&targets(&node(&s, only["ids"][0].as_u64().unwrap()))[0][0]).center(); + assert!(close(c.x, 900.0) && close(c.y, 64.0), "{c:?}"); +} + +#[test] +fn the_ink_line_names_each_spot_ink_in_its_own_ink_and_the_file_line_gives_name_and_time() { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Plate Blue", "color": "#1122cc", "spot": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Process", "color": "#22cc11"})).unwrap(); + s.execute("swatch.new", &json!({"colors": [{"swatch": "Plate Red", "tint": 50}]})).unwrap(); + // A tint swatch marked spot, as a file can hold one, is still a tint of its ink. + let st = s.doc_mut().unwrap(); + let mut tints = 0; + for w in std::sync::Arc::make_mut(&mut st.doc).swatches_iter_mut().filter(|w| w.tint_of().is_some()) { + w.spot = true; + tints += 1; + } + assert_eq!(tints, 1); + let title = s.doc().unwrap().doc.title.clone(); + // 2026-03-04 05:06 UTC. + let r = run(&mut s, json!({"positions": [], "inks": true, "info": true, "time": 1772600760})); + assert_eq!(r["inks"], json!(["Plate Red", "Plate Blue"]), "spot inks only: process, tints and [Registration] left out"); + let g = node(&s, r["ids"][0].as_u64().unwrap()); + assert!(targets(&g).is_empty()); + let l = lines(&g); + assert_eq!(l.len(), 2); + let names: Vec<_> = l[0].runs.iter().map(|run| (run.text.trim().to_string(), swatch_of(&run.style.fill))).collect(); + assert_eq!(names, [("Plate Red".into(), Some("Plate Red".into())), ("Plate Blue".into(), Some("Plate Blue".into()))]); + assert_eq!(l[1].plain_text(), format!("{title} 2026-03-04 05:06 UTC")); + assert!(l[1].runs[0].style.fill.is_registration(), "the file line prints on every plate"); + assert!(l.iter().all(|t| close(t.runs[0].style.size, 9.0))); + // At the bottom left by default: the file line is the lower one, both 18 pt in. + let doc = &s.doc().unwrap().doc; + let kids = g.children().unwrap(); + let texts: Vec<_> = kids.iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).collect(); + assert!(texts[0].y1 <= texts[1].y0 + 1e-6, "the ink line sits above the file line"); + assert!((texts[1].y1 - 382.0).abs() < 0.5 && (texts[0].x0 - 18.0).abs() < 0.5, "{texts:?}"); + // No date without a time. + let r = run(&mut s, json!({"positions": [], "info": true, "time": null})); + assert_eq!(lines(&node(&s, r["ids"][0].as_u64().unwrap()))[0].plain_text(), title); +} + +#[test] +fn lines_at_the_top_right_start_past_a_corner_target() { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap(); + let p = json!({"positions": ["topRight"], "inks": true, "textPlace": "top", "textAlign": "right", "textSize": 12}); + let r = run(&mut s, p); + let g = node(&s, r["ids"][0].as_u64().unwrap()); + let doc = &s.doc().unwrap().doc; + let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap(); + let target = bounds(&targets(&g)[0][1]); + // 600 - 18 (inset) - 36 (target) - 12 (a gap of the type size). + assert!((text.x1 - 534.0).abs() < 0.5, "{text:?}"); + assert!(text.x1 < target.x0, "the line clears the corner target"); + assert!((text.y0 - 18.0).abs() < 0.5, "{text:?}"); + assert!(close(lines(&g)[0].runs[0].style.size, 12.0)); +} + +#[test] +fn bad_params_are_refused_and_leave_the_document_unchanged() { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Process", "color": "#22cc11"})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = undo_len(&s); + for bad in [ + json!({"positions": ["middle"]}), + json!({"positions": ["top", "top"]}), + json!({"positions": "top"}), + json!({"positions": [1]}), + json!({"size": 2}), + json!({"size": "36"}), + json!({"weight": 0}), + json!({"inset": 5000}), + json!({"textSize": 100}), + json!({"textPlace": "middle"}), + json!({"textAlign": 1}), + json!({"ink": "Nope"}), + json!({"ink": "Process"}), + json!({"ink": 3}), + json!({"inks": "yes"}), + json!({"info": 1}), + json!({"time": "today", "info": true}), + json!({"artboard": 5}), + json!({"artboard": -1}), + json!({"artboard": 0, "allArtboards": true}), + json!({"positions": [], "inks": false, "info": false}), + json!({"positions": [], "inks": true}), + ] { + assert!(s.execute(COMMAND, &bad).is_err(), "{bad}"); + } + assert!(s.doc().unwrap().doc == before); + assert_eq!(undo_len(&s), undo); + // An ink line with no spot inks draws the targets and no line. + let r = run(&mut s, json!({"inks": true})); + assert_eq!(r["inks"], json!([])); + assert!(lines(&node(&s, r["ids"][0].as_u64().unwrap())).is_empty()); +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 783f971487..5c7b89aee1 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -28,6 +28,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.color.fillToStroke", "addon.color.filter", "addon.color.nearestSwatch", + "addon.color.screenMarks", "addon.color.select", "addon.color.strokeToFill", "addon.color.swatchLegend", diff --git a/crates/ui-egui/src/addons/color.rs b/crates/ui-egui/src/addons/color.rs index 6696e4b0d3..70e30e9f12 100644 --- a/crates/ui-egui/src/addons/color.rs +++ b/crates/ui-egui/src/addons/color.rs @@ -3,11 +3,12 @@ //! filter, into the colours themselves (`addon.color.filter`); below, under Inks, it opens Duotone's //! dialog and Print Ink Fixes' (`addon.color.printFixes`). The submenu applies the add-on's live //! effects, Duotone and Vector Halftone among them (Effect › Color Effects has them too), opens -//! Print Ink Fixes, Find Nearest Swatch ([`nearest`]) and Create Swatch Legend ([`legend`]) and -//! opens the panel. +//! Print Ink Fixes, Find Nearest Swatch ([`nearest`]), Create Swatch Legend ([`legend`]) and Create +//! Screen Print Marks ([`screen_marks`]) and opens the panel. pub mod legend; pub mod nearest; +pub mod screen_marks; use craft::imaging::ui::adjust::{AdjustContext, AdjustField, AdjustSliders}; use craft::menu::Node; @@ -112,6 +113,7 @@ pub fn menu() -> Vec { cmd(print_fixes()), c("Find Nearest Swatch…", nearest::COMMAND), c("Create Swatch Legend…", legend::COMMAND), + c("Create Screen Print Marks…", screen_marks::COMMAND), Sep, // Each selected object's stroke takes its own fill, or the other way (#5530). cp("Apply Fill to Stroke", "addon.color.fillToStroke", json!({})), diff --git a/crates/ui-egui/src/addons/color/screen_marks.rs b/crates/ui-egui/src/addons/color/screen_marks.rs new file mode 100644 index 0000000000..ebd73fe0c7 --- /dev/null +++ b/crates/ui-egui/src/addons/color/screen_marks.rs @@ -0,0 +1,119 @@ +//! Create Screen Print Marks in the interface (Object › Plug-ins › Color Effects › Create Screen +//! Print Marks…): a dialog for where the registration targets go, their size, stroke weight, inset +//! and ink, the spot ink and file lines with their type size and place, and whether every artboard +//! gets marks. It previews on the canvas and runs `addon.color.screenMarks` on OK. + +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; +use serde_json::{Value, json}; +use vectorcraft_color::swatch::REGISTRATION; + +use crate::VectorcraftApp; +use crate::addons::dialogs::{self, Spec}; +use crate::canvas::rulers::{general_lengths, stroke_lengths, type_lengths}; + +/// The command. +pub const COMMAND: &str = "addon.color.screenMarks"; +/// The target positions: (the command's name, the dialog's label), in the command's order. +pub const POSITIONS: [(&str, &str); 8] = [ + ("topLeft", "Top Left"), + ("top", "Top Center"), + ("topRight", "Top Right"), + ("left", "Left Center"), + ("right", "Right Center"), + ("bottomLeft", "Bottom Left"), + ("bottom", "Bottom Center"), + ("bottomRight", "Bottom Right"), +]; +/// The positions ticked when the dialog opens: the command's default. +const TICKED: [&str; 4] = ["top", "bottom", "left", "right"]; + +/// How the dialog's values reach the command. +pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None }; + +/// The positions ticked in `fields`, in the command's order. +fn ticked(fields: &DialogFields) -> Vec<&'static str> { + POSITIONS.iter().filter(|(key, _)| fields.bool(key).unwrap_or(false)).map(|(key, _)| *key).collect() +} + +/// Whether `fields` ask for anything to be drawn: a target, the file line, or the spot ink line of a document +/// that has spot inks (`spots`). +fn draws(fields: &DialogFields, spots: bool) -> bool { + !ticked(fields).is_empty() || (spots && fields.bool("inks").unwrap_or(false)) || fields.bool("info").unwrap_or(false) +} + +/// The command's params from the dialog's fields. +pub(crate) fn params(fields: &DialogFields) -> Value { + json!({ + "positions": ticked(fields), + "size": fields.number("size").unwrap_or(36.0), + "weight": fields.number("weight").unwrap_or(1.0), + "inset": fields.number("inset").unwrap_or(18.0), + "ink": fields.text("ink").unwrap_or(REGISTRATION), + "inks": fields.bool("inks").unwrap_or(false), + "info": fields.bool("info").unwrap_or(false), + "textSize": fields.number("textSize").unwrap_or(9.0), + "textPlace": fields.text("textPlace").unwrap_or("bottom"), + "textAlign": fields.text("textAlign").unwrap_or("left"), + "allArtboards": fields.bool("allArtboards").unwrap_or(false), + }) +} + +/// Opens Create Screen Print Marks' dialog on the command's defaults. The ink list is [Registration] and the +/// document's spot swatches, read once, when it opens. +pub(crate) fn open(app: &mut VectorcraftApp) -> Result { + let mut inks = vec![REGISTRATION.to_string()]; + if let Some(st) = app.session.active() { + inks.extend( + st.doc + .swatches_iter() + .filter(|w| w.spot && w.name != REGISTRATION && w.tint_of().is_none() && w.paint.color().is_some()) + .map(|w| w.name.clone()), + ); + } + let mut fields = DialogFields::from_pairs([ + ("size", FieldValue::Number(36.0)), + ("weight", FieldValue::Number(1.0)), + ("inset", FieldValue::Number(18.0)), + ("ink", FieldValue::Text(REGISTRATION.into())), + ("inks", FieldValue::Bool(false)), + ("info", FieldValue::Bool(false)), + ("textSize", FieldValue::Number(9.0)), + ("textPlace", FieldValue::Text("bottom".into())), + ("textAlign", FieldValue::Text("left".into())), + ("allArtboards", FieldValue::Bool(false)), + ]); + for (key, _) in POSITIONS { + fields.set(key, FieldValue::Bool(TICKED.contains(&key))); + } + let (lengths, strokes, types) = (general_lengths(app), stroke_lengths(app), type_lengths(app)); + dialogs::open(app, &SPEC, fields, move |fields| { + let ink_choices = inks.iter().map(|name| (name.clone(), name.clone().into())).collect(); + let places = vec![("bottom".to_string(), tl!("Bottom").into()), ("top".to_string(), tl!("Top").into())]; + let aligns = vec![("left".to_string(), tl!("Left").into()), ("right".to_string(), tl!("Right").into())]; + let mut rows = vec![Param::section(tl!("Targets:"))]; + rows.extend(POSITIONS.iter().map(|&(key, label)| Param::new(key, tl!(label), ParamKind::bool(TICKED.contains(&key))))); + rows.extend([ + Param::number("size", tl!("Size:"), 36.0, 1.0, 2).length(lengths).bounds(Some(4.0), Some(1000.0)), + Param::number("weight", tl!("Weight:"), 1.0, 0.1, 2).length(strokes).bounds(Some(0.1), Some(20.0)), + Param::number("inset", tl!("Inset:"), 18.0, 1.0, 2).length(lengths).bounds(Some(-1000.0), Some(1000.0)), + Param::new("ink", tl!("Ink:"), ParamKind::choice(ink_choices, Some(REGISTRATION.into()))), + Param::section(tl!("Text:")), + Param::new("inks", tl!("Spot Ink Names"), ParamKind::bool(false)), + Param::new("info", tl!("File Name and Date"), ParamKind::bool(false)), + Param::number("textSize", tl!("Type Size:"), 9.0, 1.0, 1).length(types).bounds(Some(4.0), Some(72.0)), + Param::new("textPlace", tl!("Place:"), ParamKind::choice(places, Some("bottom".into()))), + Param::new("textAlign", tl!("Align:"), ParamKind::choice(aligns, Some("left".into()))), + Param::new("allArtboards", tl!("All Artboards"), ParamKind::bool(false)), + ]); + let ok = draws(fields, inks.len() > 1); + ParamDialog::new(COMMAND, tl!("Create Screen Print Marks"), rows) + .ok_enabled(ok) + .ok_reason(tl!("Tick a target or a line of text.").into()) + .values(Bind::bound(fields)) + .previews(true) + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/color/screen_marks/tests.rs b/crates/ui-egui/src/addons/color/screen_marks/tests.rs new file mode 100644 index 0000000000..bb20f032f6 --- /dev/null +++ b/crates/ui-egui/src/addons/color/screen_marks/tests.rs @@ -0,0 +1,145 @@ +use craft::behavior::Mixed; +use craft::ui::contract::Role; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; +use serde_json::json; +use vectorcraft_doc::{Node, NodeKind}; + +use crate::VectorcraftApp; +use crate::addons::dialogs::tests as host; +use crate::tests::panel_harness::Panel; + +/// The marks group of the active document's marks layer: its targets' rings' widths and its type lines. +fn marks(app: &VectorcraftApp) -> Option<(Vec, Vec)> { + let doc = &app.session.active()?.doc; + let layer = doc.layers.iter().find(|l| l.name.as_deref() == Some("Screen Print Marks"))?; + let group: &Node = layer.children()?.first()?; + let kids = group.children()?; + let rings = kids + .iter() + .filter(|n| n.name.as_deref() == Some("Registration Target")) + .map(|t| t.children().unwrap()[0].geometric_bounds().unwrap().width()) + .collect(); + let lines = kids + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some(t.plain_text()), + _ => None, + }) + .collect(); + Some((rings, lines)) +} + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + app.run("swatch.new", json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap(); + app +} + +/// Keyboard and checkbox edits reach the preview; Cancel restores the drawing, while OK with Preview off applies the +/// same values in one undo step. +#[test] +fn keyboard_and_checkbox_edits_reach_the_preview_ok_and_cancel() { + for commit in [false, true] { + let app = app(); + let before = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 1000.0)); + crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({})); + panel.frame(); + assert_eq!(panel.toggled("Preview"), Some(Mixed::Same(true)), "Preview starts on"); + assert!(panel.app().session.in_interaction(), "the opening marks are previewed"); + assert_eq!(marks(&panel.app()).map(|(rings, _)| rings.len()), Some(4), "four targets on opening"); + if commit { + panel.click_role("Preview", Role::CHECK_BOX); + assert!(!panel.app().session.in_interaction()); + } + panel.click_role("Left Center", Role::CHECK_BOX); + panel.click_role("Right Center", Role::CHECK_BOX); + panel.click_role("Spot Ink Names", Role::CHECK_BOX); + panel.click_role("Size", Role::SPIN_BUTTON); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("40 pt"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); + let edited = |app: &VectorcraftApp| { + let (rings, lines) = marks(app).expect("the marks layer"); + assert_eq!(rings.len(), 2, "the unticked sides draw no target"); + assert!(rings.iter().all(|w| (w - 20.0).abs() < 1e-6), "the typed size reaches the targets: {rings:?}"); + assert_eq!(lines, ["Plate Red"], "the spot ink line"); + }; + if commit { + assert!(panel.app().session.active().unwrap().doc == before, "Preview off leaves the drawing alone"); + panel.click("OK"); + panel.frame(); + edited(&panel.app()); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + panel.app().run("edit.undo", json!({})).unwrap(); + } else { + edited(&panel.app()); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "Preview adds no undo step"); + panel.click("Cancel"); + panel.frame(); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + } + assert!(!panel.app().session.in_interaction()); + assert!(panel.app().session.active().unwrap().doc == before, "Cancel or Undo restores the original drawing"); + assert!(crate::tests::picks::open_dialogs(&panel.app()).is_empty()); + } +} + +/// With no target ticked and no line, OK is off; a spot ink picked in the dialog strokes the targets. +#[test] +fn ok_needs_something_to_draw_and_the_ink_list_offers_the_spot_swatches() { + let mut app = crate::testing::windowed(app()); + host::open_item(&mut app, "Color Effects", "Create Screen Print Marks…"); + let id = host::dialog_id(&app); + for key in ["top", "bottom", "left", "right"] { + host::set(&app, id, key, json!(false)); + } + host::frame(&mut app); + assert!(!host::confirm(&app, id), "nothing to draw: OK is off"); + host::set(&app, id, "topLeft", json!(true)); + host::set(&app, id, "ink", json!("Plate Red")); + host::frame(&mut app); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(!app.any_dialog_open()); + let doc = &app.session.active().unwrap().doc; + let layer = &doc.layers[0]; + assert!(layer.locked, "the marks layer is locked at the bottom"); + let target = &layer.children().unwrap()[0].children().unwrap()[0]; + let ring = &target.children().unwrap()[0]; + let linked = match ring.appearance.stroke_paint() { + vectorcraft_color::Paint::Solid { swatch, .. } => swatch, + _ => None, + }; + assert_eq!(linked.as_deref(), Some("Plate Red")); +} + +/// The ticked positions go in the command's order; every other value goes as the dialog holds it. +#[test] +fn params_lists_the_ticked_positions_in_order() { + let fields = DialogFields::from_pairs([ + ("bottomRight", FieldValue::Bool(true)), + ("topLeft", FieldValue::Bool(true)), + ("top", FieldValue::Bool(false)), + ("textPlace", FieldValue::Text("top".into())), + ("info", FieldValue::Bool(true)), + ]); + let p = super::params(&fields); + assert_eq!(p["positions"], json!(["topLeft", "bottomRight"])); + assert_eq!(p["textPlace"], json!("top")); + assert_eq!(p["info"], json!(true)); + assert_eq!(p["ink"], json!("[Registration]")); + assert!(p.get("time").is_none(), "the date is the time of the run"); +} + +/// Spot Ink Names alone draws something only in a document with spot inks. +#[test] +fn the_spot_ink_line_alone_needs_spot_inks() { + let fields = DialogFields::from_pairs([("inks", FieldValue::Bool(true))]); + assert!(!super::draws(&fields, false)); + assert!(super::draws(&fields, true)); +} diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index e58443e259..2035c1e202 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -107,6 +107,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option typetools::open, color::legend::COMMAND => color::legend::open, color::nearest::COMMAND => color::nearest::open, + color::screen_marks::COMMAND => color::screen_marks::open, select::COMMAND => select::open, _ => return super::arrange::open(app, id), }; diff --git a/docs/mcp.md b/docs/mcp.md index 7ed0eebae6..5ed80f8fe1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17526,6 +17526,44 @@ images and patterns keep their colours. → `{changed, swatches: [the document s {"name":"run_command","arguments":{"command":"addon.color.applyNearestSwatch","params":{"library":"document","stroke":false}}} ``` +### Create Screen Print Marks + +`addon.color.screenMarks {positions?, size?, weight?, inset?, ink?, inks?, info?, time?, textSize?, textPlace?, +textAlign?, artboard?, allArtboards?}` (Object › Plug-ins › Color Effects › Create Screen Print Marks…) draws marks for +screen printing inside an artboard as document art, so they print, separate and export with the rest of the art: + +- Registration targets, each a circle half the target's width with a cross the target's width through it, stroked and + unfilled. `positions` lists where they go: any of `topLeft`, `top`, `topRight`, `left`, `right`, `bottomLeft`, + `bottom`, `bottomRight`, each at most once (default: `top`, `bottom`, `left` and `right`; `[]` draws none). `size` + is the target's width in pt, 4…1000 (36); `weight` is the stroke weight, 0.1…20 (1); `inset` is the distance from + the artboard's edge to the target's outer edge, −1000…1000 (18), and a negative inset puts the targets outside the + artboard. +- `ink` is the targets' stroke: `"[Registration]"` (the default), which prints on every plate, or the name of a spot + swatch, linked to it. +- `inks: true` adds a line that names the document's spot inks in panel order, each name filled with its own ink. Tint + swatches, process colors and [Registration] are left out, and with no spot ink the line is left out. A line names + at most 256 inks. +- `info: true` adds a line with the file name (the title of a document never saved) and the date and time in UTC + (`2026-03-04 05:06 UTC`), filled with `ink`. `time` is Unix seconds (default: now); `null`, or no clock (the web), + leaves the date out. +- `textSize` is the lines' type size, 4…72 pt (9). `textPlace` is `"top"` or `"bottom"` (the default) and + `textAlign` is `"left"` (the default) or `"right"`: the lines sit `inset` in from that edge and side, the spot ink + line above the file line, and start past a target ticked in that corner. + +The marks of each artboard are one group, on the top-level layer "Screen Print Marks". When the document has no such +layer, the command makes it at the bottom of the stack, locked. A layer moved, unlocked or hidden stays as it is. +`artboard` is an artboard's index (default: the active artboard) and `allArtboards: true` marks every artboard; +giving both is an error. Running the command again replaces that artboard's group and leaves the other artboards' +groups alone. It is one undo step, and none when the marks come out the same (`changed: false`). The selection is +kept. An unknown position or one named twice, a number out of range, an `ink` that is not [Registration] or a spot +swatch, a value of the wrong type, nothing to draw (no position, no file line, and no spot ink line or no spot ink to +name), and marks that would reach more than 4,000,000 pt from the origin are errors that leave the document unchanged. The dialog previews on the canvas, and its OK is off while nothing is ticked. +→ `{changed, layer, ids: [group id…], inks: [spot ink name…]}` + +```json +{"name":"run_command","arguments":{"command":"addon.color.screenMarks","params":{"positions":["topLeft","topRight","bottomLeft","bottomRight"],"inks":true,"info":true}}} +``` + ## Arrange Tools add-on Arrange Tools is a built-in add-on that lays out, swaps, replaces and sizes selected objects: its commands are diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f2d93a4568..8faf69b9ba 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3270,6 +3270,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition (it replaces a script some users ran), so no area score moves. Object › Plug-ins › Color Effects › Create Swatch Legend… (`addon.color.swatchLegend`) opens a dialog (columns, chip size, gap, values, selected swatches only, with a preview) and draws a chip per colour swatch (the selected ones, else all) filled with and linked to its swatch, labelled with its name and values (HEX, RGB, CMYK, Lab or Grayscale; by default its own model; spot swatches marked), black on light chips and white on dark ones, in a grid of chosen columns, chip size and spacing, as one selected group in one undo step (#4919). Tests: `cmd::addons::color::legend::tests` (engine), `addons::color::legend::tests::create_swatch_legend_opens_its_dialog_previews_and_runs_on_ok` (ui-egui). +## Create Screen Print Marks (2026-11-29) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Color Effects › Create Screen Print Marks… (`addon.color.screenMarks`) opens a dialog (the eight target positions, size, stroke weight, inset, ink, the spot ink and file lines with their type size, place and alignment, all artboards, with a preview) and draws registration targets (a circle half the target's width with a cross through it) inside the artboard in [Registration] or a spot ink, with an optional line naming the document's spot inks, each in its own ink, and an optional line with the file name and the date and time in UTC. The marks are document art: one group per artboard on a locked "Screen Print Marks" layer made at the bottom of the stack, so they print, separate and export with the rest of the art, where Create Trim Marks draws trim marks only and the PDF export's printer's marks exist only in the exported file. Running it again replaces that artboard's marks; one undo step, none when the marks come out the same. Remaining: saved presets of the dialog's settings. Tests: `cmd::addons::color::screen_marks::tests` (engine), `addons::color::screen_marks::tests` (ui-egui). + ## Stroke Weight Up and Down shortcuts (2026-11-06) Cmd/Ctrl+Alt+. (`stroke.weightUp`) and Cmd/Ctrl+Alt+, (`stroke.weightDown`) raise and lower the weight of each selected stroke from its own weight, with the keys a [public feature request reply](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/32307397-increment-decrement-stroke-weight-key-commands) names: a quarter unit of Units › Stroke at a time up to one unit, whole units above it, no lower than a quarter unit and no higher than 1000 pt. Type steps its stroked characters; objects without a stroke are left alone; with nothing selected the weight of the next object drawn steps. Each press is one undo step (#5797). Evidence: `tests::strokeux::stroke_weight_up_and_down_step_each_selected_stroke`, `stroke_weight_up_with_nothing_selected_sets_up_new_art`, `cmd::stroke::tests::weight_steps_follow_units_and_stop_at_their_bounds`. Scores unchanged. From eae7c8318f37e4823dbad0354eb1d2677b811f06 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 14:43:51 -0800 Subject: [PATCH 17/88] Scripts: layer loops list once, clipped and Artboards.insert follow the help pages - A Layers object keeps its list of layers while the document is unchanged, so a loop over layers.length and layers[i] lists them once. - GroupItem.clipped refuses a change to a group in a hidden or locked layer or on a locked artboard, before the mask changes. - Artboards.insert returns undefined, as the Artboards help page describes; add still returns the new artboard. - docs/mcp.md: Row and Column do not use artboardRowsOrCols for placement. --- crates/engine/src/script/dom.rs | 9 +++++ crates/engine/src/script/dom/layers.rs | 52 ++++++++++++++++++++++---- crates/engine/src/tests/script_dom.rs | 44 +++++++++++++++++++++- docs/mcp.md | 7 ++-- 4 files changed, 100 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 64fc714b74..8d12f16a4f 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -171,6 +171,12 @@ pub(super) enum Coords { const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; +#[cfg(test)] +thread_local! { + /// How many nodes the layer lists of `Layers` objects have looked at on this thread. + pub(crate) static LAYER_SCANS: Cell = const { Cell::new(0) }; +} + /// What the object model keeps for one run: its coordinate system, the lists of page items and the /// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read, /// each kept while its document is unchanged, the lists of paths, the point changes of a path not @@ -211,6 +217,9 @@ pub(super) struct State { /// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently /// used first, each kept while its document is unchanged. art: RefCell>, + /// The last [`layers::ART_LISTS`] lists of layers `Layers` objects gave, least recently used + /// first, each kept while its document is unchanged. + layers: RefCell>, /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_artboards: RefCell>, /// Each open document's uid and the index of its active artboard when the run started, and for diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 3f16b07e2f..7eddf8bb1c 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -473,9 +473,44 @@ fn layer_list(d: &Document, parent: Option) -> Vec { None => Some(&d.layers), Some(p) => d.children(Some(p)), }; + #[cfg(test)] + super::LAYER_SCANS.with(|c| c.set(c.get() + list.map_or(0, |l| l.len() as u64))); list.into_iter().flatten().rev().filter(|n| n.is_layer()).map(|n| n.id).collect() } +/// A document's uid, the document as it was, the parent a `Layers` object lists (`None`: the top +/// level) and the layers it listed then. +pub(super) type LayerList = (u64, Arc, Option, Rc>); + +/// The layers of `parent` as [`layer_list`] gives them. The last [`ART_LISTS`] lists are kept while +/// their documents are unchanged, so a loop over `layers[i]` lists the layers once. Each new list +/// is charged by the objects it looks at. +fn layers_listed(h: &Host, st: &DocState, parent: Option) -> Result>> { + { + let mut lists = h.dom.layers.borrow_mut(); + let at = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent); + if let Some(at) = at { + let list = lists.remove(at); + let ids = list.3.clone(); + lists.push(list); + return Ok(ids); + } + } + let looked_at = match parent { + None => st.doc.layers.len(), + Some(p) => st.doc.children(Some(p)).map_or(0, Vec::len), + }; + h.charge_call(looked_at as u64)?; + let ids = Rc::new(layer_list(&st.doc, parent)); + let mut lists = h.dom.layers.borrow_mut(); + lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); + if lists.len() >= ART_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), parent, ids.clone())); + Ok(ids) +} + fn layers_of(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; Ok(host_ref("Layers", &held_handle(h, doc.uid, id))) @@ -483,7 +518,7 @@ fn layers_of(h: &Host, a: &[Data]) -> Answer { fn layers_length(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; - Ok(num(float(with_doc(h, doc, |_, st| layer_list(&st.doc, parent).len()) as u64))) + Ok(num(float(with_doc(h, doc, |_, st| layers_listed(h, st, parent).map(|l| l.len()))? as u64))) } fn layers_parent(h: &Host, a: &[Data]) -> Answer { @@ -522,14 +557,14 @@ fn layers_at_position(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| layer_list(&st.doc, parent).get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id)))) + with_doc(h, doc, |_, st| Ok(layers_listed(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id)))) } fn layers_by_name(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { - let ids = layer_list(&st.doc, parent); + let ids = layers_listed(h, st, parent)?; h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); id.map(|id| layer_ref(h, st.uid, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -572,7 +607,7 @@ fn layers_remove_all(h: &Host, a: &[Data]) -> Answer { if parent.is_none() { return Err(HostError::Error("a document needs at least one layer".into())); } - let ids = with_doc(h, doc, |_, st| layer_list(&st.doc, parent)); + let ids = with_doc(h, doc, |_, st| layers_listed(h, st, parent))?; let max = crate::cmd::layer::MAX_ROWS; if ids.len() > max { return Err(HostError::Range(format!("cannot delete more than {max} layers at once"))); @@ -916,6 +951,7 @@ fn group_set_clipped(h: &Host, a: &[Data]) -> Answer { if now == on { return Ok(Data::Undefined); } + super::refuse_protected_edit(h, item)?; if !ok { return Err(HostError::Error(format!("Cannot change GroupItem {}: it is hidden or locked", item.id.0))); } @@ -1305,12 +1341,14 @@ fn boards_add(h: &Host, a: &[Data]) -> Answer { add_board(h, a, None) } -/// `artboards.insert(artboardRect, index)`: a new artboard at `index`. +/// `artboards.insert(artboardRect, index)`: a new artboard at `index`. It returns nothing, as the +/// Artboards page describes (). fn boards_insert(h: &Host, a: &[Data]) -> Answer { if matches!(arg(a, 2), Data::Undefined) { return Err(HostError::Type("insert needs an index".into())); } - add_board(h, a, Some(arg(a, 2))) + add_board(h, a, Some(arg(a, 2)))?; + Ok(Data::Undefined) } fn boards_remove(h: &Host, a: &[Data]) -> Answer { @@ -1474,7 +1512,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("index", method(l, boards_index), returns("Artboard", &[("itemKey", "*")])), ("getByName", method(l, boards_by_name), returns("Artboard", &[("name", "string")])), ("add", method(l, boards_add), returns("Artboard", &[("artboardRect", "Array")])), - ("insert", method(l, boards_insert), returns("Artboard", &[("artboardRect", "Array"), ("index", "number")])), + ("insert", method(l, boards_insert), returns("undefined", &[("artboardRect", "Array"), ("index", "number")])), ("remove", method(l, boards_remove), returns("undefined", &[("index", "number")])), ("getActiveArtboardIndex", method(l, boards_active), returns("number", &[])), ("setActiveArtboardIndex", method(l, boards_set_active), returns("undefined", &[("index", "number")])), diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 0c1f935e24..ca1091bcbf 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1866,6 +1866,45 @@ fn remove_refuses_hidden_or_locked_art_as_remove_all_does() { assert!(s.active().unwrap().doc.node(b).is_none()); } +/// `clipped` on a shown, unlocked group on a locked artboard throws and changes nothing; the same +/// value as the group has stays a no-op. +#[test] +fn clipped_refuses_a_group_on_a_locked_artboard() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 0.0, 0.0, 5.0, 5.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + run(&mut s, "app.activeDocument.groupItems[0].clipped = false;").unwrap(); + let e = failure(&mut s, "app.activeDocument.groupItems[0].clipped = true;"); + assert!(e.contains("locked artboard"), "{e}"); + assert!(!s.active().unwrap().doc.node(gid).unwrap().clips()); + assert_eq!(undo_steps(&s), steps); +} + +/// A loop over `layers.length` and `layers[i]` lists the layers once while the document is +/// unchanged, so it looks at each layer a bounded number of times. +#[test] +fn a_loop_over_layers_lists_them_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for _ in 0..39 { + s.execute("layer.new", &json!({})).unwrap(); + } + let n = s.active().unwrap().doc.layers.len() as u64; + crate::script::dom::LAYER_SCANS.with(|c| c.set(0)); + let out = log(&mut s, "var L = app.activeDocument.layers, n = 0; for (var i = 0; i < L.length; i++) { L[i]; n++; } vc.log(n);"); + assert_eq!(out, vec![json!(n)]); + let scans = crate::script::dom::LAYER_SCANS.with(std::cell::Cell::get); + assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers"); +} + /// Art on a locked artboard stays: `remove()` and `removeAll()` throw and delete nothing. #[test] fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { @@ -2607,10 +2646,11 @@ fn new_artboards_get_a_name_no_other_artboard_has() { let out = log( &mut s, "var A = app.activeDocument.artboards; A[0].name = 'Artboard 2';\ - vc.log(A.add([500, 300, 700, 100]).name); vc.log(A.insert([0, -100, 100, -200], 0).name);\ + vc.log(A.add([500, 300, 700, 100]).name); vc.log(A.insert([0, -100, 100, -200], 0) === undefined); vc.log(A[0].name);\ vc.log(A.add([800, 300, 900, 100]).name);", ); - assert_eq!(out, [json!("Artboard 3"), json!("Artboard 4"), json!("Artboard 5")]); + // `insert` returns nothing, as the Artboards page describes; `add` returns the new artboard. + assert_eq!(out, [json!("Artboard 3"), json!(true), json!("Artboard 4"), json!("Artboard 5")]); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 12456d9d2b..4542c9ffc3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2964,7 +2964,8 @@ through `$`: (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of - columns for the other layouts), and `addDocument(startupPreset, presetSettings?, showOptionsDialog?)`, which runs `file.new` + columns for `GridByRow` and `RLGridByRow`; `Row` and `RLRow` put every artboard in one row and `Column` puts + them in one column, without using it for placement), and `addDocument(startupPreset, presetSettings?, showOptionsDialog?)`, which runs `file.new` with the New Document profile `startupPreset` names (`Print`, `Web`, `Mobile`, `Video`, another profile of `file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset `file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()` @@ -3119,9 +3120,9 @@ through `$`: (https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/) has `pathItems`. `groupItems` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/) and `compoundPathItems` have `length`, `[i]`, `index(key)`, `getByName(name)`, `add()` and `removeAll()`. `groupItems.add()` runs `object.newGroup`. - `clipped` runs `layer.clippingMask.toggle`. `artboards` (https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/) + `clipped` runs `layer.clippingMask.toggle`; a change to a group on a locked artboard throws. `artboards` (https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/) has `length`, `[i]`, `index(key)`, `getByName(name)`, `add(artboardRect)` (runs `artboard.new`), - `insert(artboardRect, index)` (runs `artboard.new` and `artboard.reorder`), `remove(index)` (runs + `insert(artboardRect, index)` (runs `artboard.new` and `artboard.reorder`, and returns `undefined`), `remove(index)` (runs `artboard.delete`), `getActiveArtboardIndex()` and `setActiveArtboardIndex(index)`. An `Artboard` (https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/) has `typename`, `parent`, `artboardRect`, `name`, `rulerOrigin`, `rulerPAR` (0.1 to 10), `showCenter`, `showCrossHairs`, `showSafeAreas` and `remove()`; its From ff7c147ddeecd3f5c0af8bfb4e089376ec50a55d Mon Sep 17 00:00:00 2001 From: mocenigo Date: Tue, 1 Dec 2026 00:40:02 +0100 Subject: [PATCH 18/88] macOS: the window keeps its colours while it is resized wgpu-hal 30.0.1 set the Metal layer's colour space to nil each time the surface was configured, which egui does on every resize event. Until the next frame tagged the layer sRGB again, macOS showed the canvas untagged, in the display's own gamut, so the background changed shade while the window was resized and could stay so when it stopped. wgpu-hal 30.0.2 tags the layer sRGB when it configures the surface (gfx-rs/wgpu#10013). --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 772196967a..3b20a522f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9756,9 +9756,9 @@ dependencies = [ [[package]] name = "wgpu-hal" -version = "30.0.1" +version = "30.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58" +checksum = "a57452fe453658e141aafdb09de1028afa498805fab518238ddf372a518813ff" dependencies = [ "android_system_properties", "arrayvec", From 0eb7fbabf5cade97ae6c9c9f501e5834642617b2 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 20:54:30 -0800 Subject: [PATCH 19/88] Graph: enable editing commands only for a selected graph --- crates/engine/src/cmd/graph.rs | 2 +- crates/engine/src/cmd/graph/edit.rs | 5 +++++ crates/engine/src/lib.rs | 2 +- crates/ui-egui/src/menus/state.rs | 3 +++ crates/ui-egui/src/menus/tests.rs | 24 ++++++++++++++++++++++++ 5 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 06fb062e50..522c338bd2 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -42,7 +42,7 @@ pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv}; #[cfg(test)] use data::{fmt_value, to_csv}; pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs}; -pub use edit::{GraphTypeSubject, graph_type_subject}; +pub use edit::{GraphTypeSubject, graph_type_subject, has_graph_selection}; pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed}; pub use generate::calculated_axes; #[cfg(test)] diff --git a/crates/engine/src/cmd/graph/edit.rs b/crates/engine/src/cmd/graph/edit.rs index e5ce1e7ed0..c0278748f3 100644 --- a/crates/engine/src/cmd/graph/edit.rs +++ b/crates/engine/src/cmd/graph/edit.rs @@ -200,6 +200,11 @@ pub(super) fn target(s: &Session, p: &Value, cmd: &str) -> Result { Err(bad(cmd, "select a graph")) } +/// Whether a graph command can find a graph from the current selection. +pub fn has_graph_selection(s: &Session) -> bool { + target(s, &Value::Null, "graph.setData").is_ok() +} + pub(super) fn spec_of(s: &Session, id: NodeId) -> Result { s.doc()?.doc.node(id).and_then(|n| n.extras().graph.as_deref().cloned()).ok_or(EngineError::NoNode(id)) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index fb2115190c..2054adae6d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -33,7 +33,7 @@ pub use cmd::create::constrain_click; pub use cmd::distortcmds::{perspective_click, width_point_pair}; pub use cmd::flare::flare_settings; pub use cmd::gradient::{GradientEditPaints, StopOwner}; -pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject}; +pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject, has_graph_selection}; pub use cmd::params::{check_keys, check_params}; pub use cmd::pathops::{HAIRLINE_SLIVER_WIDTH, HAIRLINE_SLIVER_WIDTH_RANGE, auto_simplify_level, can_outline_stroke}; pub use cmd::rasterfx::{export_pdf, flatten_raster_effects}; diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 6ae7c66be0..8b8c10bd8a 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -294,6 +294,9 @@ pub(crate) fn why_off(app: &VectorcraftApp, id: &str) -> Option> } if let Some(c) = vectorcraft_engine::find_command(id) { return match (c.enabled)(&app.session) { + Ok(()) if matches!(id, "graph.setData" | "graph.setType" | "graph.column" | "graph.marker") => { + (!vectorcraft_engine::has_graph_selection(&app.session)).then(|| Some("select a graph".into())) + } Ok(()) => None, // The system clipboard's contents can be pasted into an open document with an empty // internal clipboard. diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 88c2e04540..544bb4fbd7 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -1083,6 +1083,30 @@ fn app_with_a_rectangle() -> VectorcraftApp { app } +#[test] +fn graph_menu_requires_a_live_graph_and_explicit_ids_still_work() { + let mut app = app_with_a_rectangle(); + let rectangle = app.session.active().unwrap().selection.objects[0]; + let commands = ["graph.setData", "graph.setType", "graph.column", "graph.marker"]; + assert!(commands.iter().all(|id| !enabled(&app, id))); + assert!(enabled(&app, "graph.design")); + + let graph = app.run("graph.create", json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 120})).unwrap(); + let graph = vectorcraft_engine::NodeId(graph["id"].as_u64().unwrap()); + let state = app.session.active().unwrap(); + let member = state.doc.node(graph).unwrap().children().unwrap()[0].id; + assert!(commands.iter().all(|id| enabled(&app, id))); + app.run("select.set", json!({"ids": [member.0]})).unwrap(); + assert!(commands.iter().all(|id| enabled(&app, id))); + app.run("select.none", json!({})).unwrap(); + assert!(commands.iter().all(|id| !enabled(&app, id))); + + app.run("select.set", json!({"ids": [rectangle.0]})).unwrap(); + let data = app.session.execute("graph.setData", &json!({"id": graph.0})).unwrap(); + assert!(data["csv"].is_string()); + assert_eq!(app.session.active().unwrap().selection.objects, [rectangle]); +} + /// The in-window Edit menu draws Undo and Redo with the step's name, as the History panel lists it. #[test] fn the_edit_menu_draws_undo_and_redo_with_the_step_name() { From 7843e6422b1e5ea39b209fbeaeb706a5cf31904c Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 21:08:22 -0800 Subject: [PATCH 20/88] Graph tests: use the public document node ID --- crates/ui-egui/src/menus/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 544bb4fbd7..5f381f468a 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -1092,7 +1092,7 @@ fn graph_menu_requires_a_live_graph_and_explicit_ids_still_work() { assert!(enabled(&app, "graph.design")); let graph = app.run("graph.create", json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 120})).unwrap(); - let graph = vectorcraft_engine::NodeId(graph["id"].as_u64().unwrap()); + let graph = vectorcraft_doc::NodeId(graph["id"].as_u64().unwrap()); let state = app.session.active().unwrap(); let member = state.doc.node(graph).unwrap().children().unwrap()[0].id; assert!(commands.iter().all(|id| enabled(&app, id))); From 43cccb74cf3a27e4844d40650173902d3fe14ff5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:01:15 -0800 Subject: [PATCH 21/88] Color Effects: list Create Screen Print Marks in ui.menuDialog ui.menuDialog opens the Create Screen Print Marks dialog for addon.color.screenMarks, so its params text and the MCP UI catalog now list that command. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 2c8f54eb6e..b848984bb0 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.color.screenMarks|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5681df62bf..2f1483103f 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.color.screenMarks|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", From 31f755960f571ac982e42dd03d1e466b9e751cc1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 07:14:51 -0800 Subject: [PATCH 22/88] Color Effects: screen print marks check type lines without the target weight The canvas-edge check padded every mark by the target stroke weight, so a line of type that fit inside the canvas could be refused. Only the stroked targets are padded now; each line of type is checked by its layout box and its glyphs' ink, underline and strikethrough bars included. --- crates/engine/src/cmd/addons/color/screen_marks.rs | 13 ++++++++++--- .../src/cmd/addons/color/screen_marks/tests.rs | 10 ++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/addons/color/screen_marks.rs b/crates/engine/src/cmd/addons/color/screen_marks.rs index ceba23ec7d..f4a02d4fdf 100644 --- a/crates/engine/src/cmd/addons/color/screen_marks.rs +++ b/crates/engine/src/cmd/addons/color/screen_marks.rs @@ -321,9 +321,16 @@ fn screen_marks(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let layer = marks_layer(&st.doc).map(|l| (l.id, l.children().cloned().unwrap_or_default())); let drawn: Vec = boards.iter().map(|(r, board)| marks.group(*r, *board, &mut || NodeId(0))).collect(); - let reach = marks.weight; - let beyond = |b: Rect| [b.x0 - reach, b.y0 - reach, b.x1 + reach, b.y1 + reach].iter().any(|v| !v.is_finite() || v.abs() > MAX_COORD); - if drawn.iter().any(|g| g.geometric_bounds().is_some_and(beyond)) { + // Only the stroked targets reach past their paths by the target weight. The lines of type have + // no stroke; their glyphs' ink, underline and strikethrough bars included, is checked as well. + let past = |b: Rect, reach: f64| [b.x0 - reach, b.y0 - reach, b.x1 + reach, b.y1 + reach].iter().any(|v| !v.is_finite() || v.abs() > MAX_COORD); + let beyond = |n: &Node| match &n.kind { + NodeKind::Text(t) => { + n.geometric_bounds().is_some_and(|b| past(b, 0.0)) || t.ink().flatten().is_some_and(|ink| past(t.xf.transform_rect_bbox(ink), 0.0)) + } + _ => n.geometric_bounds().is_some_and(|b| past(b, marks.weight)), + }; + if drawn.iter().any(|g| g.children().is_some_and(|kids| kids.iter().any(|k| beyond(k)))) { return Err(bad(C, format!("the marks would reach past the edge of the canvas (±{MAX_COORD} pt)"))); } if let Some((layer, kids)) = &layer { diff --git a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs index 7d356efd46..eed2fdf0f8 100644 --- a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs +++ b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs @@ -181,6 +181,16 @@ fn marks_past_the_canvas_edge_are_refused() { run(&mut s, json!({"artboard": 1, "positions": ["right"]})); } +#[test] +fn the_target_weight_does_not_pad_lines_of_type_at_the_canvas_edge() { + let mut s = session(); + // The artboard ends 10 pt inside the canvas edge. + s.execute("artboard.new", &json!({"x": 3999090, "y": 0, "width": 900, "height": 100})).unwrap(); + let p = json!({"artboard": 1, "positions": [], "info": true, "textAlign": "right", "inset": 0, "weight": 20}); + let r = run(&mut s, p); + assert_eq!(lines(&node(&s, r["ids"][0].as_u64().unwrap())).len(), 1); +} + #[test] fn every_artboard_gets_its_group_and_one_artboard_rerun_keeps_the_others() { let mut s = session(); From 3c60bf4d6adc82239b52b5c9df21667ba2af68be Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 13:11:52 -0800 Subject: [PATCH 23/88] Color Effects: screen print marks follow copied artboards and clear center targets - Copies of an artboard's marks made by Duplicate Artboards, Alt-drag and paste in the same document now belong to the new artboard, so marking either artboard replaces only its own group. - Lines that would cross the top or bottom target on their side move in past it, unless that would cross another target or leave the artboard. - null is refused for every param except time, instead of falling back to the default. - The no-op check looks up each existing group's artboard once. - docs/mcp.md says that marks outside the artboard appear in an export or print clipped to the artboard only as far as its bleed reaches. --- crates/engine/src/cmd/addons.rs | 1 + .../src/cmd/addons/color/screen_marks.rs | 118 +++++++++++---- .../cmd/addons/color/screen_marks/tests.rs | 138 ++++++++++++++++++ crates/engine/src/cmd/edit.rs | 16 +- crates/engine/src/cmd/panelcmds.rs | 5 + docs/mcp.md | 10 +- docs/target-app-parity.md | 2 +- 7 files changed, 256 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 9fa5806c52..418fb84d18 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -16,6 +16,7 @@ mod shapes; mod typetools; mod units; +pub(crate) use color::screen_marks::retag as retag_screen_marks; pub(crate) use image::{DecodedImages, refresh_color_masks}; pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; diff --git a/crates/engine/src/cmd/addons/color/screen_marks.rs b/crates/engine/src/cmd/addons/color/screen_marks.rs index f4a02d4fdf..b34f3b96ce 100644 --- a/crates/engine/src/cmd/addons/color/screen_marks.rs +++ b/crates/engine/src/cmd/addons/color/screen_marks.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Create Screen Print Marks", ["Object", "Plug-ins", "Color Effects"], None, - "{positions?: [topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight…] (each at most once; default: [top, bottom, left, right]; [] draws no targets), size?: target width in pt 4..1000 (36), weight?: stroke weight in pt 0.1..20 (1), inset?: pt from the artboard's edge to the target's outer edge -1000..1000 (18; below 0 the targets sit outside the artboard), ink?: \"[Registration]\" (default) or a spot swatch's name (the targets and the file line), inks?: false (a line naming the document's spot inks, each name in its own ink; tints and [Registration] left out), info?: false (a line with the file name, or the title of a document never saved, and the date and time in UTC), time?: Unix seconds (default: now; null, or no clock as on the web: no date), textSize?: pt 4..72 (9), textPlace?: \"top\"|\"bottom\" (default), textAlign?: \"left\" (default)|\"right\" (the lines start past a target ticked in that corner), artboard?: index (default: the active artboard), allArtboards?: false} draw registration targets (a circle half the target's width with a cross through it, stroked) inside each artboard, and the lines asked for, as one group per artboard on the layer \"Screen Print Marks\", which is made locked at the bottom of the stack when there is none; running it again replaces that artboard's group. One undo step, none when the marks come out the same; the selection is kept → {changed, layer, ids: [group id…], inks: [spot ink name…]}", + "{positions?: [topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight…] (each at most once; default: [top, bottom, left, right]; [] draws no targets), size?: target width in pt 4..1000 (36), weight?: stroke weight in pt 0.1..20 (1), inset?: pt from the artboard's edge to the target's outer edge -1000..1000 (18; below 0 the targets sit outside the artboard), ink?: \"[Registration]\" (default) or a spot swatch's name (the targets and the file line), inks?: false (a line naming the document's spot inks, each name in its own ink; tints and [Registration] left out), info?: false (a line with the file name, or the title of a document never saved, and the date and time in UTC), time?: Unix seconds (default: now; null, or no clock as on the web: no date), textSize?: pt 4..72 (9), textPlace?: \"top\"|\"bottom\" (default), textAlign?: \"left\" (default)|\"right\" (the lines start past a target ticked in that corner, and move in past the top or bottom target they would cross; they stay where they are when moving would cross another target or leave the artboard), artboard?: index (default: the active artboard), allArtboards?: false; null is refused except for time} draw registration targets (a circle half the target's width with a cross through it, stroked) inside each artboard, and the lines asked for, as one group per artboard on the layer \"Screen Print Marks\", which is made locked at the bottom of the stack when there is none; running it again replaces that artboard's group. One undo step, none when the marks come out the same; the selection is kept → {changed, layer, ids: [group id…], inks: [spot ink name…]}", has_doc, screen_marks )] @@ -45,7 +45,7 @@ const MAX_INKS: usize = 256; fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive) -> Result { match p.get(key) { - None | Some(Value::Null) => Ok(default), + None => Ok(default), Some(v) => v .as_f64() .filter(|n| n.is_finite() && range.contains(n)) @@ -64,7 +64,7 @@ fn choice(p: &Value, key: &str, options: [&'static str; 2], default: &'static st /// The target positions `p` asks for, in [`POSITIONS`] order. fn positions(p: &Value) -> Result> { let asked: Vec<&str> = match p.get("positions") { - None | Some(Value::Null) => return Ok(POSITIONS.into_iter().filter(|w| DEFAULT_POSITIONS.contains(w)).collect()), + None => return Ok(POSITIONS.into_iter().filter(|w| DEFAULT_POSITIONS.contains(w)).collect()), Some(Value::Array(a)) => { a.iter().map(|v| v.as_str().ok_or_else(|| bad(COMMAND, "`positions` must be a list of position names"))).collect::>()? } @@ -162,8 +162,8 @@ impl Marks { } /// A point type line of `runs` placed with its box's top-left (or top-right) corner at `at`, or - /// its bottom corner there when `from_bottom`. - fn line(&self, runs: &[(String, Paint)], at: Point, from_bottom: bool) -> (TextObject, f64) { + /// its bottom corner there when `from_bottom`, with its box. + fn line(&self, runs: &[(String, Paint)], at: Point, from_bottom: bool) -> (TextObject, Rect) { let runs: Vec = runs .iter() .map(|(text, fill)| { @@ -182,7 +182,28 @@ impl Marks { let dx = if self.left { at.x - b.x0 } else { at.x - b.x1 }; let dy = if from_bottom { at.y - b.y1 } else { at.y - b.y0 }; t.xf = Affine::translate((dx, dy)); - (t, b.height()) + (t, Rect::new(b.x0 + dx, b.y0 + dy, b.x1 + dx, b.y1 + dy)) + } + + /// The lines placed in a column from `y`, at `x`: down from `y` at the top, up + /// from it at the bottom. Each with its box. + fn column(&self, x: f64, mut y: f64) -> Vec<(TextObject, Rect)> { + let gap = self.style.size * 0.25; + let mut placed = Vec::with_capacity(self.lines.len()); + if self.top { + for runs in &self.lines { + let (t, b) = self.line(runs, Point::new(x, y), false); + y += b.height() + gap; + placed.push((t, b)); + } + } else { + for runs in self.lines.iter().rev() { + let (t, b) = self.line(runs, Point::new(x, y), true); + y -= b.height() + gap; + placed.insert(0, (t, b)); + } + } + placed } /// The marks of artboard `r` (id `board`) as one group, with ids from `alloc` (the group's last). @@ -198,24 +219,29 @@ impl Marks { }; let skip = if self.positions.contains(&corner) { self.size + self.style.size } else { 0.0 }; let x = if self.left { r.x0 + self.inset + skip } else { r.x1 - self.inset - skip }; - let gap = self.style.size * 0.25; - let mut placed = Vec::with_capacity(self.lines.len()); - if self.top { - let mut y = r.y0 + self.inset; - for runs in &self.lines { - let (t, h) = self.line(runs, Point::new(x, y), false); - y += h + gap; - placed.push(t); - } - } else { - let mut y = r.y1 - self.inset; - for runs in self.lines.iter().rev() { - let (t, h) = self.line(runs, Point::new(x, y), true); - y -= h + gap; - placed.insert(0, t); + let (edge, sign) = if self.top { (r.y0, 1.0) } else { (r.y1, -1.0) }; + let mut placed = self.column(x, edge + sign * self.inset); + // Lines that would cross the center target on their side move in past it, unless they + // would then cross another target or leave the artboard. + let side = if self.top { "top" } else { "bottom" }; + // A target's paint: its two bars and the box of its ring, each with half the stroke weight. + let (half, ring, w2) = (self.size / 2.0, self.size / 4.0 + self.weight / 2.0, self.weight / 2.0); + let crosses = |placed: &[(TextObject, Rect)], w: &str| { + let c = self.center(r, w); + let paint = [ + Rect::new(c.x - half - w2, c.y - w2, c.x + half + w2, c.y + w2), + Rect::new(c.x - w2, c.y - half - w2, c.x + w2, c.y + half + w2), + Rect::new(c.x - ring, c.y - ring, c.x + ring, c.y + ring), + ]; + placed.iter().any(|(_, b)| paint.iter().any(|p| b.x0 < p.x1 && b.x1 > p.x0 && b.y0 < p.y1 && b.y1 > p.y0)) + }; + if self.positions.contains(&side) && crosses(&placed, side) { + let moved = self.column(x, edge + sign * (self.inset + self.size + self.weight / 2.0 + self.style.size * 0.25)); + if moved.iter().all(|(_, b)| b.y0 >= r.y0 && b.y1 <= r.y1) && !self.positions.iter().any(|w| crosses(&moved, w)) { + placed = moved; } } - children.extend(placed.into_iter().map(|t| Arc::new(Node::new(alloc(), NodeKind::Text(Box::new(t)))))); + children.extend(placed.into_iter().map(|(t, _)| Arc::new(Node::new(alloc(), NodeKind::Text(Box::new(t)))))); } let mut g = Node::group(alloc(), children); g.name = Some(LAYER_NAME.into()); @@ -234,6 +260,29 @@ fn tag(n: &Node) -> Option<&str> { n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str()) } +/// The id of the artboard marks group `n` belongs to, from its data. +fn owner(n: &Node) -> Option { + tag(n)?.parse().ok() +} + +/// Make copy `n` of an artboard's marks group belong to the artboard copied with it: its data +/// names artboard `from`, and from now on names `to`. Duplicate Artboards, Alt-drag and paste call +/// it on each copy they make. → whether `n` was such a group. +pub(crate) fn retag(n: &mut Node, from: u32, to: u32) -> bool { + if owner(n) != Some(from) { + return false; + } + let (from, to) = (from.to_string(), to.to_string()); + n.edit_attrs(|a| { + for (k, v) in a.data.iter_mut() { + if k == KEY && *v == from { + v.clone_from(&to); + } + } + }); + true +} + /// `n` with every object's id 0: marks drawn again compare equal to marks drawn the same way. fn without_ids(n: &Node) -> Node { let mut n = n.clone(); @@ -260,6 +309,10 @@ fn screen_marks(s: &mut Session, p: &Value) -> Result { let all = switch_or(p, "allArtboards", false, C)?; let given_time = date_param(p, "time", C)?; let ink_name = text_param(p, "ink", C)?.unwrap_or(REGISTRATION).to_string(); + // Defaults are for values left out; only `time` takes null (no date). + if let Some((key, _)) = p.as_object().and_then(|o| o.iter().find(|(k, v)| v.is_null() && *k != "time")) { + return Err(bad(C, format!("`{key}` must not be null: leave it out for the default"))); + } let artboard = index_opt(p, "artboard", C)?; if all && artboard.is_some() { return Err(bad(C, "give `artboard` or `allArtboards`, not both")); @@ -333,14 +386,24 @@ fn screen_marks(s: &mut Session, p: &Value) -> Result { if drawn.iter().any(|g| g.children().is_some_and(|kids| kids.iter().any(|k| beyond(k)))) { return Err(bad(C, format!("the marks would reach past the edge of the canvas (±{MAX_COORD} pt)"))); } - if let Some((layer, kids)) = &layer { - let old = |board: u32| kids.iter().filter(|k| tag(k) == Some(board.to_string().as_str())).collect::>(); - let same = boards.iter().zip(&drawn).all(|((_, board), new)| matches!(old(*board).as_slice(), [one] if without_ids(one) == *new)); + // Each existing group under the artboard it belongs to, worked out once. + let mut owned: std::collections::HashMap>> = std::collections::HashMap::new(); + for k in layer.iter().flat_map(|(_, kids)| kids) { + if let Some(board) = owner(k) { + owned.entry(board).or_default().push(k); + } + } + if let Some((layer, _)) = &layer { + let same = boards + .iter() + .zip(&drawn) + .all(|((_, board), new)| matches!(owned.get(board).map(Vec::as_slice), Some([one]) if without_ids(one) == without_ids(new))); if same { - let ids: Vec = boards.iter().filter_map(|(_, board)| old(*board).first().map(|g| g.id.0)).collect(); + let ids: Vec = boards.iter().filter_map(|(_, board)| owned.get(board).and_then(|g| g.first()).map(|g| g.id.0)).collect(); return Ok(json!({ "changed": false, "layer": layer.0, "ids": ids, "inks": names })); } } + let owned: std::collections::HashMap> = owned.into_iter().map(|(b, g)| (b, g.into_iter().map(|k| k.id).collect())).collect(); let (layer, ids) = s.edit("Create Screen Print Marks", |d, sel| { let layer = match marks_layer(d).map(|l| l.id) { Some(id) => id, @@ -356,9 +419,8 @@ fn screen_marks(s: &mut Session, p: &Value) -> Result { }; let mut ids = Vec::with_capacity(boards.len()); for (r, board) in &boards { - let board_tag = board.to_string(); let kids = d.children(Some(layer)).cloned().unwrap_or_default(); - let old: Vec = kids.iter().filter(|k| tag(k) == Some(board_tag.as_str())).map(|k| k.id).collect(); + let old: Vec = owned.get(board).cloned().unwrap_or_default(); let at = kids.iter().position(|k| old.first() == Some(&k.id)).unwrap_or(usize::MAX); // Only what the selection holds of the marks leaves it; the rest of the selection stays as it is. let mut held = vec![]; diff --git a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs index eed2fdf0f8..f77928cd33 100644 --- a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs +++ b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs @@ -156,6 +156,21 @@ fn a_second_run_replaces_the_marks_and_an_unchanged_run_adds_no_undo_step() { assert!(doc.node(NodeId(first["ids"][0].as_u64().unwrap())).is_none(), "the earlier group is gone"); } +#[test] +fn widening_an_artboard_without_changing_the_marks_adds_no_undo_step() { + let mut s = session(); + let p = json!({"positions": ["topLeft"]}); + let first = run(&mut s, p.clone()); + let before = node(&s, first["ids"][0].as_u64().unwrap()); + s.execute("artboard.setProps", &json!({"index": 0, "width": 800})).unwrap(); + let undo = undo_len(&s); + let again = run(&mut s, p); + assert_eq!(again["changed"], json!(false)); + assert_eq!(again["ids"], first["ids"], "the same group stays"); + assert!(node(&s, again["ids"][0].as_u64().unwrap()) == before, "the existing group stays unchanged"); + assert_eq!(undo_len(&s), undo, "unchanged marks add no undo step after a resize"); +} + #[test] fn replacing_the_marks_keeps_a_selected_slice_selected() { let mut s = session(); @@ -266,6 +281,126 @@ fn lines_at_the_top_right_start_past_a_corner_target() { assert!(close(lines(&g)[0].runs[0].style.size, 12.0)); } +#[test] +fn lines_move_up_past_a_bottom_center_target_they_would_cross() { + let mut s = session(); + let p = json!({"positions": ["bottom"], "info": true, "time": 1772600760, "textSize": 72}); + let r = run(&mut s, p); + let g = node(&s, r["ids"][0].as_u64().unwrap()); + let doc = &s.doc().unwrap().doc; + let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap(); + let target = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap(); + assert!(text.x0 < target.x1 && text.x1 > target.x0, "the line is long enough to reach the target: {text:?} {target:?}"); + assert!(text.y1 <= target.y0, "the line sits above the bottom target: {text:?} {target:?}"); +} + +#[test] +fn lines_do_not_move_above_a_short_artboard_to_clear_a_bottom_target() { + let mut s = session(); + s.execute("artboard.setProps", &json!({"index": 0, "width": 100, "height": 56})).unwrap(); + let p = json!({"positions": [], "info": true, "time": 1772600760}); + let original = run(&mut s, p.clone()); + let original_bounds = bounds(&node(&s, original["ids"][0].as_u64().unwrap())); + let mut with_target = p; + with_target["positions"] = json!(["bottom"]); + let r = run(&mut s, with_target); + let g = node(&s, r["ids"][0].as_u64().unwrap()); + let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| bounds(n)).unwrap(); + let target = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap(); + assert!(text.x0 < target.x1 && text.x1 > target.x0, "the file line reaches the bottom target: {text:?} {target:?}"); + assert!(text.y0 >= 0.0 && text.y1 <= 56.0, "the line stays vertically inside the artboard: {text:?}"); + assert_eq!(text, original_bounds, "the line keeps its original placement when shifting would leave the artboard"); +} + +#[test] +fn lines_do_not_move_onto_the_opposite_target_on_a_short_artboard() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 110})).unwrap(); + let p = json!({"artboard": 1, "positions": ["top", "bottom"], "info": true, "time": 1772600760, "textSize": 24}); + let r = run(&mut s, p); + let g = node(&s, r["ids"][0].as_u64().unwrap()); + let doc = &s.doc().unwrap().doc; + let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap(); + let top = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap(); + assert!(text.x1 <= top.x0 || text.y0 >= top.y1, "the line stays off the top target: {text:?} {top:?}"); +} + +#[test] +fn marks_copied_with_a_duplicated_artboard_belong_to_the_copy() { + let mut s = session(); + run(&mut s, json!({})); + s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len(); + assert_eq!(kids(&s), 2, "the duplicate carries a copy of the marks"); + let copy = run(&mut s, json!({"artboard": 1, "size": 30})); + assert_eq!(kids(&s), 2, "marking the duplicate replaces the copy"); + let source = run(&mut s, json!({})); + assert_eq!(source["changed"], json!(false), "the source artboard's marks are unchanged"); + assert_eq!(kids(&s), 2); + assert!(s.doc().unwrap().doc.node(NodeId(copy["ids"][0].as_u64().unwrap())).is_some(), "the duplicate's marks stay"); +} + +#[test] +fn marks_copied_with_a_pasted_artboard_belong_to_the_pasted_one() { + let mut s = session(); + let r = run(&mut s, json!({})); + s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap(); + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 2); + let kids = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, |k| k.len())).sum::(); + let before = kids(&s); + run(&mut s, json!({"artboard": 1, "size": 30})); + assert_eq!(kids(&s), before, "marking the pasted artboard replaces the pasted copy"); + let source = run(&mut s, json!({})); + assert_eq!(source["changed"], json!(false), "the source artboard's marks are unchanged"); +} + +#[test] +fn marks_copied_with_a_duplicated_artboard_stay_with_the_copy_after_a_resize() { + let mut s = session(); + run(&mut s, json!({})); + s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "width": 500})).unwrap(); + let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len(); + let source = run(&mut s, json!({})); + assert_eq!(source["changed"], json!(false), "the copy's marks are not the source's"); + assert_eq!(kids(&s), 2); + run(&mut s, json!({"artboard": 1})); + assert_eq!(kids(&s), 2, "marking the resized duplicate replaces the copy"); +} + +#[test] +fn shrinking_an_artboard_keeps_its_marks_when_a_new_artboard_covers_more_of_the_stored_rectangle() { + let mut s = session(); + let original = run(&mut s, json!({})); + let id = original["ids"][0].as_u64().unwrap(); + let before = node(&s, id); + s.execute("artboard.setProps", &json!({"index": 0, "width": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 120, "y": 0, "width": 480, "height": 400})).unwrap(); + run(&mut s, json!({"artboard": 1})); + assert!(s.doc().unwrap().doc.node(NodeId(id)).is_some(), "marking the new artboard keeps the original group"); + assert!(node(&s, id) == before, "the original group's art and metadata stay unchanged"); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + run(&mut s, json!({"artboard": 0})); + assert!(s.doc().unwrap().doc.node(NodeId(id)).is_none(), "marking the resized source replaces its old group"); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); +} + +#[test] +fn marks_that_reach_onto_the_next_artboard_stay_with_their_own() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 620, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"allArtboards": true, "positions": ["right"], "inset": -60})); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 2); + for id in ids { + assert!(s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).is_some(), "group {id} is kept"); + } + let again = run(&mut s, json!({"allArtboards": true, "positions": ["right"], "inset": -60})); + assert_eq!(again["changed"], json!(false)); +} + #[test] fn bad_params_are_refused_and_leave_the_document_unchanged() { let mut s = session(); @@ -293,6 +428,9 @@ fn bad_params_are_refused_and_leave_the_document_unchanged() { json!({"artboard": 5}), json!({"artboard": -1}), json!({"artboard": 0, "allArtboards": true}), + json!({"positions": null}), + json!({"artboard": null}), + json!({"size": null}), json!({"positions": [], "inks": false, "info": false}), json!({"positions": [], "inks": true}), ] { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index bac821ab90..d340f21532 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1664,10 +1664,17 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho let mut imported = clip.import_into(d, choices, same_doc)?; // Draw Inside: the clip group of the object drawn into, made on the first paste. let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?; - let artboards: Vec = boards + let made_boards: Vec<(u32, usize)> = boards .into_iter() .flat_map(|(all, dv)| all.iter().map(move |a| (a, dv))) - .map(|(a, dv)| super::panelcmds::push_artboard_copy(d, a, a.rect + dv)) + .map(|(a, dv)| (a.id, super::panelcmds::push_artboard_copy(d, a, a.rect + dv))) + .collect(); + let artboards: Vec = made_boards.iter().map(|(_, i)| *i).collect(); + // Screen print marks copied with an artboard pasted once belong to the pasted artboard. + let board_ids: Vec<(u32, u32)> = made_boards + .iter() + .filter(|(src, _)| made_boards.iter().filter(|(s, _)| s == src).count() == 1) + .filter_map(|(src, i)| d.artboards.get(*i).map(|a| (*src, a.id))) .collect(); // The layers made for remembered layers the document lacks, by parent and name. let mut made = HashMap::new(); @@ -1685,6 +1692,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho // A pasted symbol set packs from the density recorded for it at Copy. d.carry_set_densities(n, &c, &clip.set_densities); imported.apply(&mut c, d); + for (from, to) in &board_ids { + if super::addons::retag_screen_marks(&mut c, *from, *to) { + break; + } + } let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() }; if xf != Affine::IDENTITY { // A cross-document drag carries the graphic's appearance with it, diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 433c69202c..732cb02913 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -397,7 +397,12 @@ pub(crate) fn copy_artboard(d: &mut vectorcraft_doc::Document, i: usize, dv: Vec if let Some(id) = d.artboards.get(index).map(|a| a.id) { d.copy_artboard_guides(src.id, id, dv); } + let to = d.artboards.get(index).map(|a| a.id); let copies = super::edit::copy_above(d, art, |_, _, c| { + // A copy of the artboard's screen print marks belongs to the copy. + if let Some(to) = to { + let _ = super::addons::retag_screen_marks(c, src.id, to); + } c.transform(Affine::translate(dv), sc); super::object::keep_pixel_aligned(c, sc); })?; diff --git a/docs/mcp.md b/docs/mcp.md index c7f332d107..9dff1e7764 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17789,15 +17789,19 @@ screen printing inside an artboard as document art, so they print, separate and leaves the date out. - `textSize` is the lines' type size, 4…72 pt (9). `textPlace` is `"top"` or `"bottom"` (the default) and `textAlign` is `"left"` (the default) or `"right"`: the lines sit `inset` in from that edge and side, the spot ink - line above the file line, and start past a target ticked in that corner. + line above the file line, and start past a target ticked in that corner. When a line would cross the `top` or + `bottom` target on its side, the lines move in past that target. They stay where they are when moving would cross + another target or leave the artboard. The marks of each artboard are one group, on the top-level layer "Screen Print Marks". When the document has no such layer, the command makes it at the bottom of the stack, locked. A layer moved, unlocked or hidden stays as it is. `artboard` is an artboard's index (default: the active artboard) and `allArtboards: true` marks every artboard; giving both is an error. Running the command again replaces that artboard's group and leaves the other artboards' -groups alone. It is one undo step, and none when the marks come out the same (`changed: false`). The selection is +groups alone. A group copied with an artboard duplicated, Alt-dragged or pasted in the same document belongs to the copy. Marks +outside the artboard (a negative `inset`) appear in an export or a print clipped to the artboard only as far as its +bleed reaches. It is one undo step, and none when the marks come out the same (`changed: false`). The selection is kept. An unknown position or one named twice, a number out of range, an `ink` that is not [Registration] or a spot -swatch, a value of the wrong type, nothing to draw (no position, no file line, and no spot ink line or no spot ink to +swatch, a value of the wrong type (`null` included, except for `time`), nothing to draw (no position, no file line, and no spot ink line or no spot ink to name), and marks that would reach more than 4,000,000 pt from the origin are errors that leave the document unchanged. The dialog previews on the canvas, and its OK is off while nothing is ticked. → `{changed, layer, ids: [group id…], inks: [spot ink name…]}` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 65a7560d67..4e6aec3605 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3290,7 +3290,7 @@ A VectorCraft addition (it replaces a script some users ran), so no area score m ## Create Screen Print Marks (2026-11-29) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Color Effects › Create Screen Print Marks… (`addon.color.screenMarks`) opens a dialog (the eight target positions, size, stroke weight, inset, ink, the spot ink and file lines with their type size, place and alignment, all artboards, with a preview) and draws registration targets (a circle half the target's width with a cross through it) inside the artboard in [Registration] or a spot ink, with an optional line naming the document's spot inks, each in its own ink, and an optional line with the file name and the date and time in UTC. The marks are document art: one group per artboard on a locked "Screen Print Marks" layer made at the bottom of the stack, so they print, separate and export with the rest of the art, where Create Trim Marks draws trim marks only and the PDF export's printer's marks exist only in the exported file. Running it again replaces that artboard's marks; one undo step, none when the marks come out the same. Remaining: saved presets of the dialog's settings. Tests: `cmd::addons::color::screen_marks::tests` (engine), `addons::color::screen_marks::tests` (ui-egui). +A VectorCraft addition, so no area score moves. Object › Plug-ins › Color Effects › Create Screen Print Marks… (`addon.color.screenMarks`) opens a dialog (the eight target positions, size, stroke weight, inset, ink, the spot ink and file lines with their type size, place and alignment, all artboards, with a preview) and draws registration targets (a circle half the target's width with a cross through it) inside the artboard in [Registration] or a spot ink, with an optional line naming the document's spot inks, each in its own ink, and an optional line with the file name and the date and time in UTC. The marks are document art: one group per artboard on a locked "Screen Print Marks" layer made at the bottom of the stack, so they print, separate and export with the rest of the art, where Create Trim Marks draws trim marks only and the PDF export's printer's marks exist only in the exported file. The lines move in past a top or bottom target they would cross. They stay where they are when moving would cross another target or leave the artboard. Marks copied with a duplicated artboard belong to the copy. Running it again replaces that artboard's marks; one undo step, none when the marks come out the same. Remaining: saved presets of the dialog's settings. Tests: `cmd::addons::color::screen_marks::tests` (engine), `addons::color::screen_marks::tests` (ui-egui). ## Stroke Weight Up and Down shortcuts (2026-11-06) From 0c679ddf6408af3a4bcd981b67d77e4154447db6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 16:16:00 -0800 Subject: [PATCH 24/88] Color Effects: copied artboards leave other artboards' screen print marks alone Duplicate Artboards, Alt-drag, Copy and Cut select art by position, so a marks group of another artboard lying wholly on the copied one was copied and kept its owner. Create Screen Print Marks then found two groups for that owner. Each marks group on the marks layer now goes with the artboard it belongs to: it is copied with that artboard when that one is copied too, and otherwise stays where it is. A group moved off the marks layer, or one whose artboard was deleted, is copied like other art. When the marks layer was deleted, pasting an artboard with its marks made the layer again without its marks tag, so the next run made a second marks layer. The layer a paste makes for those marks is now the marks layer when the document has none. --- crates/engine/src/cmd/addons.rs | 4 +- .../src/cmd/addons/color/screen_marks.rs | 18 +++- .../cmd/addons/color/screen_marks/tests.rs | 84 +++++++++++++++++++ crates/engine/src/cmd/edit.rs | 18 ++-- crates/engine/src/cmd/panelcmds.rs | 40 ++++++++- crates/engine/src/cmd/xform.rs | 3 + docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 8 files changed, 164 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 418fb84d18..555682c5c8 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -16,7 +16,9 @@ mod shapes; mod typetools; mod units; -pub(crate) use color::screen_marks::retag as retag_screen_marks; +pub(crate) use color::screen_marks::{ + LAYER_NAME as SCREEN_MARKS_LAYER, adopt_layer as adopt_screen_marks_layer, managed_owners as screen_marks_owners, retag as retag_screen_marks, +}; pub(crate) use image::{DecodedImages, refresh_color_masks}; pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; diff --git a/crates/engine/src/cmd/addons/color/screen_marks.rs b/crates/engine/src/cmd/addons/color/screen_marks.rs index b34f3b96ce..7581edc721 100644 --- a/crates/engine/src/cmd/addons/color/screen_marks.rs +++ b/crates/engine/src/cmd/addons/color/screen_marks.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Create Screen Print Marks", ["Object", "Plug-ins", "Color Effects"], None, - "{positions?: [topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight…] (each at most once; default: [top, bottom, left, right]; [] draws no targets), size?: target width in pt 4..1000 (36), weight?: stroke weight in pt 0.1..20 (1), inset?: pt from the artboard's edge to the target's outer edge -1000..1000 (18; below 0 the targets sit outside the artboard), ink?: \"[Registration]\" (default) or a spot swatch's name (the targets and the file line), inks?: false (a line naming the document's spot inks, each name in its own ink; tints and [Registration] left out), info?: false (a line with the file name, or the title of a document never saved, and the date and time in UTC), time?: Unix seconds (default: now; null, or no clock as on the web: no date), textSize?: pt 4..72 (9), textPlace?: \"top\"|\"bottom\" (default), textAlign?: \"left\" (default)|\"right\" (the lines start past a target ticked in that corner, and move in past the top or bottom target they would cross; they stay where they are when moving would cross another target or leave the artboard), artboard?: index (default: the active artboard), allArtboards?: false; null is refused except for time} draw registration targets (a circle half the target's width with a cross through it, stroked) inside each artboard, and the lines asked for, as one group per artboard on the layer \"Screen Print Marks\", which is made locked at the bottom of the stack when there is none; running it again replaces that artboard's group. One undo step, none when the marks come out the same; the selection is kept → {changed, layer, ids: [group id…], inks: [spot ink name…]}", + "{positions?: [topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight…] (each at most once; default: [top, bottom, left, right]; [] draws no targets), size?: target width in pt 4..1000 (36), weight?: stroke weight in pt 0.1..20 (1), inset?: pt from the artboard's edge to the target's outer edge -1000..1000 (18; below 0 the targets sit outside the artboard), ink?: \"[Registration]\" (default) or a spot swatch's name (the targets and the file line), inks?: false (a line naming the document's spot inks, each name in its own ink; tints and [Registration] left out), info?: false (a line with the file name, or the title of a document never saved, and the date and time in UTC), time?: Unix seconds (default: now; null, or no clock as on the web: no date), textSize?: pt 4..72 (9), textPlace?: \"top\"|\"bottom\" (default), textAlign?: \"left\" (default)|\"right\" (the lines start past a target ticked in that corner, and move in past the top or bottom target they would cross; they stay where they are when moving would cross another target or leave the artboard), artboard?: index (default: the active artboard), allArtboards?: false; null is refused except for time} draw registration targets (a circle half the target's width with a cross through it, stroked) inside each artboard, and the lines asked for, as one group per artboard on the layer \"Screen Print Marks\", which is made locked at the bottom of the stack when there is none; running it again replaces that artboard's group. Another artboard's group lying on a copied artboard goes with its own artboard. One undo step, none when the marks come out the same; the selection is kept → {changed, layer, ids: [group id…], inks: [spot ink name…]}", has_doc, screen_marks )] @@ -265,6 +265,11 @@ fn owner(n: &Node) -> Option { tag(n)?.parse().ok() } +/// Each marks group on the marks layer of `d`, with the id of the artboard it belongs to. +pub(crate) fn managed_owners(d: &Document) -> std::collections::HashMap { + marks_layer(d).and_then(|l| l.children()).into_iter().flatten().filter_map(|k| Some((k.id, owner(k)?))).collect() +} + /// Make copy `n` of an artboard's marks group belong to the artboard copied with it: its data /// names artboard `from`, and from now on names `to`. Duplicate Artboards, Alt-drag and paste call /// it on each copy they make. → whether `n` was such a group. @@ -283,6 +288,17 @@ pub(crate) fn retag(n: &mut Node, from: u32, to: u32) -> bool { true } +/// Make top-level layer `layer`, which a paste made for a marks group it copied with an artboard, +/// the marks layer, when the document has none. +pub(crate) fn adopt_layer(d: &mut Document, layer: NodeId) { + if marks_layer(d).is_some() || !d.layers.iter().any(|l| l.id == layer) { + return; + } + if let Some(l) = d.node_mut(layer) { + l.edit_attrs(|a| a.data.push((KEY.into(), "layer".into()))); + } +} + /// `n` with every object's id 0: marks drawn again compare equal to marks drawn the same way. fn without_ids(n: &Node) -> Node { let mut n = n.clone(); diff --git a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs index f77928cd33..4c88d20d64 100644 --- a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs +++ b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs @@ -356,6 +356,90 @@ fn marks_copied_with_a_pasted_artboard_belong_to_the_pasted_one() { assert_eq!(source["changed"], json!(false), "the source artboard's marks are unchanged"); } +#[test] +fn marks_pasted_after_their_layer_was_deleted_are_found_again() { + let mut s = session(); + let r = run(&mut s, json!({})); + s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap(); + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("layer.delete", &json!({"ids": [r["layer"]]})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 2); + run(&mut s, json!({"artboard": 1, "size": 30})); + let doc = &s.doc().unwrap().doc; + let layers: Vec<_> = doc.layers.iter().filter(|l| l.name.as_deref() == Some(LAYER_NAME)).collect(); + assert_eq!(layers.len(), 1, "one marks layer"); + assert_eq!(layers[0].children().unwrap().len(), 1, "marking the pasted artboard replaces the pasted copy"); +} + +#[test] +fn another_artboards_marks_lying_on_a_copied_artboard_stay_with_their_own() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"positions": ["right"], "inset": -200})); + let g = node(&s, r["ids"][0].as_u64().unwrap()); + let b = bounds(&g); + assert!(b.x0 >= 700.0 && b.x1 <= 1300.0, "the marks lie wholly on the second artboard: {b:?}"); + let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len(); + s.execute("artboard.duplicate", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap(); + assert_eq!(kids(&s), 1, "duplicating the second artboard leaves the first one's marks out"); + s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap(); + let copied = s.execute("artboard.copy", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap(); + assert_eq!(copied["copied"], json!(0), "copying the second artboard leaves the first one's marks out"); + let again = run(&mut s, json!({"positions": ["right"], "inset": -200})); + assert_eq!(again["changed"], json!(false)); +} + +#[test] +fn duplicating_overlapping_artboards_copies_marks_lying_on_both_once() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 600, "height": 400})).unwrap(); + run(&mut s, json!({"artboard": 1, "positions": ["left"]})); + s.execute("artboard.duplicate", &json!({"indices": [0, 1], "art": true, "lockedAndHidden": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the second artboard's copy carries its marks"); + let copy = run(&mut s, json!({"artboard": 3, "positions": ["left"], "size": 30})); + assert_eq!(copy["changed"], json!(true)); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "marking that copy replaces the copied marks"); +} + +#[test] +fn marks_lying_on_another_copied_artboard_go_with_their_own_artboards_copy() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let p = json!({"positions": ["right"], "inset": -200}); + run(&mut s, p.clone()); + s.execute("artboard.duplicate", &json!({"indices": [0, 1], "art": true, "lockedAndHidden": true})).unwrap(); + let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len(); + assert_eq!(kids(&s), 2, "the first artboard's copy carries its marks"); + run(&mut s, json!({"artboard": 2, "positions": ["right"], "inset": -200, "size": 30})); + assert_eq!(kids(&s), 2, "marking the first artboard's copy replaces the copied marks"); + assert_eq!(run(&mut s, p)["changed"], json!(false), "the first artboard's marks are unchanged"); +} + +#[test] +fn a_marks_group_moved_off_the_marks_layer_is_copied_like_other_art() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"positions": ["right"], "inset": -200})); + s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap(); + let other = s.doc().unwrap().doc.layers[1].id.0; + s.execute("layer.move", &json!({"ids": [r["ids"][0]], "target": other})).unwrap(); + let kids = |s: &Session| s.doc().unwrap().doc.layers[1].children().unwrap().len(); + let before = kids(&s); + s.execute("artboard.duplicate", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap(); + assert_eq!(kids(&s), before + 1, "the duplicate carries a copy of the moved group"); +} + +#[test] +fn marks_of_a_deleted_artboard_are_copied_like_other_art() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + run(&mut s, json!({"positions": ["right"], "inset": -200})); + s.execute("artboard.delete", &json!({"indices": [0]})).unwrap(); + s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the duplicate carries a copy of the marks"); +} + #[test] fn marks_copied_with_a_duplicated_artboard_stay_with_the_copy_after_a_resize() { let mut s = session(); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index d340f21532..b92bdf77e7 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1692,11 +1692,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho // A pasted symbol set packs from the density recorded for it at Copy. d.carry_set_densities(n, &c, &clip.set_densities); imported.apply(&mut c, d); - for (from, to) in &board_ids { - if super::addons::retag_screen_marks(&mut c, *from, *to) { - break; - } - } + let marks = board_ids.iter().any(|(from, to)| super::addons::retag_screen_marks(&mut c, *from, *to)); let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() }; if xf != Affine::IDENTITY { // A cross-document drag carries the graphic's appearance with it, @@ -1705,7 +1701,17 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho } let layer = match remembered.get(k) { Some(Some(Remembered::Layer(l))) => Some(*l), - Some(Some(Remembered::Make { parent, names })) => make_layers(d, &mut made, *parent, names)?, + Some(Some(Remembered::Make { parent, names })) => { + let last = make_layers(d, &mut made, *parent, names)?; + // The marks layer made again for a copy of an artboard's marks is the marks + // layer, so Create Screen Print Marks finds the copy there. + if let (true, None, [name], Some(l)) = (marks, parent, names.as_slice(), last) + && name == super::addons::SCREEN_MARKS_LAYER + { + super::addons::adopt_screen_marks_layer(d, l); + } + last + } _ => None, }; // In a clip group or a clipping layer the bottom child is the clipping path: art pasted diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 732cb02913..954ff35892 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -306,6 +306,42 @@ pub(crate) fn artboard_art(s: &Session, i: usize, art: bool, all: bool, moving: }) } +/// `arts` (artboard indices with their art) with each artboard's screen print marks group in its +/// own artboard's entry: another artboard's group lying on one of them goes with its own artboard +/// when that one is among `arts`, and is left out when it is not. Only the groups on the marks +/// layer count; a group whose artboard was deleted stays where it is. Copies and cuts of artboards. +pub(crate) fn marks_with_owners(d: &vectorcraft_doc::Document, arts: Vec<(usize, Vec)>) -> Vec<(usize, Vec)> { + let owners = super::addons::screen_marks_owners(d); + if owners.is_empty() { + return arts; + } + let board = |i: usize| d.artboards.get(i).map(|a| a.id); + let owner = |id: NodeId| owners.get(&id).copied().filter(|o| d.artboards.iter().any(|a| a.id == *o)); + let mut moved: Vec<(u32, NodeId)> = vec![]; + let mut arts: Vec<(usize, Vec)> = arts + .into_iter() + .map(|(i, art)| { + let art = art + .into_iter() + .filter(|id| match owner(*id) { + Some(o) if Some(o) != board(i) => { + moved.push((o, *id)); + false + } + _ => true, + }) + .collect(); + (i, art) + }) + .collect(); + for (o, id) in moved { + if let Some((_, art)) = arts.iter_mut().find(|(i, _)| board(*i) == Some(o)) { + art.push(id); + } + } + arts +} + /// Each of `indices` with the art that goes with it when `art` ([`artboard_art`]), an object /// counted once, with the first of them it is on (artboards can overlap). pub(crate) fn artboards_art(s: &Session, indices: &[usize], art: bool, all: bool, moving: bool) -> Result)>> { @@ -315,7 +351,7 @@ pub(crate) fn artboards_art(s: &Session, indices: &[usize], art: bool, all: bool let art = artboard_art(s, i, art, all, moving)?.into_iter().filter(|id| seen.insert(*id)).collect(); arts.push((i, art)); } - Ok(arts) + Ok(if moving { arts } else { marks_with_owners(&s.doc()?.doc, arts) }) } /// How far a copy of `rect` moves to sit right of the last artboard (Duplicate Artboards, Paste). @@ -368,6 +404,8 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result = indices.iter().filter_map(|i| st.doc.artboards.get(*i).cloned()).collect(); let clip = Clipboard { source_artboard: boards.first().map(|a| a.rect), artboards: boards, ..Clipboard::copy(st, &art, false) }; diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index 7b71a20a3a..6656711738 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -692,6 +692,9 @@ fn artboard_move(s: &mut Session, p: &Value) -> Result { let art = art.into_iter().filter(|id| !arts.iter().any(|(_, a)| a.contains(id))).collect(); arts.push((i, art)); } + if copy { + arts = super::panelcmds::marks_with_owners(&s.doc()?.doc, arts); + } let ids: Vec = arts.iter().flat_map(|(_, a)| a.iter().copied()).collect(); let sc = Scaling { patterns: super::object::transform_patterns(s, p, &ids)?, ..Scaling::default() }; let (index, moved) = s.edit(if copy { "Duplicate Artboard" } else { "Move Artboard" }, |d, _| { diff --git a/docs/mcp.md b/docs/mcp.md index 9dff1e7764..e8b77d7707 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17797,7 +17797,11 @@ The marks of each artboard are one group, on the top-level layer "Screen Print M layer, the command makes it at the bottom of the stack, locked. A layer moved, unlocked or hidden stays as it is. `artboard` is an artboard's index (default: the active artboard) and `allArtboards: true` marks every artboard; giving both is an error. Running the command again replaces that artboard's group and leaves the other artboards' -groups alone. A group copied with an artboard duplicated, Alt-dragged or pasted in the same document belongs to the copy. Marks +groups alone. A group copied with an artboard duplicated, Alt-dragged or pasted in the same document belongs to the copy. +Another artboard's group lying on an artboard that is duplicated, Alt-dragged, copied or cut goes with its own artboard: +it is copied with that artboard when that one is copied too, and otherwise stays where it is. A group whose artboard was +deleted is copied like other art. When the "Screen Print Marks" layer was +deleted, pasting an artboard with its marks makes the layer again, and the command uses that layer. Marks outside the artboard (a negative `inset`) appear in an export or a print clipped to the artboard only as far as its bleed reaches. It is one undo step, and none when the marks come out the same (`changed: false`). The selection is kept. An unknown position or one named twice, a number out of range, an `ink` that is not [Registration] or a spot diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4e6aec3605..5f26574f20 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3290,7 +3290,7 @@ A VectorCraft addition (it replaces a script some users ran), so no area score m ## Create Screen Print Marks (2026-11-29) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Color Effects › Create Screen Print Marks… (`addon.color.screenMarks`) opens a dialog (the eight target positions, size, stroke weight, inset, ink, the spot ink and file lines with their type size, place and alignment, all artboards, with a preview) and draws registration targets (a circle half the target's width with a cross through it) inside the artboard in [Registration] or a spot ink, with an optional line naming the document's spot inks, each in its own ink, and an optional line with the file name and the date and time in UTC. The marks are document art: one group per artboard on a locked "Screen Print Marks" layer made at the bottom of the stack, so they print, separate and export with the rest of the art, where Create Trim Marks draws trim marks only and the PDF export's printer's marks exist only in the exported file. The lines move in past a top or bottom target they would cross. They stay where they are when moving would cross another target or leave the artboard. Marks copied with a duplicated artboard belong to the copy. Running it again replaces that artboard's marks; one undo step, none when the marks come out the same. Remaining: saved presets of the dialog's settings. Tests: `cmd::addons::color::screen_marks::tests` (engine), `addons::color::screen_marks::tests` (ui-egui). +A VectorCraft addition, so no area score moves. Object › Plug-ins › Color Effects › Create Screen Print Marks… (`addon.color.screenMarks`) opens a dialog (the eight target positions, size, stroke weight, inset, ink, the spot ink and file lines with their type size, place and alignment, all artboards, with a preview) and draws registration targets (a circle half the target's width with a cross through it) inside the artboard in [Registration] or a spot ink, with an optional line naming the document's spot inks, each in its own ink, and an optional line with the file name and the date and time in UTC. The marks are document art: one group per artboard on a locked "Screen Print Marks" layer made at the bottom of the stack, so they print, separate and export with the rest of the art, where Create Trim Marks draws trim marks only and the PDF export's printer's marks exist only in the exported file. The lines move in past a top or bottom target they would cross. They stay where they are when moving would cross another target or leave the artboard. Marks copied with a duplicated artboard belong to the copy, and another artboard's marks lying on a copied artboard stay with their own artboard. A paste that makes the deleted marks layer again makes it the marks layer. Running it again replaces that artboard's marks; one undo step, none when the marks come out the same. Remaining: saved presets of the dialog's settings. Tests: `cmd::addons::color::screen_marks::tests` (engine), `addons::color::screen_marks::tests` (ui-egui). ## Stroke Weight Up and Down shortcuts (2026-11-06) From b767a1e05b9ac24d9e41b55b6f881bff82ac5fa9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 22:08:47 -0800 Subject: [PATCH 25/88] Color Effects: screen print marks follow their artboard's copy and paste into their locked layer - The canvas-edge check pads the targets by half the target weight, the part of the stroke that lies outside their paths. - Copying an artboard with its art also takes the artboard's own marks group when the group lies off the artboard, under the same locked and hidden rule as other art. - Pasting an artboard copied with its marks puts the marks back into the Screen Print Marks layer while that layer is locked or hidden. Other art copied with the artboard still refuses a locked or hidden layer. --- crates/engine/src/cmd/addons.rs | 3 +- .../src/cmd/addons/color/screen_marks.rs | 25 +++++++- .../cmd/addons/color/screen_marks/tests.rs | 57 +++++++++++++++++++ crates/engine/src/cmd/edit.rs | 35 ++++++++---- crates/engine/src/cmd/panelcmds.rs | 18 +++++- docs/mcp.md | 2 + 6 files changed, 123 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 555682c5c8..94eff63759 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -17,7 +17,8 @@ mod typetools; mod units; pub(crate) use color::screen_marks::{ - LAYER_NAME as SCREEN_MARKS_LAYER, adopt_layer as adopt_screen_marks_layer, managed_owners as screen_marks_owners, retag as retag_screen_marks, + LAYER_NAME as SCREEN_MARKS_LAYER, adopt_layer as adopt_screen_marks_layer, copied_owners as screen_marks_copied, layer_id as screen_marks_layer, + managed_owners as screen_marks_owners, owned_by as screen_marks_of, retag as retag_screen_marks, }; pub(crate) use image::{DecodedImages, refresh_color_masks}; pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines}; diff --git a/crates/engine/src/cmd/addons/color/screen_marks.rs b/crates/engine/src/cmd/addons/color/screen_marks.rs index 7581edc721..5f66210fe4 100644 --- a/crates/engine/src/cmd/addons/color/screen_marks.rs +++ b/crates/engine/src/cmd/addons/color/screen_marks.rs @@ -270,6 +270,25 @@ pub(crate) fn managed_owners(d: &Document) -> std::collections::HashMap Option { + marks_layer(d).map(|l| l.id) +} + +/// Is `n` the marks group of one of the artboards with ids `boards`? +pub(crate) fn owned_by(n: &Node, boards: &[u32]) -> bool { + owner(n).is_some_and(|o| boards.contains(&o)) +} + +/// Each marks group on the marks layer of `d` that goes with an artboard copy, in paint order, +/// with the id of the artboard it belongs to. Locked and hidden ones, and all of them while the +/// marks layer is locked or hidden, only with `locked_and_hidden`. +pub(crate) fn copied_owners(d: &Document, locked_and_hidden: bool) -> Vec<(NodeId, u32)> { + let layer = marks_layer(d).filter(|l| l.rides_with_artboard(locked_and_hidden)); + let kids = layer.and_then(|l| l.children()).into_iter().flatten(); + kids.filter(|k| k.rides_with_artboard(locked_and_hidden)).filter_map(|k| Some((k.id, owner(k)?))).collect() +} + /// Make copy `n` of an artboard's marks group belong to the artboard copied with it: its data /// names artboard `from`, and from now on names `to`. Duplicate Artboards, Alt-drag and paste call /// it on each copy they make. → whether `n` was such a group. @@ -390,14 +409,14 @@ fn screen_marks(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let layer = marks_layer(&st.doc).map(|l| (l.id, l.children().cloned().unwrap_or_default())); let drawn: Vec = boards.iter().map(|(r, board)| marks.group(*r, *board, &mut || NodeId(0))).collect(); - // Only the stroked targets reach past their paths by the target weight. The lines of type have - // no stroke; their glyphs' ink, underline and strikethrough bars included, is checked as well. + // Only the stroked targets reach past their paths, by half the target weight. The lines of type + // have no stroke; their glyphs' ink, underline and strikethrough bars included, is checked as well. let past = |b: Rect, reach: f64| [b.x0 - reach, b.y0 - reach, b.x1 + reach, b.y1 + reach].iter().any(|v| !v.is_finite() || v.abs() > MAX_COORD); let beyond = |n: &Node| match &n.kind { NodeKind::Text(t) => { n.geometric_bounds().is_some_and(|b| past(b, 0.0)) || t.ink().flatten().is_some_and(|ink| past(t.xf.transform_rect_bbox(ink), 0.0)) } - _ => n.geometric_bounds().is_some_and(|b| past(b, marks.weight)), + _ => n.geometric_bounds().is_some_and(|b| past(b, marks.weight / 2.0)), }; if drawn.iter().any(|g| g.children().is_some_and(|kids| kids.iter().any(|k| beyond(k)))) { return Err(bad(C, format!("the marks would reach past the edge of the canvas (±{MAX_COORD} pt)"))); diff --git a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs index 4c88d20d64..76c2c9f799 100644 --- a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs +++ b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs @@ -206,6 +206,19 @@ fn the_target_weight_does_not_pad_lines_of_type_at_the_canvas_edge() { assert_eq!(lines(&node(&s, r["ids"][0].as_u64().unwrap())).len(), 1); } +#[test] +fn a_target_reaches_past_its_paths_by_half_its_weight_at_the_canvas_edge() { + let mut s = session(); + // The artboard ends at the canvas edge. + s.execute("artboard.new", &json!({"x": 3999100, "y": 0, "width": 900, "height": 100})).unwrap(); + // The cross ends 15 pt inside the edge, and its 20 pt stroke reaches 10 pt past that. + let r = run(&mut s, json!({"artboard": 1, "positions": ["right"], "size": 36, "weight": 20, "inset": 15})); + assert_eq!(targets(&node(&s, r["ids"][0].as_u64().unwrap())).len(), 1); + // 5 pt inside the edge, the stroke reaches 5 pt past it. + let err = s.execute(COMMAND, &json!({"artboard": 1, "positions": ["right"], "size": 36, "weight": 20, "inset": 5})).unwrap_err().to_string(); + assert!(err.contains("edge of the canvas"), "{err}"); +} + #[test] fn every_artboard_gets_its_group_and_one_artboard_rerun_keeps_the_others() { let mut s = session(); @@ -356,6 +369,34 @@ fn marks_copied_with_a_pasted_artboard_belong_to_the_pasted_one() { assert_eq!(source["changed"], json!(false), "the source artboard's marks are unchanged"); } +#[test] +fn marks_copied_with_an_artboard_paste_back_into_their_locked_layer() { + let mut s = session(); + let r = run(&mut s, json!({})); + let layer = NodeId(r["layer"].as_u64().unwrap()); + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let marks = |s: &Session| s.doc().unwrap().doc.node(layer).map(|l| (l.locked, l.children().map_or(0, |k| k.len()))); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 2); + assert_eq!(marks(&s), Some((true, 2)), "the pasted marks go into the marks layer, which stays locked"); + run(&mut s, json!({"artboard": 1, "size": 30})); + assert_eq!(marks(&s), Some((true, 2)), "marking the pasted artboard replaces the pasted copy"); +} + +#[test] +fn other_art_copied_with_an_artboard_does_not_paste_into_a_locked_layer() { + let mut s = session(); + run(&mut s, json!({})); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap(); + let other = s.doc().unwrap().doc.layers[1].id.0; + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("layer.setProps", &json!({"id": other, "locked": true})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("edit.paste", &json!({})).unwrap_err().to_string(); + assert!(err.contains("locked or hidden"), "{err}"); + assert!(s.doc().unwrap().doc == before, "nothing is pasted"); +} + #[test] fn marks_pasted_after_their_layer_was_deleted_are_found_again() { let mut s = session(); @@ -416,6 +457,22 @@ fn marks_lying_on_another_copied_artboard_go_with_their_own_artboards_copy() { assert_eq!(run(&mut s, p)["changed"], json!(false), "the first artboard's marks are unchanged"); } +#[test] +fn marks_lying_on_another_artboard_go_with_their_own_artboards_copy_alone() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let p = json!({"positions": ["right"], "inset": -200}); + run(&mut s, p.clone()); + let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len(); + s.execute("artboard.duplicate", &json!({"index": 0, "art": true})).unwrap(); + assert_eq!(kids(&s), 1, "the locked marks stay without lockedAndHidden"); + s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + assert_eq!(kids(&s), 2, "the first artboard's copy carries its marks lying on the second artboard"); + run(&mut s, json!({"artboard": 3, "positions": ["right"], "inset": -200, "size": 30})); + assert_eq!(kids(&s), 2, "marking the copy replaces the copied marks"); + assert_eq!(run(&mut s, p)["changed"], json!(false), "the first artboard's marks are unchanged"); +} + #[test] fn a_marks_group_moved_off_the_marks_layer_is_copied_like_other_art() { let mut s = session(); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 02afd94308..b005e1e56b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -189,7 +189,7 @@ pub fn specs() -> Vec { "Paste", ["Edit"], Some("Cmd+V"), - "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own, also for a pie in the art of a symbol, pattern, brush or graph design the paste brings) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", + "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own, also for a pie in the art of a symbol, pattern, brush or graph design the paste brings) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted, except the Screen Print Marks layer for the marks copied with their artboard). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", has_clipboard, |s, p| paste(s, p, PasteMode::Offset) ), @@ -1621,9 +1621,16 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho && inside.is_none() && (st.doc.paste_remembers_layers || boards.is_some()) && parent.is_some_and(|p| st.doc.node(p).is_some_and(Node::is_layer)); + // Screen print marks copied with an artboard that is pasted once go back into the marks layer, + // locked or hidden as it is. + let pasted_once: Vec = match boards { + Some((all, _)) => all.iter().map(|a| a.id).filter(|id| all.iter().filter(|a| a.id == *id).count() == 1).collect(), + None => vec![], + }; + let marks: Vec = clip.nodes.iter().map(|n| super::addons::screen_marks_of(n, &pasted_once)).collect(); // Each object's remembered layer, found before anything is pasted: a hidden or locked one // refuses the whole paste. - let remembered = if remember { remembered_layers(&st.doc, &clip.source_layers, same_doc)? } else { vec![] }; + let remembered = if remember { remembered_layers(&st.doc, &clip.source_layers, &marks, same_doc)? } else { vec![] }; // Front/back: relative to the selection (top-most / bottom-most selected object); with // nothing selected, the top / bottom of the current layer. Art other than paths goes beside // the compound path that holds the selected object, not into it. @@ -1851,18 +1858,22 @@ enum Remembered { Make { parent: Option, names: Vec }, } -/// [`remembered_layer`] for each object's source layer, worked out once for each layer. -fn remembered_layers(d: &Document, sources: &[Option], same_doc: bool) -> Result>> { - let mut found: HashMap<&SourceLayer, Remembered> = HashMap::new(); +/// [`remembered_layer`] for each object's source layer, worked out once for each layer. The objects +/// `marks` marks are screen print marks groups, which may go back into the marks layer while it +/// is locked or hidden. +fn remembered_layers(d: &Document, sources: &[Option], marks: &[bool], same_doc: bool) -> Result>> { + let mut found: HashMap<(&SourceLayer, bool), Remembered> = HashMap::new(); sources .iter() - .map(|src| { + .enumerate() + .map(|(k, src)| { let Some(src) = src else { return Ok(None) }; - if let Some(r) = found.get(src) { + let key = (src, marks.get(k).copied().unwrap_or(false)); + if let Some(r) = found.get(&key) { return Ok(Some(r.clone())); } - let r = remembered_layer(d, src, same_doc)?; - found.insert(src, r.clone()); + let r = remembered_layer(d, src, key.1, same_doc)?; + found.insert(key, r.clone()); Ok(Some(r)) }) .collect() @@ -1873,8 +1884,9 @@ fn remembered_layers(d: &Document, sources: &[Option], same_doc: bo /// it still where they were (by id) are kept. Below them, and in another document from the top, /// each name is matched among the layers inside the one above (the topmost of the same name whose /// layers match the most names, a shown and unlocked one first). The names left unmatched are -/// made. A matched layer that is hidden or locked, or inside one that is, is an error. -fn remembered_layer(d: &Document, src: &SourceLayer, same_doc: bool) -> Result { +/// made. A matched layer that is hidden or locked, or inside one that is, is an error, except the +/// marks layer for a screen print marks group (`marks`). +fn remembered_layer(d: &Document, src: &SourceLayer, marks: bool, same_doc: bool) -> Result { let held = |id: &NodeId| d.node(*id).is_some_and(|n| n.is_layer() && n.name.as_ref() == src.names.last()); let kept = if same_doc && src.ids.last().is_some_and(held) { src.ids.len() @@ -1889,6 +1901,7 @@ fn remembered_layer(d: &Document, src: &SourceLayer, same_doc: bool) -> Result Result)>> { let mut seen = std::collections::HashSet::new(); let mut arts = vec![]; @@ -351,7 +352,20 @@ pub(crate) fn artboards_art(s: &Session, indices: &[usize], art: bool, all: bool let art = artboard_art(s, i, art, all, moving)?.into_iter().filter(|id| seen.insert(*id)).collect(); arts.push((i, art)); } - Ok(if moving { arts } else { marks_with_owners(&s.doc()?.doc, arts) }) + if moving { + return Ok(arts); + } + let d = &s.doc()?.doc; + if art { + for (id, o) in super::addons::screen_marks_copied(d, all) { + if let Some((_, own)) = arts.iter_mut().find(|(i, _)| d.artboards.get(*i).is_some_and(|a| a.id == o)) + && seen.insert(id) + { + own.push(id); + } + } + } + Ok(marks_with_owners(d, arts)) } /// How far a copy of `rect` moves to sit right of the last artboard (Duplicate Artboards, Paste). diff --git a/docs/mcp.md b/docs/mcp.md index 25751faf9b..e103b34222 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11110,6 +11110,8 @@ pastes objects back into the layers and sublayers they came from: in the same do else by the names of the layer and the layers around it (the topmost chain that matches the most names, a shown and unlocked one first). A missing sublayer is made inside its layer, and a missing top-level layer on top, in the paste's undo step. When a matched layer, or a layer around it, is hidden or locked, the paste fails and nothing is pasted. +Screen print marks copied with their artboard (`addon.color.screenMarks`) go back into the Screen Print Marks layer +even while it is hidden or locked. Drawing modes (`view.drawMode`) apply too: in Draw Inside, `edit.paste`, `edit.pasteInPlace` and `edit.pasteOnAllArtboards` put the objects inside the object drawn into (its clip group, made on the first paste), whatever Paste Remembers Layers says; in Draw Behind, From cf81f627992b03f4a08cff301e1fdd859cbbd8b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 22:12:51 -0800 Subject: [PATCH 26/88] Scripts: compound pathItems are PathItems, clipped checks its clipping path, doScript follows inserted artboards - A compound path's `pathItems` is a `PathItems` object scoped to the compound path: it reads its paths, `parent` is the compound path, and the methods that make a path throw. `removeAll()` keeps the compound path, empty, as `remove()` of its last path does. `PathItems` gains `toString()`. - `GroupItem.clipped` throws when the path that would become the clipping path, or the clipping path it would release, is hidden or locked, before `layer.clippingMask.toggle` changes it. - After `artboards.add` or `insert` gives the active artboard another index, `app.doScript` steps act on that artboard at its new index. The Artboard tool's selection kept from the run's start is held by artboard id, so a Fit to Artwork Bounds or paste step acts on the same artboards after one is inserted or removed. - `Layer.opacity` runs no command only for the exact value its getter reports, as a page item's does. - `Layer.zOrderPosition` reads the kept list of layers and each layer's place in it, so a loop over the layers lists them once. - Tests: the Revert test compares the artboard's name with the saved one, and the `clipped` test reads `clipped` inside the script after the error. --- crates/engine/src/script/actions.rs | 26 ++-- crates/engine/src/script/dom.rs | 3 + crates/engine/src/script/dom/layers.rs | 120 ++++++++++++++--- crates/engine/src/script/dom/paths.rs | 33 +++++ crates/engine/src/script/mod.rs | 12 +- crates/engine/src/tests/script_actions.rs | 43 ++++++ crates/engine/src/tests/script_dom.rs | 124 +++++++++++++++++- .../tests/it/script_host_vs_scriptcheck.rs | 5 +- docs/mcp.md | 13 +- 9 files changed, 337 insertions(+), 42 deletions(-) diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 28c98af3fc..f16cb3ada2 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -254,20 +254,30 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { // Saved steps run as they run in the Actions panel: keys their commands no longer read are // passed over. // A document whose active artboard the run set with `setActiveArtboardIndex` plays on that - // artboard, and the Artboard tool's selection as the run started no longer holds for it. - let picks = h.artboard_picks.as_ref().filter(|(uid, _)| !h.dom.active_artboards.borrow().contains(uid)); - let active: Vec<(u64, usize)> = { + // artboard, and the Artboard tool's selection as the run started no longer holds for it. One + // where `artboards.add` or `artboards.insert` moved the active artboard to another index plays + // on that artboard at its new index. The Artboard tool's selection is the artboards it held, + // at the indices they have now. + let (active, picks): (Vec<(u64, usize)>, Option<(u64, Vec)>) = { let moved = h.dom.active_artboards.borrow(); + let shifted = h.dom.boards_shifted.borrow(); let session = h.session.borrow(); - h.active_artboards + let doc = |uid: u64| session.documents().iter().find(|d| d.uid == uid); + let active = h + .active_artboards .iter() - .map(|&(uid, i)| match session.documents().iter().find(|d| d.uid == uid) { - Some(st) if moved.contains(&uid) => (uid, super::dom::active_artboard(st)), + .map(|&(uid, i)| match doc(uid) { + Some(st) if moved.contains(&uid) || shifted.contains(&uid) => (uid, super::dom::active_artboard(st)), _ => (uid, i), }) - .collect() + .collect(); + let picks = h.artboard_picks.as_ref().filter(|(uid, _)| !moved.contains(uid)).map(|(uid, ids)| { + let at = doc(*uid).map(|st| ids.iter().filter_map(|id| st.doc.artboards.iter().position(|ab| ab.id == *id)).collect()); + (*uid, at.unwrap_or_default()) + }); + (active, picks) }; - let start = Start { active: &active, picks, batch: s.artboard }; + let start = Start { active: &active, picks: picks.as_ref(), batch: s.artboard }; let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params); let outer = h.session.borrow_mut().set_replaying(true); let r = command(h, &s.id, ¶ms); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 1b79fa783d..402e7c5a3f 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -224,6 +224,9 @@ pub(super) struct State { layers: RefCell>, /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_artboards: RefCell>, + /// The uids of the documents where `artboards.add` or `artboards.insert` gave the active + /// artboard another index. + pub(super) boards_shifted: RefCell>, /// Each open document's uid and the index of its active artboard when the run started, and for /// a document the run opened, the index before the run first added an artboard to it. pub(super) boards_at_start: RefCell>, diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index e27f59fd65..04debab36a 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -32,6 +32,8 @@ //! active artboard has another index at the end of the run, because artboards were inserted, //! removed or reordered before it. +use std::cell::OnceCell; +use std::collections::HashMap; use std::rc::Rc; use std::sync::Arc; @@ -65,6 +67,8 @@ enum Kind { Group, /// Compound paths (`CompoundPathItem`). Compound, + /// Paths (`PathItem`): the `pathItems` of a compound path. + Path, } impl Kind { @@ -73,6 +77,7 @@ impl Kind { Kind::Any => "PageItems", Kind::Group => "GroupItems", Kind::Compound => "CompoundPathItems", + Kind::Path => "PathItems", } } @@ -81,6 +86,7 @@ impl Kind { Kind::Any => typename(n).is_some(), Kind::Group => typename(n) == Some("GroupItem"), Kind::Compound => typename(n) == Some("CompoundPathItem"), + Kind::Path => typename(n) == Some("PathItem"), } } } @@ -227,7 +233,8 @@ fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer { if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); } - set_layer(h, a, "object.setProps", |n| (f64::from(n.opacity) * 100.0 - v).abs() < 1e-4, json!({"opacity": v})) + // Only the exact number the getter reports counts as the same opacity, as for a page item. + set_layer(h, a, "object.setProps", |n| (f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4 == v, json!({"opacity": v})) } fn layer_color(h: &Host, a: &[Data]) -> Answer { @@ -273,13 +280,19 @@ fn layer_to_string(h: &Host, a: &[Data]) -> Answer { } /// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is -/// not counted. +/// not counted. The list of the layers beside it and each one's place in it are kept as +/// [`layers_listed`] keeps the list, so a loop over the layers reads them once. fn layer_z_position(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; let at = with_doc(h, doc, |_, st| { - let list = layer_list(&st.doc, st.doc.parent_of(id)); - list.iter().position(|l| *l == id).map(|i| list.len() - i) - }); + let (list, places) = layers_kept(h, st, st.doc.parent_of(id))?; + let places = places.get_or_init(|| { + #[cfg(test)] + super::LAYER_SCANS.with(|c| c.set(c.get() + list.len() as u64)); + list.iter().enumerate().map(|(i, l)| (*l, i)).collect() + }); + Ok::<_, HostError>(places.get(&id).map(|i| list.len() - i)) + })?; at.map(|i| num(float(i as u64))).ok_or_else(|| HostError::Error(STALE_LAYER.into())) } @@ -479,21 +492,28 @@ fn layer_list(d: &Document, parent: Option) -> Vec { } /// A document's uid, the document as it was, the parent a `Layers` object lists (`None`: the top -/// level) and the layers it listed then. -pub(super) type LayerList = (u64, Arc, Option, Rc>); +/// level), the layers it listed then and, once a layer's place was asked for, each layer's index in +/// that list. +pub(super) type LayerList = (u64, Arc, Option, Rc>, Rc>>); /// The layers of `parent` as [`layer_list`] gives them. The last [`ART_LISTS`] lists are kept while /// their documents are unchanged, so a loop over `layers[i]` lists the layers once. Each new list /// is charged by the objects it looks at. fn layers_listed(h: &Host, st: &DocState, parent: Option) -> Result>> { + layers_kept(h, st, parent).map(|(ids, _)| ids) +} + +/// The list [`layers_listed`] gives, with the index of each layer in it, which is built the first +/// time it is asked for. +fn layers_kept(h: &Host, st: &DocState, parent: Option) -> Result<(Rc>, Rc>>)> { { let mut lists = h.dom.layers.borrow_mut(); - let at = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent); + let at = lists.iter().position(|(uid, doc, p, ..)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent); if let Some(at) = at { let list = lists.remove(at); - let ids = list.3.clone(); + let kept = (list.3.clone(), list.4.clone()); lists.push(list); - return Ok(ids); + return Ok(kept); } } let looked_at = match parent { @@ -507,8 +527,9 @@ fn layers_listed(h: &Host, st: &DocState, parent: Option) -> Result= ART_LISTS { lists.remove(0); } - lists.push((st.uid, st.doc.clone(), parent, ids.clone())); - Ok(ids) + let places = Rc::new(OnceCell::new()); + lists.push((st.uid, st.doc.clone(), parent, ids.clone(), places.clone())); + Ok((ids, places)) } fn layers_of(h: &Host, a: &[Data]) -> Answer { @@ -781,12 +802,17 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } + // A compound path whose members are cleared stays, empty, as it does after `remove()` of its last + // path. + let in_compound = c.is_some_and(|c| with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })))); if !ids.is_empty() { on_doc(h, doc.uid, true, |h| { for p in &masked { command(h, "layer.clippingMask.toggle", &json!({"id": p.0}))?; } - command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})) + let ids: Vec = ids.iter().map(|i| i.0).collect(); + let params = if in_compound { json!({"ids": ids, "keepEmpty": true}) } else { json!({"ids": ids}) }; + command(h, "edit.clear", ¶ms) })?; } Ok(Data::Undefined) @@ -852,10 +878,42 @@ fn compounds_remove_all(h: &Host, a: &[Data]) -> Answer { } fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer { - let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; - // A compound path's `pathItems` are its `PageItems`: it holds only paths. - let compound = c.is_some_and(|c| with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })))); - Ok(text(if compound && kind == Kind::Any { "PathItems" } else { kind.class() })) + art_scope(h, arg(a, 0), kind.class())?; + Ok(text(kind.class())) +} + +/// The `PathItems` of a compound path: a `PathItems` object whose handle names the compound path. +/// `PathItems`' members hand over to the functions below when their handle names one +/// ([`is_scoped_paths`]). +fn compound_path_items(h: &Host, a: &[Data]) -> Answer { + let item = this_item_of(h, a, "CompoundPathItem")?; + Ok(collection(h, Kind::Path, Some(item.id), item.doc.uid)) +} + +pub(super) fn is_scoped_paths(a: &[Data]) -> bool { + host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == "PathItems" && handle.len() == 5) +} + +pub(super) fn paths_typename(h: &Host, a: &[Data]) -> Answer { + art_typename(h, a, Kind::Path) +} +pub(super) fn paths_length(h: &Host, a: &[Data]) -> Answer { + art_length(h, a, Kind::Path) +} +pub(super) fn paths_parent(h: &Host, a: &[Data]) -> Answer { + art_parent(h, a, Kind::Path) +} +pub(super) fn paths_at(h: &Host, a: &[Data]) -> Answer { + art_at(h, a, Kind::Path) +} +pub(super) fn paths_by_name(h: &Host, a: &[Data]) -> Answer { + art_by_name(h, a, Kind::Path) +} +pub(super) fn paths_index(h: &Host, a: &[Data]) -> Answer { + art_index(h, a, Kind::Path) +} +pub(super) fn paths_remove_all(h: &Host, a: &[Data]) -> Answer { + art_remove_all(h, a, Kind::Path) } pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer { @@ -943,11 +1001,19 @@ fn group_clipped(h: &Host, a: &[Data]) -> Answer { } /// `clipped = true`: the group's topmost object becomes its clipping path; `false` releases the -/// clipping mask. The group keeps its id either way. +/// clipping mask. The group keeps its id either way. The path that becomes or stops being the +/// clipping path (the topmost object, or the bottom one while the group clips) must be shown and +/// unlocked, as the group must. fn group_set_clipped(h: &Host, a: &[Data]) -> Answer { let on = boolean(arg(a, 1), "clipped")?; let item = this_item_of(h, a, "GroupItem")?; - let (now, ok) = with_doc(h, item.doc, |_, st| (st.doc.node(item.id).is_some_and(crate::doc::Node::clips), editable(&st.doc, item.id))); + let (now, ok, mask) = with_doc(h, item.doc, |_, st| { + let n = st.doc.node(item.id); + let now = n.is_some_and(crate::doc::Node::clips); + let children = n.and_then(|n| n.children()).map_or(&[][..], Vec::as_slice); + let mask = if now { children.first() } else { children.iter().rev().find(|c| !c.is_ruler_guide()) }; + (now, editable(&st.doc, item.id), mask.map(|m| (m.id, editable(&st.doc, m.id)))) + }); if now == on { return Ok(Data::Undefined); } @@ -955,6 +1021,12 @@ fn group_set_clipped(h: &Host, a: &[Data]) -> Answer { if !ok { return Err(HostError::Error(format!("Cannot change GroupItem {}: it is hidden or locked", item.id.0))); } + if let Some((mask, mask_ok)) = mask { + super::refuse_protected_edit(h, Item { doc: item.doc, id: mask })?; + if !mask_ok { + return Err(HostError::Error(format!("Cannot change GroupItem {}: its clipping path {} is hidden or locked", item.id.0, mask.0))); + } + } on_doc(h, item.doc.uid, true, |h| command(h, "layer.clippingMask.toggle", &json!({"id": item.id.0})))?; Ok(Data::Undefined) } @@ -977,7 +1049,7 @@ pub(super) fn members(class: &str, l: &Link) -> Vec { m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); m } - "CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items), collection_of("PathItems"))]), + "CompoundPathItem" => named(vec![("pathItems", get(l, compound_path_items), collection_of("PathItems"))]), _ => Vec::new(), } } @@ -1333,6 +1405,14 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into())) }) })?; + // The active artboard keeps its id; an artboard inserted before it gives it the next index, which + // the steps `app.doScript` plays then act on. + if with_doc(h, doc, |_, st| active_artboard(st)) != active { + let mut shifted = h.dom.boards_shifted.borrow_mut(); + if !shifted.contains(&doc.uid) { + shifted.push(doc.uid); + } + } Ok(board_ref(h, doc.uid, id)) } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 03ec3812a6..8f6929e35c 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -395,27 +395,50 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { Ok(host_ref("PathItems", &[float(h.run), float(doc.uid)])) } +/// The document of a document's `PathItems`. The `PathItems` of a compound path are read through +/// [`super::layers`], and they make no paths: each method that would make one throws. fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result { + if super::layers::is_scoped_paths(a) { + return Err(HostError::Error("a compound path's pathItems cannot make paths".into())); + } doc_of(h, arg(a, 0), "PathItems") } /// `typename` of the paths of a document that is still open. fn items_typename(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_typename(h, a); + } items_doc(h, a)?; Ok(Data::String("PathItems".into())) } +/// `toString()`: `[PathItems]`, a document's or a compound path's. +fn items_to_string(h: &super::Host, a: &[Data]) -> Answer { + items_typename(h, a)?; + Ok(Data::String("[PathItems]".into())) +} + fn items_length(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_length(h, a); + } let doc = items_doc(h, a)?; Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64))) } fn items_parent(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_parent(h, a); + } let doc = items_doc(h, a)?; Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) } fn items_at(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_at(h, a); + } let doc = items_doc(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; @@ -423,6 +446,9 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer { } fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_by_name(h, a); + } let doc = items_doc(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { @@ -434,6 +460,9 @@ fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { } fn items_index(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_index(h, a); + } match arg(a, 1) { Data::String(_) => items_by_name(h, a), Data::Number(_) => match items_at(h, a)? { @@ -448,6 +477,9 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { /// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before /// anything is deleted, as `PageItems.removeAll()` does. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_remove_all(h, a); + } let doc = items_doc(h, a)?; let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = path_items(h, st)?; @@ -1903,6 +1935,7 @@ pub(super) fn classes(l: &Link) -> Vec { None, named(vec![ ("typename", get(l, items_typename), typed("string")), + ("toString", method(l, items_to_string), returns("string", &[])), ("length", get(l, items_length), typed("number")), ("parent", get(l, items_parent), typed("Document")), ("index", method(l, items_index), returns("PathItem", &[("itemKey", "*")])), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 361a7e0e00..bbd00ecebe 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -827,9 +827,10 @@ struct Host { /// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it. active_artboards: Vec<(u64, usize)>, /// The artboards the Artboard tool had selected in the active document as the run starts (two or - /// more), with that document's uid. The run gives the tool fresh state, which drops them, so the - /// steps `app.doScript` plays read them here. - artboard_picks: Option<(u64, Vec)>, + /// more), by artboard id, with that document's uid. The run gives the tool fresh state, which + /// drops them, so the steps `app.doScript` plays read them here, at the indices those artboards + /// have when each step runs. + artboard_picks: Option<(u64, Vec)>, /// 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 @@ -2235,7 +2236,10 @@ impl Session { } // The Artboard tool's selection, which the fresh tool state below drops. let picks = cmd::artboard_tool_picks(self); - let artboard_picks = self.active().filter(|_| !picks.is_empty()).map(|d| (d.uid, picks)); + let artboard_picks = self + .active() + .filter(|_| !picks.is_empty()) + .map(|d| (d.uid, picks.iter().filter_map(|i| d.doc.artboards.get(*i).map(|ab| ab.id)).collect())); self.reset_tool(); let open: Vec = self.docs.iter().map(|d| d.uid).collect(); self.script_high_water.retain(|uid, _| open.contains(uid)); diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index 396abbab4c..32dfb781b8 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -413,3 +413,46 @@ fn a_run_keeps_the_artboard_tools_selection_for_its_steps() { s.execute("artboard.delete", &json!({"index": 2})).unwrap(); assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1})); } + +/// After the script inserts an artboard before the active one, a step that names no artboard acts +/// on the artboard that was active, at its new index, not on the artboard now at the old index. +#[test] +fn steps_follow_the_active_artboard_past_an_inserted_one() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let was = boards(&s); + make_active(&mut s, 1); + let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]); + log_with(&mut s, "app.activeDocument.artboards.insert([2000, 300, 2100, 200], 0); app.doScript('Fit', 'Set');", &actions); + let after = boards(&s); + assert_eq!(after.len(), 4); + assert_eq!(after[1], was[0], "the artboard now at the old index is left as it was"); + assert_ne!(after[2], was[1], "the artboard that was active fits the selection"); + assert_eq!(after[3], was[2]); +} + +/// The Artboard tool's selection as the run started stays on the same artboards after the script +/// inserts one before them: a Fit to Artwork Bounds step fits those artboards at their new indices. +#[test] +fn the_artboard_tools_selection_follows_its_artboards_past_an_inserted_one() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let mut art = Vec::new(); + for b in &was { + let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap()); + } + make_active(&mut s, 1); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([0, 2])); + let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToArt"})])]); + log_with(&mut s, "app.activeDocument.artboards.insert([2000, 300, 2100, 200], 0); app.doScript('Fit', 'Set');", &actions); + let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(boards[1..], [art[0], was[1], art[2]], "the selected artboards fit their art"); +} diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 40b9b31513..5c9488874b 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1936,11 +1936,12 @@ fn wrappers_go_stale_after_revert() { assert_eq!(log(&mut s, &source), vec![json!(stale), json!(2)], "{operation}"); } // An artboard read before the revert is stale too, although the loaded document has a board with its id. - let source = "var b = app.activeDocument.artboards[0]; b.name = 'changed'; vc.run('file.revert');\ - try { b.name = 'wrong'; vc.log('ran'); } catch (e) { vc.log(e.message); } vc.log(app.activeDocument.artboards[0].name);"; + let source = "var b = app.activeDocument.artboards[0], saved = b.name; b.name = 'changed'; vc.run('file.revert');\ + try { b.name = 'wrong'; vc.log('ran'); } catch (e) { vc.log(e.message); } vc.log(app.activeDocument.artboards[0].name); vc.log(saved);"; let out = log(&mut s, source); assert_eq!(out[0], json!("Stale artboard"), "{out:?}"); - assert_ne!(out[1], json!("wrong"), "{out:?}"); + assert_ne!(out[2], json!("changed"), "{out:?}"); + assert_eq!(out[1], out[2], "the revert gives the artboard the saved name: {out:?}"); } #[test] @@ -2011,12 +2012,54 @@ fn clipped_refuses_a_group_on_a_locked_artboard() { .unwrap(); let steps = undo_steps(&s); run(&mut s, "app.activeDocument.groupItems[0].clipped = false;").unwrap(); - let e = failure(&mut s, "app.activeDocument.groupItems[0].clipped = true;"); - assert!(e.contains("locked artboard"), "{e}"); + // The script reads `clipped` after the error, before the run's rollback could put a change back. + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0]; try { g.clipped = true; vc.log('ran'); } catch (e) { vc.log(e.message); } vc.log(g.clipped);", + ); + assert!(out[0].as_str().unwrap().contains("locked artboard"), "{out:?}"); + assert_eq!(out[1], json!(false), "{out:?}"); assert!(!s.active().unwrap().doc.node(gid).unwrap().clips()); assert_eq!(undo_steps(&s), steps); } +/// `clipped` on a shown, unlocked group throws and changes nothing when the path that would become +/// the clipping path, or the clipping path it would release, is locked. +#[test] +fn clipped_refuses_a_locked_clipping_path() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 0.0, 0.0, 5.0, 5.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let top = s.active().unwrap().doc.node(gid).unwrap().children().unwrap().last().unwrap().id; + let set = |s: &mut Session, on: bool| { + let source = format!( + "var g = app.activeDocument.groupItems[0]; try {{ g.clipped = {on}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }} vc.log(g.clipped);" + ); + log(s, &source) + }; + s.execute("object.setProps", &json!({"ids": [top.0], "locked": true})).unwrap(); + let paint = format!("{:?}", s.active().unwrap().doc.node(top).unwrap()); + let steps = undo_steps(&s); + let out = set(&mut s, true); + assert!(out[0].as_str().unwrap().contains("hidden or locked"), "{out:?}"); + assert_eq!(out[1], json!(false), "{out:?}"); + let now = s.active().unwrap().doc.node(gid).unwrap(); + assert!(!now.clips()); + assert_eq!(now.children().unwrap().last().unwrap().id, top, "the locked path stays on top"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.node(top).unwrap()), paint, "the locked path keeps its paint"); + assert_eq!(undo_steps(&s), steps); + // Releasing a clipping mask whose clipping path is locked is refused too. + s.execute("object.setProps", &json!({"ids": [top.0], "locked": false})).unwrap(); + assert_eq!(set(&mut s, true), [json!("ran"), json!(true)]); + let mask = s.active().unwrap().doc.node(gid).unwrap().children().unwrap()[0].id; + s.execute("object.setProps", &json!({"ids": [mask.0], "locked": true})).unwrap(); + let out = set(&mut s, false); + assert!(out[0].as_str().unwrap().contains("hidden or locked"), "{out:?}"); + assert_eq!(out[1], json!(true), "{out:?}"); +} + /// A loop over `layers.length` and `layers[i]` lists the layers once while the document is /// unchanged, so it looks at each layer a bounded number of times. #[test] @@ -2034,6 +2077,41 @@ fn a_loop_over_layers_lists_them_once() { assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers"); } +/// A loop that reads each layer's `zOrderPosition` lists the layers and their places once while the +/// document is unchanged. +#[test] +fn a_loop_over_layers_z_order_positions_lists_them_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for _ in 0..39 { + s.execute("layer.new", &json!({})).unwrap(); + } + let n = s.active().unwrap().doc.layers.len() as u64; + crate::script::dom::LAYER_SCANS.with(|c| c.set(0)); + let out = log( + &mut s, + "var L = app.activeDocument.layers, z = []; for (var i = 0; i < L.length; i++) z.push(L[i].zOrderPosition); vc.log(z[0]); vc.log(z[z.length - 1]);", + ); + assert_eq!(out, vec![json!(n), json!(1)]); + let scans = crate::script::dom::LAYER_SCANS.with(std::cell::Cell::get); + assert!(scans <= 3 * n, "{scans} nodes looked at for {n} layers"); +} + +/// Assigning a layer an opacity its getter would read back as another number runs the command, +/// though it is within 0.0001 of the opacity the layer has; the number the getter reports is a no-op. +#[test] +fn a_layers_opacity_is_set_unless_the_getter_already_reports_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "app.activeDocument.layers[0].opacity = 0;"); + let steps = undo_steps(&s); + let out = log(&mut s, "var l = app.activeDocument.layers[0]; l.opacity = l.opacity; vc.log(l.opacity);"); + assert_eq!(out, [json!(0)]); + assert_eq!(undo_steps(&s), steps, "the opacity the getter reports runs no command"); + let out = log(&mut s, "var l = app.activeDocument.layers[0]; l.opacity = 0.00009; vc.log(l.opacity);"); + assert_eq!(out, [json!(0.0001)]); +} + /// Art on a locked artboard stays: `remove()` and `removeAll()` throw and delete nothing. #[test] fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { @@ -2633,6 +2711,42 @@ fn a_compound_paths_path_items_are_path_items() { assert_eq!(out, [json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems")]); } +/// A compound path's `pathItems` is a `PathItems` object that lists the compound path's own paths: +/// it reads them, its `parent` is the compound path, and each method that would make a path throws +/// and makes none. +#[test] +fn a_compound_paths_path_items_list_its_paths_and_make_none() { + let (mut s, a, b) = doc(); + rect(&mut s, 200.0, 20.0, 10.0, 10.0); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "inner"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.compoundPathItems[0], p = c.pathItems, n = d.pathItems.length;\ + vc.log(p.parent === c); vc.log(p.getByName('inner').name);\ + try { p.rectangle(10, 10, 5, 5); vc.log('made'); } catch (e) { vc.log(e.message); }\ + try { p.add(); vc.log('made'); } catch (e) { vc.log(e.message); }\ + vc.log(p.length); vc.log(d.pathItems.length === n);", + ); + let refused = json!("a compound path's pathItems cannot make paths"); + assert_eq!(out, [json!(true), json!("inner"), refused.clone(), refused, json!(2), json!(true)]); +} + +/// `compound.pathItems.removeAll()` deletes the compound path's paths and keeps the compound path, +/// empty, as `remove()` of its last path does. +#[test] +fn removing_all_of_a_compound_paths_paths_keeps_the_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let out = + log(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log(c.pathItems.length); vc.log(c.typename);"); + assert_eq!(out, [json!(0), json!("CompoundPathItem")]); + assert!(s.active().unwrap().doc.node(NodeId(c)).is_some()); + assert!(s.active().unwrap().doc.node(a).is_none() && s.active().unwrap().doc.node(b).is_none()); +} + #[test] fn a_layers_and_a_compound_paths_items_answer_index_and_to_string() { let (mut s, a, b) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index f806a607d1..d0fa17f497 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -183,7 +183,10 @@ const INSIDE: &[(&str, &str)] = &[ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), ("PathItems.", "prototype"), - ("PathItems.prototype.", "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star typename"), + ( + "PathItems.prototype.", + "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star toString typename", + ), ("PathItem.", "prototype"), ( "PathItem.prototype.", diff --git a/docs/mcp.md b/docs/mcp.md index 391081ce60..f4795cc55f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3158,7 +3158,9 @@ through `$`: `compoundPathItems` and a layer's or group's `pageItems` list art topmost first, as the document's `pageItems` does. The document's `groupItems` and `compoundPathItems` hold every group or compound path at any depth, and a layer's or group's hold only the ones directly in it. A layer's `pageItems` leave out its sublayers, and a compound path's `pathItems` - list its paths, with the typename `PathItems`. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole + are a `PathItems` object that lists its paths: `length`, `[i]`, `index(key)`, `getByName(name)`, `parent` (the + compound path), `toString()` and `removeAll()`, which keeps the compound path, empty. Its methods that make a path + throw an error. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole numbers from 0 to 255. A layer's name is from 1 to 512 characters. A layer's `zOrderPosition` counts the layers beside it from 1 at the bottom, leaving out art, and `zOrder` with `BRINGFORWARD` or `SENDBACKWARD` moves it past the next layer beside it and any art between them. @@ -3166,7 +3168,8 @@ through `$`: deselects only the layer's art (`select.toggle`); the rest of the selection, ruler guides included, stays. A layer with nothing to add or deselect runs no command. `clipped = true` makes the group's topmost object, which must be a path, a compound path or type, its clipping - path; `false` releases the mask; the group keeps its id. `groupItems.add()` makes an empty group on top of the + path; `false` releases the mask; the group keeps its id. A hidden or locked object that would become the clipping + path, or a hidden or locked clipping path that `false` would release, throws. `groupItems.add()` makes an empty group on top of the layer's or group's contents, or of the current layer's for the document's collection. `compoundPathItems.add()` throws, since a compound path holds at least one path. `artboards.add` and `insert` stop at 100 artboards in a document, the limit `Documents.add` uses. An artboard's rectangle is @@ -3626,8 +3629,10 @@ through `$`: Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to Selected Art) and does not name one acts on the active document's active artboard, by the index it had as the run started, which the view keeps: after the script deletes artboards, the artboard now at that index, or the last one - past the end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to - Artwork Bounds step act on those instead, as in the panel's playback. A step of a recorded `command.batch` step that + past the end. After `artboards.add` or `insert` gives the active artboard another index, such a step acts on that + artboard at its new index. While the Artboard tool has several artboards selected as the run starts, a paste step + and a Fit to Artwork Bounds step act on those artboards, at the indices they have when the step runs, as in the + panel's playback. A step of a recorded `command.batch` step that names its `artboard` acts on that artboard, or the last one past the end, as `command.batch` gives it. VectorCraft's own rules: the action and its set are matched by their exact names, and a name that matches no action or more than one throws an error before any step runs, as does an action with no included step. A stop, and a step whose command a script may not run or the engine does not have From a57173accc63373a4b384872a70a9c49a17c4c4d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 22:54:23 -0800 Subject: [PATCH 27/88] ROADMAP: M13 lists the layers, artboards, perspective grid and startup presets scripts have The M13 row lists layers, groups, compound paths and artboards, the perspective grid, `app.getPresetSettings` and `app.startupPresetsList` among what scripts have, and no longer lists layers and artboards as remaining. --- docs/roadmap.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index f669559fd2..3f616c0110 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -209,7 +209,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames, and save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, its stories and threaded frames, its layers, groups, compound paths and artboards, and its perspective grid, read the startup presets with `app.getPresetSettings` and `app.startupPresetsList`, and save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`; the rest of the script document model (paths, text lines and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged); Tools toolbar Search opens the existing tool-aware command palette (#8758) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | From 2fd7178d7cadbbdbb14de1584019374cb73b99ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 22:55:55 -0800 Subject: [PATCH 28/88] Color Effects: copied screen print marks go to the marks layer and the moved copy A marks group pasted into another document now goes into that document's marks layer, even when an unlocked ordinary layer has the same name. Before, the name match preferred the unlocked layer, so the marks landed in it. Moving an artboard with copy and moveArt now builds the copy's art with artboards_art, as Duplicate Artboards does, so a marks group lying wholly outside its artboard is copied with it. --- .../cmd/addons/color/screen_marks/tests.rs | 31 +++++++++++++++++++ crates/engine/src/cmd/edit.rs | 11 +++++-- crates/engine/src/cmd/xform.rs | 13 ++------ 3 files changed, 42 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs index 76c2c9f799..fd1912756d 100644 --- a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs +++ b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs @@ -383,6 +383,37 @@ fn marks_copied_with_an_artboard_paste_back_into_their_locked_layer() { assert_eq!(marks(&s), Some((true, 2)), "marking the pasted artboard replaces the pasted copy"); } +#[test] +fn marks_pasted_into_another_document_go_into_its_marks_layer_not_a_layer_of_the_same_name() { + let mut s = session(); + run(&mut s, json!({})); + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({})); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let plain = NodeId(s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].as_u64().unwrap()); + s.execute("edit.paste", &json!({})).unwrap(); + let kids = |s: &Session, l: NodeId| s.doc().unwrap().doc.node(l).map(|l| (l.locked, l.children().map_or(0, |k| k.len()))); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 2); + assert_eq!(kids(&s, layer), Some((true, 2)), "the pasted marks go into the locked marks layer"); + assert_eq!(kids(&s, plain), Some((false, 0)), "the ordinary layer of the same name stays empty"); +} + +#[test] +fn marks_lying_off_an_artboard_go_with_its_copy_made_by_moving_it() { + let mut s = session(); + let r = run(&mut s, json!({"positions": ["right"], "inset": -200})); + let b = bounds(&node(&s, r["ids"][0].as_u64().unwrap())); + assert!(b.x0 >= 600.0, "the marks lie wholly off the artboard: {b:?}"); + let p = json!({"index": 0, "dy": 500, "copy": true, "moveArt": true, "lockedAndHidden": true}); + s.execute("artboard.move", &p).unwrap(); + let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 2); + assert_eq!(kids(&s), 2, "the copy carries a copy of the marks"); + run(&mut s, json!({"artboard": 1, "positions": ["right"], "inset": -200, "size": 30})); + assert_eq!(kids(&s), 2, "marking the copy replaces the copied marks"); +} + #[test] fn other_art_copied_with_an_artboard_does_not_paste_into_a_locked_layer() { let mut s = session(); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index b005e1e56b..ff90db1370 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1884,9 +1884,15 @@ fn remembered_layers(d: &Document, sources: &[Option], marks: &[boo /// it still where they were (by id) are kept. Below them, and in another document from the top, /// each name is matched among the layers inside the one above (the topmost of the same name whose /// layers match the most names, a shown and unlocked one first). The names left unmatched are -/// made. A matched layer that is hidden or locked, or inside one that is, is an error, except the -/// marks layer for a screen print marks group (`marks`). +/// made. A matched layer that is hidden or locked, or inside one that is, is an error. A screen +/// print marks group (`marks`) goes into the document's marks layer, locked or hidden as it is, +/// when the document has one. fn remembered_layer(d: &Document, src: &SourceLayer, marks: bool, same_doc: bool) -> Result { + // A marks group goes into the document's marks layer when it has one, not into an ordinary + // layer of the same name. + if marks && let Some(l) = super::addons::screen_marks_layer(d) { + return Ok(Remembered::Layer(l)); + } let held = |id: &NodeId| d.node(*id).is_some_and(|n| n.is_layer() && n.name.as_ref() == src.names.last()); let kept = if same_doc && src.ids.last().is_some_and(held) { src.ids.len() @@ -1901,7 +1907,6 @@ fn remembered_layer(d: &Document, src: &SourceLayer, marks: bool, same_doc: bool let rest = &src.names[kept..]; let (end, matched, _) = named_chain(d, kept.checked_sub(1).map(|j| src.ids[j]), rest); if let Some(l) = end - && !(marks && matched == rest.len() && super::addons::screen_marks_layer(d) == Some(l)) && !d.ancestry(l).is_some_and(|a| a.iter().all(|i| d.node(*i).is_some_and(|n| n.visible && !n.locked))) { return Err(EngineError::Other("the target layer is locked or hidden".into())); diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index 6656711738..63f47d652a 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -685,16 +685,9 @@ fn artboard_move(s: &mut Session, p: &Value) -> Result { if !copy { super::panelcmds::refuse_locked(&s.doc()?.doc, &indices)?; } - // Each artboard's art, an object counted once (artboards can overlap). - let mut arts: Vec<(usize, Vec)> = vec![]; - for &i in &indices { - let art = super::panelcmds::artboard_art(s, i, move_art, locked_art, !copy)?; - let art = art.into_iter().filter(|id| !arts.iter().any(|(_, a)| a.contains(id))).collect(); - arts.push((i, art)); - } - if copy { - arts = super::panelcmds::marks_with_owners(&s.doc()?.doc, arts); - } + // Each artboard's art, an object counted once (artboards can overlap). A copy also takes each + // copied artboard's screen print marks group, wherever the group lies. + let arts = super::panelcmds::artboards_art(s, &indices, move_art, locked_art, !copy)?; let ids: Vec = arts.iter().flat_map(|(_, a)| a.iter().copied()).collect(); let sc = Scaling { patterns: super::object::transform_patterns(s, p, &ids)?, ..Scaling::default() }; let (index, moved) = s.edit(if copy { "Duplicate Artboard" } else { "Move Artboard" }, |d, _| { From e4e77b422c3b6f910fe1312d52ba7d45fad9478a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 00:19:24 -0800 Subject: [PATCH 29/88] Scripts: name the artboard and layer-position types clippy flags as complex Clippy's type_complexity lint stopped the gate on the tuple types in doScript's artboard step and the kept layer list. The types get names (ActiveBoards, BoardPicks, LayerPositions); nothing else changes. --- crates/engine/src/script/actions.rs | 7 ++++++- crates/engine/src/script/dom/layers.rs | 7 +++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index f16cb3ada2..490bb3863c 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -27,6 +27,11 @@ use vectorcraft_js::{Data, HostError, HostMember}; use super::{Host, Link, command, current, refused_to_scripts}; +/// Each open document's uid with the artboard index a run plays on. +type ActiveBoards = Vec<(u64, usize)>; +/// A document's uid with the indices of the artboards the Artboard tool holds. +type BoardPicks = Option<(u64, Vec)>; + /// The most actions a run's request may carry. pub const MAX_ACTIONS: usize = 4096; /// The most steps one action may have, after a `command.batch` step gives its own steps. @@ -258,7 +263,7 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { // where `artboards.add` or `artboards.insert` moved the active artboard to another index plays // on that artboard at its new index. The Artboard tool's selection is the artboards it held, // at the indices they have now. - let (active, picks): (Vec<(u64, usize)>, Option<(u64, Vec)>) = { + let (active, picks): (ActiveBoards, BoardPicks) = { let moved = h.dom.active_artboards.borrow(); let shifted = h.dom.boards_shifted.borrow(); let session = h.session.borrow(); diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 04debab36a..b69fb2a6e3 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -494,7 +494,10 @@ fn layer_list(d: &Document, parent: Option) -> Vec { /// A document's uid, the document as it was, the parent a `Layers` object lists (`None`: the top /// level), the layers it listed then and, once a layer's place was asked for, each layer's index in /// that list. -pub(super) type LayerList = (u64, Arc, Option, Rc>, Rc>>); +pub(super) type LayerList = (u64, Arc, Option, Rc>, LayerPositions); + +/// Each layer's index in a kept list, built the first time it is asked for. +pub(super) type LayerPositions = Rc>>; /// The layers of `parent` as [`layer_list`] gives them. The last [`ART_LISTS`] lists are kept while /// their documents are unchanged, so a loop over `layers[i]` lists the layers once. Each new list @@ -505,7 +508,7 @@ fn layers_listed(h: &Host, st: &DocState, parent: Option) -> Result) -> Result<(Rc>, Rc>>)> { +fn layers_kept(h: &Host, st: &DocState, parent: Option) -> Result<(Rc>, LayerPositions)> { { let mut lists = h.dom.layers.borrow_mut(); let at = lists.iter().position(|(uid, doc, p, ..)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent); From 3d5c51b6892b1fcf18c2fc2f8d603c610fed2f2c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:35:21 -0800 Subject: [PATCH 30/88] Screen print marks: artboard moves and cuts take marks by their owner Moving an artboard with its art now takes its own screen print marks group by the artboard recorded on it, even when the group lies outside every artboard, and leaves another artboard's group that lies on it. Cut already did; the duplicate code path for it is removed. Tests cover duplicate, Alt-drag, copy and cut of overlapping artboards and of marks outside the artboard, and moves with and without Move Locked and Hidden Artwork. --- .../cmd/addons/color/screen_marks/tests.rs | 105 ++++++++++++++++++ crates/engine/src/cmd/panelcmds.rs | 15 +-- crates/engine/src/cmd/xform.rs | 5 +- docs/mcp.md | 3 +- docs/target-app-parity.md | 2 + 5 files changed, 116 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs index fd1912756d..e1cc3aec9e 100644 --- a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs +++ b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs @@ -488,6 +488,111 @@ fn marks_lying_on_another_copied_artboard_go_with_their_own_artboards_copy() { assert_eq!(run(&mut s, p)["changed"], json!(false), "the first artboard's marks are unchanged"); } +/// `target` (`index` or `indices`) with the parameters each artboard copy command takes: an +/// Alt-drag for `artboard.move`, and the artboards' art for the others. +fn copy_params(command: &str, target: Value) -> Value { + let mut p = match command { + "artboard.move" => json!({"moveArt": true, "copy": true, "dy": 500, "lockedAndHidden": true}), + _ => json!({"art": true, "lockedAndHidden": true}), + }; + if let (Some(p), Some(t)) = (p.as_object_mut(), target.as_object()) { + p.extend(t.clone()); + } + p +} + +#[test] +fn overlapping_artboard_copies_keep_one_marks_group_per_owner() { + for command in ["artboard.duplicate", "artboard.move", "artboard.copy"] { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 600, "height": 400})).unwrap(); + let first = run(&mut s, json!({"artboard": 0, "positions": ["right"]})); + let second = run(&mut s, json!({"artboard": 1, "positions": ["left"]})); + let before = s.doc().unwrap().doc.clone(); + let originals = [node(&s, first["ids"][0].as_u64().unwrap()), node(&s, second["ids"][0].as_u64().unwrap())]; + let p = copy_params(command, json!({"indices": [0, 1]})); + s.execute(command, &p).unwrap(); + if command == "artboard.copy" { + s.execute("edit.paste", &json!({})).unwrap(); + } + let d = &s.doc().unwrap().doc; + let groups = d.layers[0].children().unwrap(); + assert_eq!(groups.len(), 4, "{command}"); + for (source, original) in originals.iter().enumerate() { + assert!(d.node(original.id).unwrap() == original, "{command}"); + let copied_board = &d.artboards[source + 2]; + let copies: Vec<_> = groups.iter().filter(|g| super::owner(g) == Some(copied_board.id)).collect(); + assert_eq!(copies.len(), 1, "{command}: owner {source}"); + let offset = copied_board.rect.origin() - d.artboards[source].rect.origin(); + assert_eq!(bounds(copies[0]), bounds(original) + offset, "{command}: owner {source}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc == before, "{command}: one undo restores both artboards and marks"); + } +} + +#[test] +fn off_board_marks_follow_artboard_copies_and_cuts_by_owner() { + for command in ["artboard.duplicate", "artboard.move", "artboard.copy", "artboard.cut"] { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200})); + let original = node(&s, r["ids"][0].as_u64().unwrap()); + let other = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200})); + let foreign = node(&s, other["ids"][0].as_u64().unwrap()); + assert!(bounds(&original).y1 < 0.0); + assert!(s.doc().unwrap().doc.artboards[0].rect.contains_rect(bounds(&foreign))); + let before = s.doc().unwrap().doc.clone(); + let p = copy_params(command, json!({"index": 0})); + let reply = s.execute(command, &p).unwrap(); + if command == "artboard.cut" { + assert_eq!(reply["copied"], json!(1)); + assert!(s.doc().unwrap().doc.node(original.id).is_none()); + } + if matches!(command, "artboard.copy" | "artboard.cut") { + s.execute("edit.paste", &json!({})).unwrap(); + } + let d = &s.doc().unwrap().doc; + let copied_board = d.artboards.last().unwrap(); + let copies: Vec<_> = d.layers[0].children().unwrap().iter().filter(|g| super::owner(g) == Some(copied_board.id)).collect(); + assert_eq!(copies.len(), 1, "{command}"); + assert!(d.node(foreign.id).unwrap() == &foreign, "{command}: another artboard's marks stay unchanged"); + let offset = copied_board.rect.origin() - before.artboards[0].rect.origin(); + assert_eq!(bounds(copies[0]), bounds(&original) + offset, "{command}"); + s.execute("edit.undo", &json!({})).unwrap(); + if command == "artboard.cut" { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert!(s.doc().unwrap().doc == before, "{command}"); + } +} + +#[test] +fn moving_an_artboard_uses_marks_ownership_instead_of_containment() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let outside = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200})); + let other = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200})); + let own = node(&s, outside["ids"][0].as_u64().unwrap()); + let foreign = node(&s, other["ids"][0].as_u64().unwrap()); + assert!(bounds(&own).y1 < 0.0); + assert!(s.doc().unwrap().doc.artboards[0].rect.contains_rect(bounds(&foreign))); + let before = s.doc().unwrap().doc.clone(); + for (move_art, all) in [(false, true), (true, false)] { + s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": move_art, "lockedAndHidden": all})).unwrap(); + assert!(node(&s, own.id.0) == own); + assert!(node(&s, foreign.id.0) == foreign); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc == before); + } + s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": true, "lockedAndHidden": true})).unwrap(); + assert_eq!(bounds(&node(&s, own.id.0)), bounds(&own) + vectorcraft_geom::Vec2::new(0.0, 500.0)); + assert!(node(&s, foreign.id.0) == foreign); + assert_eq!(super::owner(&node(&s, own.id.0)), super::owner(&own)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc == before); +} + #[test] fn marks_lying_on_another_artboard_go_with_their_own_artboards_copy_alone() { let mut s = session(); diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index f8d33ec1ac..8446f38eb8 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -38,7 +38,7 @@ pub fn specs() -> Vec { "Cut Artboard", [], None, - "{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}", + "{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden). With art, screen print marks go with their recorded owner artboard even outside its bounds, subject to lockedAndHidden; edit.cut runs this while the Artboard tool is chosen → {copied: objects}", has_doc, |s, p| { boards_and_art_noted(s, p, "artboard.cut")?; @@ -309,7 +309,7 @@ pub(crate) fn artboard_art(s: &Session, i: usize, art: bool, all: bool, moving: /// `arts` (artboard indices with their art) with each artboard's screen print marks group in its /// own artboard's entry: another artboard's group lying on one of them goes with its own artboard /// when that one is among `arts`, and is left out when it is not. Only the groups on the marks -/// layer count; a group whose artboard was deleted stays where it is. Copies and cuts of artboards. +/// layer count; a group whose artboard was deleted stays where it is. pub(crate) fn marks_with_owners(d: &vectorcraft_doc::Document, arts: Vec<(usize, Vec)>) -> Vec<(usize, Vec)> { let owners = super::addons::screen_marks_owners(d); if owners.is_empty() { @@ -343,18 +343,15 @@ pub(crate) fn marks_with_owners(d: &vectorcraft_doc::Document, arts: Vec<(usize, } /// Each of `indices` with the art that goes with it when `art` ([`artboard_art`]), an object -/// counted once, with the first of them it is on (artboards can overlap). A copy also takes each -/// copied artboard's own screen print marks group, wherever the group lies. +/// counted once, with the first of them it is on (artboards can overlap). With `art`, each +/// artboard takes its own eligible screen print marks group, wherever the group lies. pub(crate) fn artboards_art(s: &Session, indices: &[usize], art: bool, all: bool, moving: bool) -> Result)>> { let mut seen = std::collections::HashSet::new(); let mut arts = vec![]; for &i in indices { - let art = artboard_art(s, i, art, all, moving)?.into_iter().filter(|id| seen.insert(*id)).collect(); + let art: Vec = artboard_art(s, i, art, all, moving)?.into_iter().filter(|id| seen.insert(*id)).collect(); arts.push((i, art)); } - if moving { - return Ok(arts); - } let d = &s.doc()?.doc; if art { for (id, o) in super::addons::screen_marks_copied(d, all) { @@ -418,8 +415,6 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result = indices.iter().filter_map(|i| st.doc.artboards.get(*i).cloned()).collect(); let clip = Clipboard { source_artboard: boards.first().map(|a| a.rect), artboards: boards, ..Clipboard::copy(st, &art, false) }; diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index 63f47d652a..f7afd656d1 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Move Artboard", [], None, - "{index | indices: [index…], dx, dy, moveArt?: bool, copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard)} move artboards (and the art fully inside them; locked and hidden art, and art also on another locked artboard, only with lockedAndHidden), several in one step (an error when one is locked); `copy` (Alt-drag) leaves them and moves copies, which start unlocked → {index (the first), indices: the artboards moved or the copies, moved: the art moved or the copies}", + "{index | indices: [index…], dx, dy, moveArt?: bool, copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard)} move artboards (and the art fully inside them; locked and hidden art, and art also on another locked artboard, only with lockedAndHidden), several in one step (an error when one is locked); `copy` (Alt-drag) leaves them and moves copies, which start unlocked. With moveArt, screen print marks go with their recorded owner artboard even outside its bounds, subject to lockedAndHidden → {index (the first), indices: the artboards moved or the copies, moved: the art moved or the copies}", has_doc, artboard_move ), @@ -685,8 +685,7 @@ fn artboard_move(s: &mut Session, p: &Value) -> Result { if !copy { super::panelcmds::refuse_locked(&s.doc()?.doc, &indices)?; } - // Each artboard's art, an object counted once (artboards can overlap). A copy also takes each - // copied artboard's screen print marks group, wherever the group lies. + // Each artboard takes its art once and its own eligible screen print marks group. let arts = super::panelcmds::artboards_art(s, &indices, move_art, locked_art, !copy)?; let ids: Vec = arts.iter().flat_map(|(_, a)| a.iter().copied()).collect(); let sc = Scaling { patterns: super::object::transform_patterns(s, p, &ids)?, ..Scaling::default() }; diff --git a/docs/mcp.md b/docs/mcp.md index 2b95ef9d65..33ddb8e5a4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17919,7 +17919,8 @@ giving both is an error. Running the command again replaces that artboard's grou groups alone. A group copied with an artboard duplicated, Alt-dragged or pasted in the same document belongs to the copy. Another artboard's group lying on an artboard that is duplicated, Alt-dragged, copied or cut goes with its own artboard: it is copied with that artboard when that one is copied too, and otherwise stays where it is. A group whose artboard was -deleted is copied like other art. When the "Screen Print Marks" layer was +deleted is copied like other art. With art enabled, moves and cuts also take marks by their recorded owner, even when +the marks lie outside every artboard, subject to `lockedAndHidden`. When the "Screen Print Marks" layer was deleted, pasting an artboard with its marks makes the layer again, and the command uses that layer. Marks outside the artboard (a negative `inset`) appear in an export or a print clipped to the artboard only as far as its bleed reaches. It is one undo step, and none when the marks come out the same (`changed: false`). The selection is diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 01d39964e3..83400d420f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3303,6 +3303,8 @@ A VectorCraft addition (it replaces a script some users ran), so no area score m A VectorCraft addition, so no area score moves. Object › Plug-ins › Color Effects › Create Screen Print Marks… (`addon.color.screenMarks`) opens a dialog (the eight target positions, size, stroke weight, inset, ink, the spot ink and file lines with their type size, place and alignment, all artboards, with a preview) and draws registration targets (a circle half the target's width with a cross through it) inside the artboard in [Registration] or a spot ink, with an optional line naming the document's spot inks, each in its own ink, and an optional line with the file name and the date and time in UTC. The marks are document art: one group per artboard on a locked "Screen Print Marks" layer made at the bottom of the stack, so they print, separate and export with the rest of the art, where Create Trim Marks draws trim marks only and the PDF export's printer's marks exist only in the exported file. The lines move in past a top or bottom target they would cross. They stay where they are when moving would cross another target or leave the artboard. Marks copied with a duplicated artboard belong to the copy, and another artboard's marks lying on a copied artboard stay with their own artboard. A paste that makes the deleted marks layer again makes it the marks layer. Running it again replaces that artboard's marks; one undo step, none when the marks come out the same. Remaining: saved presets of the dialog's settings. Tests: `cmd::addons::color::screen_marks::tests` (engine), `addons::color::screen_marks::tests` (ui-egui). +With art enabled, artboard moves and cuts take eligible screen print marks by their recorded owner, including marks outside every artboard. Tests: `overlapping_artboard_copies_keep_one_marks_group_per_owner`, `off_board_marks_follow_artboard_copies_and_cuts_by_owner`, `moving_an_artboard_uses_marks_ownership_instead_of_containment` in `cmd::addons::color::screen_marks::tests`. + ## Stroke Weight Up and Down shortcuts (2026-11-06) Cmd/Ctrl+Alt+. (`stroke.weightUp`) and Cmd/Ctrl+Alt+, (`stroke.weightDown`) raise and lower the weight of each selected stroke from its own weight, with the keys a [public feature request reply](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/32307397-increment-decrement-stroke-weight-key-commands) names: a quarter unit of Units › Stroke at a time up to one unit, whole units above it, no lower than a quarter unit and no higher than 1000 pt. Type steps its stroked characters; objects without a stroke are left alone; with nothing selected the weight of the next object drawn steps. Each press is one undo step (#5797). Evidence: `tests::strokeux::stroke_weight_up_and_down_step_each_selected_stroke`, `stroke_weight_up_with_nothing_selected_sets_up_new_art`, `cmd::stroke::tests::weight_steps_follow_units_and_stop_at_their_bounds`. Scores unchanged. From e365915ce19ec200bb5d501572800bc98d4a9703 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:00:53 -0800 Subject: [PATCH 31/88] Screen print marks: docs say the marks layer is found by its tag The command finds the marks layer it made by a tag in the layer's data, not by its name, and a paste remakes the layer only when it was deleted while named "Screen Print Marks". --- docs/mcp.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 33ddb8e5a4..6c072b3aad 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17912,16 +17912,18 @@ screen printing inside an artboard as document art, so they print, separate and `bottom` target on its side, the lines move in past that target. They stay where they are when moving would cross another target or leave the artboard. -The marks of each artboard are one group, on the top-level layer "Screen Print Marks". When the document has no such -layer, the command makes it at the bottom of the stack, locked. A layer moved, unlocked or hidden stays as it is. +The marks of each artboard are one group, on the top-level marks layer the command made, which it finds by a tag in +the layer's data and not by its name. The command makes that layer, named "Screen Print Marks", at the bottom of the +stack, locked, when the document has none. Another layer with that name is not used, and the marks layer keeps its +role when renamed. A marks layer moved, unlocked or hidden stays as it is. `artboard` is an artboard's index (default: the active artboard) and `allArtboards: true` marks every artboard; giving both is an error. Running the command again replaces that artboard's group and leaves the other artboards' groups alone. A group copied with an artboard duplicated, Alt-dragged or pasted in the same document belongs to the copy. Another artboard's group lying on an artboard that is duplicated, Alt-dragged, copied or cut goes with its own artboard: it is copied with that artboard when that one is copied too, and otherwise stays where it is. A group whose artboard was deleted is copied like other art. With art enabled, moves and cuts also take marks by their recorded owner, even when -the marks lie outside every artboard, subject to `lockedAndHidden`. When the "Screen Print Marks" layer was -deleted, pasting an artboard with its marks makes the layer again, and the command uses that layer. Marks +the marks lie outside every artboard, subject to `lockedAndHidden`. When the marks layer was +deleted while named "Screen Print Marks", pasting an artboard with its marks makes the layer again, and the command uses that layer. Marks outside the artboard (a negative `inset`) appear in an export or a print clipped to the artboard only as far as its bleed reaches. It is one undo step, and none when the marks come out the same (`changed: false`). The selection is kept. An unknown position or one named twice, a number out of range, an `ink` that is not [Registration] or a spot From 1b9f1e26e8ca1ca44c64bf3b7206cd058fdb667f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 15:46:12 -0800 Subject: [PATCH 32/88] Image Trace: tracing again keeps the tracing's note and tags Tracing an Image Trace object again, with Image Trace > Make, Make and Expand, or a script's tracing options, replaced the object with one that had no attributes, so its note, tags and URL were lost. The new object now takes them over. A script's saved Tags and Tag objects follow the new object and keep their identity, as the PluginItem does. pathItems.removeAll() and textFrames.removeAll() could leave an image at the bottom of an ordinary group named Image Trace, which made the group a tracing. Both now throw "Only Image Trace can make a tracing" before anything is deleted, as move, remove() and zOrder do, counting a compound path that the deletion leaves empty. Follows up #9077. --- crates/engine/src/cmd/buildcmds/trace.rs | 25 ++++--- crates/engine/src/script/dom.rs | 18 +++++ crates/engine/src/script/dom/paths.rs | 11 ++- crates/engine/src/script/dom/tags.rs | 9 ++- crates/engine/src/script/dom/text.rs | 11 ++- crates/engine/src/tests/script_dom_tracing.rs | 75 +++++++++++++++++++ docs/mcp.md | 12 +-- docs/target-app-parity.md | 2 +- 8 files changed, 137 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index f5b3d9fa38..08a962f919 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -1225,17 +1225,20 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result) -> } } +/// Whether deleting the objects `ids` together would leave an image first in an ordinary group +/// named as a tracing, which would make that group one. `edit.clear` also deletes a compound path +/// it leaves empty, so such a compound path counts as deleted. +pub(super) fn clearing_makes_tracing(d: &Document, ids: &[NodeId]) -> bool { + let mut gone: HashSet = ids.iter().copied().collect(); + let compounds: HashSet = + ids.iter().filter_map(|i| d.parent_of(*i)).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))).collect(); + for c in compounds { + if d.children(Some(c)).is_some_and(|k| k.iter().all(|n| gone.contains(&n.id))) { + gone.insert(c); + } + } + let parents: HashSet = gone.iter().filter_map(|i| d.parent_of(*i)).filter(|p| !gone.contains(p)).collect(); + parents.into_iter().filter(|p| named_as_tracing(d, *p)).any(|p| { + d.children(Some(p)).and_then(|c| c.iter().find(|n| !gone.contains(&n.id)).map(|n| matches!(n.kind, NodeKind::Image(_)))).unwrap_or(false) + }) +} + /// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place. fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> { let index = with_doc(h, doc, |_, st| { diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index e4c32058fa..34db320f87 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -474,15 +474,17 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { /// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked /// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before -/// anything is deleted, as `PageItems.removeAll()` does. +/// anything is deleted, as `PageItems.removeAll()` does, and so does an image the deletion would +/// leave first in an ordinary group named as a tracing. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, tracing) = with_doc(h, doc, |_, st| { let ids = path_items(h, st)?; let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); let locks = st.doc.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused, on_locked)) + let tracing = super::clearing_makes_tracing(&st.doc, &ids); + Ok::<_, HostError>((ids, refused, on_locked, tracing)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -492,6 +494,9 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } + if tracing { + return Err(HostError::Error(super::NOT_A_TRACING.into())); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/script/dom/tags.rs b/crates/engine/src/script/dom/tags.rs index dff0120f78..c9e6f619c0 100644 --- a/crates/engine/src/script/dom/tags.rs +++ b/crates/engine/src/script/dom/tags.rs @@ -47,10 +47,12 @@ fn owner_of(h: &Host, d: &Data) -> std::result::Result { } /// The page item a handle's run, document uid and id (as [`id_parts`] gave it) name, which must -/// still be in its document. +/// still be in its document. A tracing the run traced again is followed to the object that +/// replaced it, which keeps its tags, as its `PluginItem` is. fn resolve_item(h: &Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result { let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = super::tracing::follow(h, doc.uid, id); let alive = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| typename(n).is_some())); if !alive { return Err(HostError::Error(STALE_ITEM.into())); @@ -111,7 +113,8 @@ fn doc_of_owner(owner: Owner) -> Doc { } fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data { - let [high, low] = id_parts(id); + // A tracing traced again keeps the id of the first object of its chain, as its `PluginItem` does. + let [high, low] = id_parts(super::tracing::origin(h, doc.uid, id)); let [tag_high, tag_low] = id_parts(NodeId(tag)); host_ref("Tag", &[float(h.run), float(doc.uid), high, low, tag_high, tag_low]) } @@ -119,7 +122,7 @@ fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data { /// `PageItem.tags`. pub(super) fn item_tags(h: &Host, a: &[Data]) -> Answer { let item = item_of(h, arg(a, 0))?; - let [high, low] = id_parts(item.id); + let [high, low] = id_parts(super::tracing::origin(h, item.doc.uid, item.id)); Ok(host_ref("Tags", &[float(h.run), float(item.doc.uid), high, low])) } diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 3c4acac317..9fae433f0e 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1363,16 +1363,18 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { } /// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a -/// locked artboard, stops it first, as `PageItems.removeAll()` does. +/// locked artboard, stops it first, as `PageItems.removeAll()` does, and so does an image the +/// deletion would leave first in an ordinary group named as a tracing. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let doc = frames_doc(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, tracing) = with_doc(h, doc, |_, st| { let ids = frame_ids(h, st)?; let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); let locks = st.doc.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused, on_locked)) + let tracing = super::clearing_makes_tracing(&st.doc, &ids); + Ok::<_, HostError>((ids, refused, on_locked, tracing)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -1382,6 +1384,9 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD))); } + if tracing { + return Err(HostError::Error(super::NOT_A_TRACING.into())); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 24223785dd..78e7fc930b 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -1302,3 +1302,78 @@ fn retraced_plugin_is_the_same_object_as_its_collection_handle() { assert_eq!(out, vec![json!(true); 5]); let _ = std::fs::remove_dir_all(base); } + +#[test] +fn retrace_keeps_the_tracing_note_and_tags() { + let base = folder("retrace-attributes"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(); p.note = 'keep me'; var tags = p.tags, t = tags.add(); t.name = 'job'; t.value = '42';\ + p.tracing.tracingOptions.threshold = 90; vc.log(p.note); vc.log(p.tags.length); vc.log(p.tags[0].name + '=' + p.tags[0].value);\ + vc.log(tags.length); vc.log(t.value); vc.log(t === p.tags[0]); vc.log(tags === p.tags);", + ); + assert_eq!(out, [json!("keep me"), json!(1), json!("job=42"), json!(1), json!("42"), json!(true), json!(true)]); + // Image Trace › Make on the tracing keeps them too. + let id = traces(&s)[0]; + let r = s.execute("imageTrace.make", &json!({"id": id.0, "params": {"threshold": 100}})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let d = &s.active().unwrap().doc; + let attrs = d.node(id).and_then(|n| n.extras().attrs.as_deref().cloned()).unwrap_or_default(); + assert_eq!(attrs.note, "keep me"); + let tags: Vec<(&str, &str)> = attrs.tags.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect(); + assert_eq!(tags, [("job", "42")]); + let r = s.execute("imageTrace.makeAndExpand", &json!({"id": id.0})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let d = &s.active().unwrap().doc; + let group = d.node(id).unwrap(); + assert!(matches!(group.kind, NodeKind::Group { .. })); + let attrs = group.extras().attrs.as_deref().cloned().unwrap_or_default(); + assert_eq!(attrs.note, "keep me"); + let tags: Vec<(&str, &str)> = attrs.tags.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect(); + assert_eq!(tags, [("job", "42")]); + let _ = std::fs::remove_dir_all(base); +} + +/// `pathItems.removeAll()` and `textFrames.removeAll()` refuse to leave an image at the bottom of an +/// ordinary group named as a tracing, before the document changes. +#[test] +fn remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() { + let setup = |bottom: &str| { + format!( + "var d = app.activeDocument; d.selection = [{bottom}]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);" + ) + }; + for (name, bottom, list) in [ + ("remove-all-trace-name-paths", "d.pathItems.rectangle(10, 10, 20, 20)", "pathItems"), + // `edit.clear` also deletes the compound path its members leave empty. + ( + "remove-all-trace-name-compound", + "(function () { d.selection = [d.pathItems.rectangle(10, 10, 20, 20), d.pathItems.rectangle(40, 40, 5, 5)];\ + vc.run('object.compoundPath.make'); return d.pageItems[0]; })()", + "pathItems", + ), + ("remove-all-trace-name-type", "d.textFrames.pointText([10, 10])", "textFrames"), + ] { + let base = folder(name); + let (mut s, _) = session(&base, false); + log(&mut s, &base, &setup(bottom)); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, m = ''; try {{ d.{list}.removeAll(); }} catch (e) {{ m = e.message; }}\ + vc.log(m); vc.log(d.pageItems[0].typename);" + ), + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!("GroupItem")], "{list}"); + assert!(traces(&s).is_empty(), "{list}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{list}"); + assert_eq!(undo_steps(&s), steps, "{list}"); + let _ = std::fs::remove_dir_all(base); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index e716a1a08e..eb4cd18da8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3143,8 +3143,9 @@ through `$`: unlocked source image (`TracingObject.sourceArt`) out of its tracing throws `a tracing's source image cannot leave its tracing` and changes nothing; a hidden source image (the default) throws `Cannot move`. Moving or duplicating an image to the bottom of an ordinary group named `Image Trace` throws `Only Image Trace can make a tracing` before - the document changes, as renaming such a group does. `move`, `remove()` and `zOrder` throw the same error, with - nothing changed, when they would leave an image at the bottom of such a group. An object of + the document changes, as renaming such a group does. `move`, `remove()`, `zOrder`, `pathItems.removeAll()` and + `textFrames.removeAll()` throw the same error, with nothing changed, when they would leave an image at the bottom of + such a group. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or @@ -3361,9 +3362,10 @@ through `$`: count the seam fills of an Abutting trace, `usedColorCount` counts the different fill and stroke paints, and `imageResolution` is the image's pixels per inch as placed, an error for an image placed at different resolutions across and down. Assigning an option, or `loadFromPreset(name)`, traces again with `imageTrace.make`, keeps the - source image and the view, and a value the tracing already has runs no command. Assigning `viewRaster` or - `viewVector` does not trace again: it runs `imageTrace.setView`. The `PluginItem`, `TracingObject` - and `TracingOptions` follow the new object, and a run traces again at most 10,000 times. Tracing again throws + source image, the view, and the tracing's attributes (its note, tags and URL), and a value the tracing already has + runs no command. Assigning `viewRaster` or `viewVector` does not trace again: it runs `imageTrace.setView`. The + `PluginItem`, `TracingObject`, `TracingOptions` and the tracing's `Tags` and `Tag` objects follow the new object, + and a run traces again at most 10,000 times. Tracing again throws `Cannot retrace a tracing containing added artwork`, with nothing changed, when the tracing holds an object its trace did not make, whether this run, an earlier run or a command added it, and `releaseTracing()` throws `Cannot release a tracing containing added artwork` in the same case. When no object was added, both throw diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 144759bf00..1961a50bae 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1115,7 +1115,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. - - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. + - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Tracing again keeps the tracing's note, tags and URL. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, or deleting paths or type with `removeAll()` so that an image is left at its bottom, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. From f78e95159b3a3c8bccf45973952e2119122ccf24 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 18:11:39 -0800 Subject: [PATCH 33/88] Scripting: keep the placed image size message after app.open's limit The 256 MiB document limit sat in Disk::open_target, which placedItems' file assignment also calls, so an oversized image was refused as "Script document exceeds 256 MiB" before its own check ("is larger than 256 MiB") ran, and placed_file_refuses_bad_values_without_changing_the_document failed. app.open now checks the document size itself after open_target, and open_target still reports a failed metadata read as a read failure. --- crates/engine/src/script/dom/save_open.rs | 4 ++++ crates/engine/src/script/files.rs | 6 +----- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 109d091180..a5886ca6d3 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -1091,6 +1091,10 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { } // The command opens the given path; a real path that is not valid UTF-8 is still refused. let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; + // The document's size is read before any of it is; a placed image keeps its own limit and message. + if std::fs::metadata(&real).is_ok_and(|m| m.len() > super::super::files::MAX_OPEN_BYTES) { + return Err(refused(super::super::files::OPEN_TOO_LARGE, path)); + } plain(real)?; p.insert("path".into(), json!(plain(std::path::PathBuf::from(path))?)); let r = crate::cmd::fileio::with_read_limit(super::super::files::MAX_OPEN_BYTES as usize, || { diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index b33e1c0c68..31ddbdacd2 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -726,13 +726,9 @@ impl Disk { Err(ScriptRead::Refused | ScriptRead::TooLarge) => return Err(ACCESS_DENIED), Err(ScriptRead::Failed(_)) => return Err(READ_FAILED), }; - let meta = std::fs::metadata(&real).map_err(|_| READ_FAILED)?; - if !meta.is_file() { + if !std::fs::metadata(&real).map_err(|_| READ_FAILED)?.is_file() { return Err(NOT_REGULAR); } - if meta.len() > MAX_OPEN_BYTES { - return Err(OPEN_TOO_LARGE); - } Ok(real) } From c4ba200e9a2fe8fc15245ec99f695c8a9277b4fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:13:56 -0800 Subject: [PATCH 34/88] Scripts: played steps follow the active artboard after the script adds or removes one A script that removed or inserted an artboard before the active one left the steps app.doScript plays on the index the run started with, so an Align to Artboard step acted on a different artboard than getActiveArtboardIndex() and the run's report gave. Adding, inserting or removing an artboard through artboards or Artboard.remove() now makes playback use the active artboard by id, as setActiveArtboardIndex does, which also follows an undo inside the run. - The locked-artboard removeAll test reads the collections' lengths inside the run after catching the refusal, so a delete before the refusal fails it. - layer.setProps and docs/mcp.md give dimImages: true as 50%. - docs/mcp.md says artboards.insert reorders only when the new artboard is not already at the index, and describes the playback rule. - The Document.views progress line no longer says Type is missing. --- crates/engine/src/cmd/layer.rs | 2 +- crates/engine/src/script/actions.rs | 4 +-- crates/engine/src/script/dom.rs | 3 +- crates/engine/src/script/dom/layers.rs | 26 ++++++++++------ crates/engine/src/tests/script_actions.rs | 36 +++++++++++++++++++++++ crates/engine/src/tests/script_dom.rs | 12 +++++++- docs/mcp.md | 18 +++++++----- docs/target-app-parity.md | 4 +-- 8 files changed, 81 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 469ff2721e..77b1ad4755 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Layer Options…", ["Window", "Layers"], None, - "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step, and none when every row already has every option given", + "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|true (50)|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step, and none when every row already has every option given", has_doc, set_props ), diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 8728bd76fb..d1e4088eee 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -253,8 +253,8 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { h.charge_call(16 + s.id.len() as u64 + s.bytes)?; // Saved steps run as they run in the Actions panel: keys their commands no longer read are // passed over. - // A document whose active artboard the script chose uses that choice, not the one the run - // started with. + // A document whose active artboard the script chose, or whose artboards the script added or + // removed, uses its active artboard by id, not the index the run started with. let chosen = h.session.borrow().active().and_then(|st| { h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?; Some((st.uid, super::dom::active_artboard(st))) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 2a82bfe3cb..e8559e3cd9 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -238,7 +238,8 @@ pub(super) struct State { layers: RefCell>, /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_artboards: RefCell>, - /// Each document's uid and revert generation when `setActiveArtboardIndex` last chose it. + /// Each document's uid and revert generation when `setActiveArtboardIndex` last chose its active + /// artboard, or the script last added or removed one of its artboards. pub(super) chosen_artboards: RefCell>, /// Each open document's uid and the index of its active artboard when the run started. pub(super) boards_at_start: Vec<(u64, usize)>, diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 4328c1bad2..433cd9c805 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -1289,6 +1289,7 @@ fn board_set_safe_areas(h: &Host, a: &[Data]) -> Answer { fn board_remove(h: &Host, a: &[Data]) -> Answer { let (b, i) = this_board(h, a)?; on_doc(h, b.doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?; + follow_active_board(h, b.doc.uid); Ok(Data::Undefined) } @@ -1401,6 +1402,7 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into())) }) })?; + follow_active_board(h, doc.uid); Ok(board_ref(h, doc.uid, id)) } @@ -1423,9 +1425,23 @@ fn boards_remove(h: &Host, a: &[Data]) -> Answer { let len = with_doc(h, doc, |_, st| st.doc.artboards.len()); let i = board_index_arg(arg(a, 1), len, "index")?; on_doc(h, doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?; + follow_active_board(h, doc.uid); Ok(Data::Undefined) } +/// After the script adds or removes an artboard in document `uid`, the steps `app.doScript` plays +/// act on the document's active artboard by id, at the index the run's report gives it, as after +/// `setActiveArtboardIndex`, until the document is reverted. +fn follow_active_board(h: &Host, uid: u64) { + let reverts = reverts_of(h, uid); + let mut chosen = h.dom.chosen_artboards.borrow_mut(); + if let Some((_, generation)) = chosen.iter_mut().find(|(u, _)| *u == uid) { + *generation = reverts; + } else { + chosen.push((uid, reverts)); + } +} + fn boards_active(h: &Host, a: &[Data]) -> Answer { let doc = boards_doc(h, a)?; Ok(num(float(with_doc(h, doc, |_, st| active_artboard(st)) as u64))) @@ -1444,15 +1460,7 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer { let st = s.document_mut(doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; st.active_artboard = st.doc.artboards.get(i).map(|ab| ab.id); } - { - let mut chosen = h.dom.chosen_artboards.borrow_mut(); - let reverts = reverts_of(h, doc.uid); - if let Some((_, generation)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) { - *generation = reverts; - } else { - chosen.push((doc.uid, reverts)); - } - } + follow_active_board(h, doc.uid); // A document made during the run has no index from the start of the run, so the first choice // records one; an artboard inserted before it later still puts it in the report. if !h.dom.boards_at_start.iter().any(|(uid, _)| *uid == doc.uid) { diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index ea399d2fd2..eb9af77a70 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -338,6 +338,42 @@ fn steps_discard_the_chosen_artboard_after_revert() { assert_ne!(now[2], was[2], "playback uses the run's original index after revert"); } +/// An artboard the script removes or inserts moves the active artboard's index; its played steps act +/// on the active artboard at the index `getActiveArtboardIndex()` gives, as the run's report does, +/// also after an undo puts the artboards back. +#[test] +fn steps_follow_the_active_artboard_after_the_script_removes_or_inserts_one_before_it() { + let setup = |active: Option| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + if let Some(i) = active { + make_active(&mut s, i); + } + (s, id) + }; + let actions = set(&[("Align", vec![json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}})])]); + let cases = [ + (Some(1), "A.remove(0);"), + (Some(1), "A[0].remove();"), + (Some(1), "A.insert([2000, 500, 2100, 400], 0);"), + (Some(1), "A.insert([2000, 500, 2100, 400], 2);"), + (Some(1), "A.remove(0); app.undo();"), + (None, "A.insert([2000, 500, 2100, 400], 0);"), + ]; + for (active, edit) in cases { + let (mut s, id) = setup(active); + let source = format!("var A = app.activeDocument.artboards; {edit} vc.log(A.getActiveArtboardIndex()); app.doScript('Align', 'Set');"); + let out = log_with(&mut s, &source, &actions); + let index = out[0].as_u64().unwrap() as usize; + let board = s.active().unwrap().doc.artboards[index].rect; + let left = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0; + assert_eq!(left, board.x0, "{active:?} {edit}"); + } +} + /// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none, /// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it. #[test] diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 73e44c2af7..77d6a72d68 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -2334,6 +2334,11 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() { lock(&mut s, true); let before = format!("{:?}", s.active().unwrap().doc.layers); let steps = undo_steps(&s); + // The lengths are read inside the run, after the refusal is caught, so a delete that ran before + // the refusal shows here even though a failed run would put the tree back. + let lengths = "vc.log([d.pageItems.length, d.layers[0].pageItems.length, d.groupItems.length, d.groupItems.length && d.groupItems[0].pageItems.length, \ + d.compoundPathItems.length]);"; + let counts = log(&mut s, &format!("var d = app.activeDocument; {lengths}")); for scope in [ "app.activeDocument.layers[0].pageItems", "app.activeDocument.layers[0].groupItems", @@ -2342,8 +2347,13 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() { "app.activeDocument.layers[0].compoundPathItems", "app.activeDocument.compoundPathItems", ] { - let err = failure(&mut s, &format!("{scope}.removeAll();")); + let out = log( + &mut s, + &format!("var d = app.activeDocument; try {{ {scope}.removeAll(); vc.log('ok'); }} catch (e) {{ vc.log(e.message); }} {lengths}"), + ); + let err = out[0].as_str().unwrap_or_default(); assert!(err.contains("cannot delete objects on a locked artboard"), "{scope}: {err}"); + assert_eq!(out[1..], counts[..], "{scope}: nothing is deleted before the refusal"); assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{scope}"); assert_eq!(undo_steps(&s), steps, "{scope}"); } diff --git a/docs/mcp.md b/docs/mcp.md index c3a96d73f9..f63a7a1049 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3284,7 +3284,8 @@ through `$`: `index(key)`, `getByName(name)`, `add()` and `removeAll()`. `groupItems.add()` runs `object.newGroup`. `clipped` runs `layer.clippingMask.toggle`. `artboards` (https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/) has `length`, `[i]`, `index(key)`, `getByName(name)`, `add(artboardRect)` (runs `artboard.new` and returns - the new artboard), `insert(artboardRect, index)` (runs `artboard.new` and `artboard.reorder`, returns nothing; + the new artboard), `insert(artboardRect, index)` (runs `artboard.new`, and `artboard.reorder` only when the new artboard is not + already at `index`, so an index equal to the length appends it; returns nothing; read `artboards[index]` afterward), `remove(index)` (runs `artboard.delete`), `getActiveArtboardIndex()` and `setActiveArtboardIndex(index)`. An `Artboard` (https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/) has `typename`, `parent`, `artboardRect`, `name`, @@ -3914,12 +3915,13 @@ through `$`: steps. A step that acts on the active artboard (Paste in Place, in Front and in Back, Align, Distribute Objects and Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to Selected Art) and does not name one acts on the active document's active artboard. Once the script has called - `setActiveArtboardIndex` on that document, it is the artboard the script chose while that artboard exists. If it - has been deleted, playback uses the same fallback as `getActiveArtboardIndex()`, script coordinates and the view: - the saved active artboard if it still exists, otherwise index 0. File > Revert discards the script's stored choice. - If the script has not chosen an artboard on that document since its last revert, the step uses the index of its active artboard - as the run started: after the script deletes artboards, the artboard now at that index, or the last one past the - end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to + `setActiveArtboardIndex` on that document, or added, inserted or removed one of its artboards through `artboards` + or `Artboard.remove()`, it is the artboard `getActiveArtboardIndex()` gives: the artboard the script chose while + that artboard exists, otherwise the same fallback as script coordinates and the view use (the saved active artboard + if it still exists, otherwise index 0). An undo inside the run that puts artboards back moves it with them. File > + Revert discards the script's stored choice. Otherwise the step uses the index of the document's active artboard as + the run started: after steps or commands such as `artboard.delete` delete artboards, the artboard now at that index, + or the last one past the end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to Artwork Bounds step act on those instead, as in the panel's playback. A step of a recorded `command.batch` step that names its `artboard` acts on that artboard, or the last one past the end, as `command.batch` gives it. VectorCraft's own rules: the action and its set are matched by their exact names, and a name that matches no action or more than @@ -8277,7 +8279,7 @@ and `layerRows`, the rows highlighted in the panel. `layer.selectAll {id}` and then `layer.setCurrent {id}`. - **Eye and lock**: `layer.setProps {ids?, visible?, locked?, name?}` for any rows, plus Layer Options for layers: `template` (also locks the layer and dims its images to 50% unless given), `printable`, `preview` (off: the layer - draws and is clicked in outline, Ctrl/Cmd-click its eye), `dimImages` (0–100, or false) and `color` (an index 0–26, + draws and is clicked in outline, Ctrl/Cmd-click its eye), `dimImages` (0–100, true for 50, or false) and `color` (an index 0–26, `#rrggbb` or a preset name; a hex color with an alpha part, `#rrggbbaa` or `#rgba`, is an error, and so it is in `layer.new` and `layer.newSublayer`). Several rows change in one undo step (a drag down the eye or lock column). When every row already has every option given, the call records no undo step. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 69a695c269..bfa548cb7f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1132,11 +1132,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). - `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.rs`. - - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; File > Revert discards that stored choice. `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. + - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). After the script adds, inserts or removes an artboard, playback acts on the active artboard at the index `getActiveArtboardIndex()` gives. After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; File > Revert discards that stored choice. `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - 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 warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`. From 5587dfdbcab758a7055fb78c6ecd580aadd9e6b2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:42:17 -0800 Subject: [PATCH 35/88] Screen print marks: pasted marks never use an ordinary layer of that name A pasted marks group went into an ordinary top-level layer named "Screen Print Marks" when the document had no tagged marks layer, and the paste failed when that layer was hidden or locked. The paste now makes a new marks layer instead. That layer is made apart from an ordinary layer of the same name pasted at the same time, and ordinary art pasted later skips the marks layer when matching layers by name. --- .../cmd/addons/color/screen_marks/tests.rs | 72 +++++++++++++++++++ crates/engine/src/cmd/edit.rs | 50 ++++++++----- docs/mcp.md | 2 +- 3 files changed, 106 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs index e1cc3aec9e..2659bb7a65 100644 --- a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs +++ b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs @@ -399,6 +399,78 @@ fn marks_pasted_into_another_document_go_into_its_marks_layer_not_a_layer_of_the assert_eq!(kids(&s, plain), Some((false, 0)), "the ordinary layer of the same name stays empty"); } +#[test] +fn marks_pasted_without_a_marks_layer_make_one_and_skip_a_layer_of_the_same_name() { + for props in [json!({}), json!({"visible": false}), json!({"locked": true})] { + let mut s = session(); + run(&mut s, json!({})); + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let plain = s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].clone(); + let mut set = props.clone(); + set["id"] = plain.clone(); + s.execute("layer.setProps", &set).unwrap(); + let plain = NodeId(plain.as_u64().unwrap()); + s.execute("edit.paste", &json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.artboards.len(), 2, "{props}"); + assert_eq!(doc.node(plain).and_then(|l| l.children().map(|k| k.len())), Some(0), "the ordinary layer stays empty: {props}"); + let made: Vec<_> = doc.layers.iter().filter(|l| l.id != plain && l.name.as_deref() == Some(LAYER_NAME)).collect(); + assert_eq!(made.len(), 1, "a marks layer is made: {props}"); + assert_eq!(made[0].children().map_or(0, |k| k.len()), 1, "the pasted marks go into it: {props}"); + let made = made[0].id.0; + let r = run(&mut s, json!({"artboard": 1, "size": 30})); + assert_eq!(r["layer"], json!(made), "the command uses the made layer: {props}"); + } +} + +#[test] +fn marks_and_art_from_a_layer_of_the_same_name_paste_into_separate_layers() { + let mut s = session(); + let r = run(&mut s, json!({})); + s.execute("layer.setProps", &json!({"id": r["layer"], "name": "Renamed Marks"})).unwrap(); + s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap(); + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + for paste in 1..=2 { + s.execute("edit.paste", &json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + let marks = super::layer_id(doc).expect("a marks layer is made"); + let named: Vec<_> = doc.layers.iter().filter(|l| l.name.as_deref() == Some(LAYER_NAME)).collect(); + assert_eq!(named.len(), 2, "the marks layer and the ordinary layer are separate: paste {paste}"); + for l in named { + let items = l.children().unwrap().len(); + assert_eq!(items, paste, "each paste adds one item to each layer: paste {paste}, marks {}", l.id == marks); + } + let ordinary = doc.layers.iter().find(|l| l.name.as_deref() == Some(LAYER_NAME) && l.id != marks).unwrap(); + assert!( + ordinary.children().unwrap().iter().all(|k| k.children().is_none()), + "only the rectangle goes into the ordinary layer: paste {paste}" + ); + } +} + +#[test] +fn art_pasted_again_skips_a_marks_layer_above_its_ordinary_layer() { + let mut s = session(); + run(&mut s, json!({})); + s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap(); + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let ordinary = NodeId(s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].as_u64().unwrap()); + for paste in 1..=2 { + s.execute("edit.paste", &json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + let marks = super::layer_id(doc).expect("a marks layer is made"); + assert_ne!(marks, ordinary); + let kids = |l: NodeId| doc.node(l).unwrap().children().unwrap().iter().map(|k| k.children().is_none()).collect::>(); + assert_eq!(kids(ordinary), vec![true; paste], "the rectangles go into the ordinary layer: paste {paste}"); + assert_eq!(kids(marks), vec![false; paste], "only marks go into the marks layer: paste {paste}"); + } +} + #[test] fn marks_lying_off_an_artboard_go_with_its_copy_made_by_moving_it() { let mut s = session(); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index ff90db1370..e00e6b5c31 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1685,6 +1685,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho .collect(); // The layers made for remembered layers the document lacks, by parent and name. let mut made = HashMap::new(); + // The marks layer made for screen print marks, kept apart from ordinary layers of its name. + let mut made_marks: HashMap<(Option, String), NodeId> = HashMap::new(); // Objects pasted into each parent so far (keeps their order in front and back pastes). let mut placed: BTreeMap, usize> = BTreeMap::new(); let mut new_ids = vec![]; @@ -1708,17 +1710,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho } let layer = match remembered.get(k) { Some(Some(Remembered::Layer(l))) => Some(*l), - Some(Some(Remembered::Make { parent, names })) => { - let last = make_layers(d, &mut made, *parent, names)?; - // The marks layer made again for a copy of an artboard's marks is the marks - // layer, so Create Screen Print Marks finds the copy there. - if let (true, None, [name], Some(l)) = (marks, parent, names.as_slice(), last) - && name == super::addons::SCREEN_MARKS_LAYER - { - super::addons::adopt_screen_marks_layer(d, l); - } - last - } + Some(Some(Remembered::Make { parent, names })) => make_remembered(d, &mut made, &mut made_marks, marks, *parent, names)?, _ => None, }; // In a clip group or a clipping layer the bottom child is the clipping path: art pasted @@ -1886,12 +1878,15 @@ fn remembered_layers(d: &Document, sources: &[Option], marks: &[boo /// layers match the most names, a shown and unlocked one first). The names left unmatched are /// made. A matched layer that is hidden or locked, or inside one that is, is an error. A screen /// print marks group (`marks`) goes into the document's marks layer, locked or hidden as it is, -/// when the document has one. +/// or into a new top-level marks layer when the document has none. fn remembered_layer(d: &Document, src: &SourceLayer, marks: bool, same_doc: bool) -> Result { - // A marks group goes into the document's marks layer when it has one, not into an ordinary - // layer of the same name. - if marks && let Some(l) = super::addons::screen_marks_layer(d) { - return Ok(Remembered::Layer(l)); + // A marks group goes into the document's marks layer, never into an ordinary layer of the + // same name. + if marks { + return Ok(match super::addons::screen_marks_layer(d) { + Some(l) => Remembered::Layer(l), + None => Remembered::Make { parent: None, names: vec![super::addons::SCREEN_MARKS_LAYER.to_string()] }, + }); } let held = |id: &NodeId| d.node(*id).is_some_and(|n| n.is_layer() && n.name.as_ref() == src.names.last()); let kept = if same_doc && src.ids.last().is_some_and(held) { @@ -1927,7 +1922,9 @@ fn named_chain(d: &Document, parent: Option, names: &[String]) -> (Optio None => Some(&d.layers), Some(p) => d.node(p).and_then(Node::children), }; - for l in siblings.into_iter().flatten().rev().filter(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str())) { + // Ordinary art never goes into the screen print marks layer by its name. + let marks_layer = parent.is_none().then(|| super::addons::screen_marks_layer(d)).flatten(); + for l in siblings.into_iter().flatten().rev().filter(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str()) && Some(l.id) != marks_layer) { let (end, n, open) = named_chain(d, Some(l.id), rest); let chain = (end, n + 1, open && l.visible && !l.locked); if (chain.1, chain.2) > (best.1, best.2) { @@ -1937,6 +1934,25 @@ fn named_chain(d: &Document, parent: Option, names: &[String]) -> (Optio best } +/// Makes the layers of a `Remembered::Make` for one pasted object. The marks layer for a screen +/// print marks group (`marks`) is made apart from ordinary layers of its name (`made_marks`) and +/// becomes the marks layer, so Create Screen Print Marks finds the copy there. +fn make_remembered( + d: &mut Document, + made: &mut HashMap<(Option, String), NodeId>, + made_marks: &mut HashMap<(Option, String), NodeId>, + marks: bool, + parent: Option, + names: &[String], +) -> Result> { + let is_marks = marks && parent.is_none() && matches!(names, [n] if n == super::addons::SCREEN_MARKS_LAYER); + let last = make_layers(d, if is_marks { made_marks } else { made }, parent, names)?; + if let (true, Some(l)) = (is_marks, last) { + super::addons::adopt_screen_marks_layer(d, l); + } + Ok(last) +} + /// Layers `names`, each inside the one before, the first under `parent` (none: on top); `made` /// keeps the ones a paste has made, by parent and name, so they are made once. The last one, or /// none when `names` is empty. diff --git a/docs/mcp.md b/docs/mcp.md index 6c072b3aad..a8a96400ca 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17923,7 +17923,7 @@ Another artboard's group lying on an artboard that is duplicated, Alt-dragged, c it is copied with that artboard when that one is copied too, and otherwise stays where it is. A group whose artboard was deleted is copied like other art. With art enabled, moves and cuts also take marks by their recorded owner, even when the marks lie outside every artboard, subject to `lockedAndHidden`. When the marks layer was -deleted while named "Screen Print Marks", pasting an artboard with its marks makes the layer again, and the command uses that layer. Marks +deleted, or the document pasted into has none, pasting an artboard with its marks makes a new marks layer named "Screen Print Marks" at the top level, and the command uses that layer. Marks outside the artboard (a negative `inset`) appear in an export or a print clipped to the artboard only as far as its bleed reaches. It is one undo step, and none when the marks come out the same (`changed: false`). The selection is kept. An unknown position or one named twice, a number out of range, an `ink` that is not [Registration] or a spot From 6144d0646ee9972d082d78b77b8f4c9dabdc8f96 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 22:45:25 -0800 Subject: [PATCH 36/88] Screen print marks: artboard move test checks explicit coordinates CI's test-lint step failed on the mirror rule: the assertion in moving_an_artboard_uses_marks_ownership_instead_of_containment called bounds on both sides of assert_eq!. The test now compares the moved marks with the starting coordinates shifted 500 pt, checks that the artboard itself moved 500 pt, and checks that the top marks stay above the moved artboard. --- crates/engine/src/cmd/addons/color/screen_marks/tests.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs index 2659bb7a65..0ee7e71a91 100644 --- a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs +++ b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs @@ -658,7 +658,13 @@ fn moving_an_artboard_uses_marks_ownership_instead_of_containment() { assert!(s.doc().unwrap().doc == before); } s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": true, "lockedAndHidden": true})).unwrap(); - assert_eq!(bounds(&node(&s, own.id.0)), bounds(&own) + vectorcraft_geom::Vec2::new(0.0, 500.0)); + let start = bounds(&own); + let moved = bounds(&node(&s, own.id.0)); + let expected = (start.x0, start.y0 + 500.0, start.x1, start.y1 + 500.0); + assert_eq!((moved.x0, moved.y0, moved.x1, moved.y1), expected, "the marks move 500 pt down with their artboard"); + let board = s.doc().unwrap().doc.artboards[0].rect; + assert_eq!(board.y0, before.artboards[0].rect.y0 + 500.0, "the artboard itself moved"); + assert!(moved.y1 < board.y0, "the top marks stay above their moved artboard"); assert!(node(&s, foreign.id.0) == foreign); assert_eq!(super::owner(&node(&s, own.id.0)), super::owner(&own)); s.execute("edit.undo", &json!({})).unwrap(); From 2e43ddd557fb3be58cf700f690e4e0ea4aed9261 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 13:04:54 -0800 Subject: [PATCH 37/88] Type: an unfinished Character value stays with the text it was typed for A value typed into a number field of the Character panel or of the Properties panel's Character section and not yet committed (for example "3+" in Font size, Leading, Tracking or Kerning) stayed in the field when other text with the same value was selected, and Enter then committed it to that text. The controls now pass an edit target to CharacterControls::edit_target: the document, its File > Revert and Undo or Redo counts, and the text the change goes to, which is the Type tool's range or story (by its own offsets, so a caret position counts for Kerning) or else the selected stories. When the target changes, every number field of the rows drops the unfinished value. The craft-libs pin moves to the commit that adds CharacterControls::edit_target. --- Cargo.lock | 176 ++++++------- Cargo.toml | 78 +++--- apps/vectorcraft-web/Cargo.toml | 2 +- crates/doc/src/selection.rs | 2 +- crates/ui-egui/src/panels/character.rs | 22 +- crates/ui-egui/src/panels/character/tests.rs | 256 +++++++++++++++++++ xtask/src/pdf_deps.rs | 2 +- 7 files changed, 406 insertions(+), 132 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 75c87011b4..297380c1cd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1231,7 +1231,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-automation", "craft-behavior", @@ -1272,7 +1272,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "crc32fast", "flate2", @@ -1283,7 +1283,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1295,7 +1295,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "rustix 1.1.6", ] @@ -1303,7 +1303,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1328,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1346,7 +1346,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-docpath", @@ -1364,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "crc32fast", "flate2", @@ -1373,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "egui", ] @@ -1381,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "md-5", "rayon", @@ -1390,12 +1390,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-cms", @@ -1415,7 +1415,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-control-protocol", "craft-platform", @@ -1426,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1436,7 +1436,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "rayon", ] @@ -1444,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1470,7 +1470,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "blake3", "craft-ecproj-format", @@ -1486,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "serde", ] @@ -1494,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1513,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-codepage", "encoding_rs", @@ -1525,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "serde", "serde_json", @@ -1535,12 +1535,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1555,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1574,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1583,7 +1583,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "cap-primitives", "craft-atomic", @@ -1606,12 +1606,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "gif", ] @@ -1619,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "flate2", ] @@ -1627,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1640,7 +1640,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1670,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-dds", "craft-jpeg", @@ -1697,7 +1697,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1715,7 +1715,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "thiserror 2.0.21", ] @@ -1723,7 +1723,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1734,7 +1734,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-host", "craft-i18n", @@ -1749,7 +1749,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-i18n", @@ -1763,7 +1763,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-host", @@ -1781,7 +1781,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1793,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "encoding_rs", "image", @@ -1804,7 +1804,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "chrono", "craft-codepage", @@ -1814,7 +1814,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "uds_windows", "winsafe", @@ -1823,7 +1823,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-keymap", @@ -1839,7 +1839,7 @@ dependencies = [ [[package]] name = "craft-pbr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-texture", "thiserror 2.0.21", @@ -1848,7 +1848,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "flate2", "serde", @@ -1859,7 +1859,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1871,7 +1871,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "async-channel", "async-io", @@ -1904,7 +1904,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1913,7 +1913,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-host", @@ -1937,7 +1937,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1948,7 +1948,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-eps", "flate2", @@ -1962,7 +1962,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "encoding_rs", "flate2", @@ -1973,7 +1973,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "dispatch2", "egui", @@ -1986,7 +1986,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -2005,7 +2005,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-atomic", "craft-host", @@ -2022,7 +2022,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "fax", "hayro-ccitt", @@ -2033,7 +2033,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2054,7 +2054,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-keymap", @@ -2066,7 +2066,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2091,7 +2091,7 @@ dependencies = [ [[package]] name = "craft-texture" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "thiserror 2.0.21", ] @@ -2099,7 +2099,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2114,7 +2114,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-atomic", "craft-behavior", @@ -2129,7 +2129,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "serde", "thiserror 2.0.21", @@ -2139,7 +2139,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "serde", "thiserror 2.0.21", @@ -2148,7 +2148,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-keymap", @@ -2163,12 +2163,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2182,7 +2182,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -2199,7 +2199,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "accesskit", "craft-behavior", @@ -2237,7 +2237,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2248,7 +2248,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-host", @@ -2266,7 +2266,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-host", @@ -2287,7 +2287,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-host", @@ -2308,7 +2308,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-behavior", "craft-host", @@ -2327,7 +2327,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "base64 0.22.1", "chrono", @@ -2359,7 +2359,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "flate2", "serde", @@ -2370,7 +2370,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2380,7 +2380,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "js-sys", "serde_json", @@ -2391,7 +2391,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "winsafe", ] @@ -2399,7 +2399,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "craft-appkit", "craft-atomic", @@ -2431,7 +2431,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3790,7 +3790,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3799,7 +3799,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3817,7 +3817,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3835,12 +3835,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "flate2", "hayro-ccitt", @@ -4823,7 +4823,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4980,7 +4980,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=53c27ce2422e73784f15ca93a43dd0a32fc33280#53c27ce2422e73784f15ca93a43dd0a32fc33280" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index 7dab0c8895..60055c372a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,53 +10,53 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } # 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } # The metallic-roughness BRDF and environment light the 3D effects' Roughness and Metallic shade with. -craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -196,13 +196,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } emath = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } epaint = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 70aae32f73..250cbbfe65 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "53c27ce2422e73784f15ca93a43dd0a32fc33280", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index 02c4391921..ead201ffab 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -78,7 +78,7 @@ pub struct Selection { } /// See [`Selection::symbol_part`]. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct SymbolPart { /// The symbol instance. pub instance: NodeId, diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 677eec516a..7dde6b8938 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -316,7 +316,7 @@ fn run_format_after_typing(app: &mut VectorcraftApp, mut p: Value, editing: Opti app.run("text.setRangeStyle", p) } -#[derive(PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Hash)] pub(crate) enum FormatTarget { Objects(Vec, Option), Story(Vec), @@ -338,6 +338,22 @@ pub(crate) fn format_target_kept(app: &mut VectorcraftApp) -> Result Option<(u64, u64, u64, FormatTarget)> { + let st = app.session.active()?; + let o = app.session.tool_options(); + let offset = |k: &str| o.get(k).and_then(Value::as_u64).map_or(0, |v| v as usize); + let editing = text_editing(app).map(|(id, _, _)| (id, offset("start"), offset("end"))); + Some((st.uid, st.reverts, st.history_restores, format_target(app, editing))) +} + /// Apply a settings dialog to its opening text only. Compare before keeping typing so a /// refused confirmation on different text does not commit that text's in-progress edit. pub(crate) fn run_format_at_target(app: &mut VectorcraftApp, p: Value, target: &FormatTarget) -> Result { @@ -1230,6 +1246,7 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow let sets = font_menu::family_sets(hold.document.as_deref(), &hold.recently_added); let sample = font_menu::sample_text(app); let unit = type_unit(app); + let target = character_target(app); let mut source = FontPickerSource::new(catalog) .settings(Bind::bound(&mut hold.settings)) .filters(Bind::bound(&mut hold.filters)) @@ -1244,7 +1261,8 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow .rows(rows) .font_picker(source) .axes_layout(AxesLayout::Button) - .anti_alias_methods(&ANTI_ALIAS_METHODS); + .anti_alias_methods(&ANTI_ALIAS_METHODS) + .edit_target(target); if let Some(languages) = &languages { controls = controls.languages(languages); } diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index d1f6be332e..835e77325a 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -433,6 +433,262 @@ fn highlight_commands_ask_the_framework_to_focus_the_field_by_key() { } } +/// A number field of the character controls, by name, and the attribute of a character it sets. +type CharacterField = (&'static str, fn(&CharStyle) -> f64); + +/// The Character panel's number fields with its options and the East Asian and Middle Eastern +/// options shown. Properties shows the first four. +const CHARACTER_FIELDS: [CharacterField; 13] = [ + ("Font size", |s| s.size), + ("Leading", |s| s.leading.unwrap_or(0.0)), + ("Kerning", |s| s.kerning.unwrap_or(0.0)), + ("Tracking", |s| s.tracking), + ("Vertical scale", |s| s.v_scale), + ("Horizontal scale", |s| s.h_scale), + ("Baseline shift", |s| s.baseline_shift), + ("Rotation", |s| s.rotation), + ("Insert Aki Left", |s| s.aki_left), + ("Insert Aki Right", |s| s.aki_right), + ("Tsume", |s| s.tsume), + ("Horizontal Diacritic Position", |s| s.diacritic_horizontal), + ("Vertical Diacritic Position", |s| s.diacritic_vertical), +]; + +/// A panel that shows the character controls: its name, how it draws and the fields it shows. +type CharacterDraw = (&'static str, fn(&mut VectorcraftApp, &mut egui::Ui), &'static [CharacterField]); + +/// The Character panel and Properties with the fields each shows. +fn character_draws() -> [CharacterDraw; 2] { + [("Character", show, &CHARACTER_FIELDS), ("Properties", super::super::properties::show, &CHARACTER_FIELDS[..4])] +} + +/// A document with two text objects, `Ab` and `Cd`, at 12 pt with a leading of 20 pt and a tracking +/// of 10, and the East Asian and Middle Eastern options shown. +fn two_styled_texts() -> (VectorcraftApp, u64, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.show_east_asian_options = true; + app.session.prefs.show_indic_options = true; + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let a = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("text.create", json!({"x": 20, "y": 140, "text": "Cd", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("text.setStyle", json!({"ids": [a, b], "leading": 20, "tracking": 10})).unwrap(); + (app, a, b) +} + +/// Types `3+` into the field `name` without committing it. +fn type_unfinished(p: &mut crate::tests::panel_harness::Panel, name: &str) { + p.focus(name); + p.key(egui::Key::A, egui::Modifiers::COMMAND); + p.type_text("3+"); +} + +/// Draws a frame, then types `1` and Enter into the focused field. +fn finish_typing(p: &mut crate::tests::panel_harness::Panel) { + p.frame(); + p.type_text("1"); + p.key(egui::Key::Enter, egui::Modifiers::NONE); +} + +/// The attribute `read` of each run of the text `id`. +fn run_values(app: &VectorcraftApp, id: u64, read: fn(&CharStyle) -> f64) -> Vec<(String, f64)> { + block_text(app, NodeId(id)).runs.iter().map(|r| (r.text.clone(), read(&r.style))).collect() +} + +/// The number fields of the Character panel and Properties keep a value typed and not yet committed +/// while the text it was typed for stays selected, and drop it when other text with the same value +/// is selected. +#[test] +fn an_unfinished_character_value_does_not_reach_other_selected_text() { + use crate::tests::panel_harness::Panel; + for (panel, draw, fields) in character_draws() { + for &(name, read) in fields { + let (mut app, a, b) = two_styled_texts(); + let before = run_values(&app, a, read); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut p = Panel::new(app, draw); + type_unfinished(&mut p, name); + finish_typing(&mut p); + assert_eq!(run_values(&p.app(), a, read), [("Ab".to_string(), 4.0)], "{panel} {name}: an unchanged selection keeps 3+"); + p.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(run_values(&p.app(), a, read), before, "{panel} {name}: undone"); + + type_unfinished(&mut p, name); + p.app().run("select.set", json!({"ids": [b]})).unwrap(); + finish_typing(&mut p); + let app = p.app(); + assert_eq!( + (run_values(&app, a, read), run_values(&app, b, read)), + (before, vec![("Cd".to_string(), 1.0)]), + "{panel} {name}: b takes 1, not 3+1" + ); + } + } +} + +/// While the Type tool edits text, a value typed into the Character panel belongs to the selected +/// characters: another range in the same text drops it. +#[test] +fn an_unfinished_character_value_does_not_reach_another_text_range() { + use crate::tests::panel_harness::Panel; + for (panel, draw, _) in character_draws() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Abcd", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 0, "caret": 2})); + let mut p = Panel::new(app, draw); + type_unfinished(&mut p, "Tracking"); + p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 2, "caret": 4})); + finish_typing(&mut p); + let want = vec![("Ab".to_string(), 0.0), ("cd".to_string(), 1.0)]; + assert_eq!(run_values(&p.app(), id, |s| s.tracking), want, "{panel}: the second range takes 1, not 3+1"); + } +} + +/// At a caret the Kerning field sets the pair at the caret, so a value typed there does not reach +/// the pair at another caret position in the same text, though both pairs have the same kerning. +#[test] +fn an_unfinished_kerning_does_not_reach_another_caret_position() { + use crate::tests::panel_harness::Panel; + for (panel, draw, _) in character_draws() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Abcd", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("text.setRangeStyle", json!({"id": id, "kerning": 10})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 1, "caret": 1})); + let mut p = Panel::new(app, draw); + type_unfinished(&mut p, "Kerning"); + p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 3, "caret": 3})); + finish_typing(&mut p); + let kernings: Vec = run_values(&p.app(), id, |s| s.kerning.unwrap_or(0.0)).into_iter().map(|(_, k)| k).collect(); + assert!(kernings.contains(&1.0) && !kernings.contains(&4.0), "{panel}: the pair at the second caret takes 1, not 3+1: {kernings:?}"); + } +} + +/// Another document whose text has the same id and tracking drops the value. +#[test] +fn an_unfinished_character_value_does_not_reach_another_document() { + use crate::tests::panel_harness::Panel; + let (mut app, a, _) = two_styled_texts(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let other = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(other, a, "both documents' texts have the same id"); + app.run("text.setStyle", json!({"ids": [a], "tracking": 10})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut p = Panel::new(app, show); + type_unfinished(&mut p, "Tracking"); + p.app().run("document.activate", json!({"index": 1})).unwrap(); + finish_typing(&mut p); + let tracking = |s: &CharStyle| s.tracking; + let second = run_values(&p.app(), a, tracking); + p.app().run("document.activate", json!({"index": 0})).unwrap(); + let first = run_values(&p.app(), a, tracking); + assert_eq!((first, second), (vec![("Ab".to_string(), 10.0)], vec![("Ab".to_string(), 1.0)]), "the other document takes 1"); +} + +/// File › Revert drops the value, though the restored text has the same id and tracking. +#[test] +fn an_unfinished_character_value_is_dropped_by_file_revert() { + use crate::tests::panel_harness::Panel; + let (mut app, a, _) = two_styled_texts(); + let dir = vectorcraft_testkit::TempDir::new("character-value-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Type.vectorcraft")})).unwrap(); + // An unsaved change for Revert to undo, leaving the text as saved. + app.run("shape.rectangle", json!({"x": 100, "y": 200, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut p = Panel::new(app, show); + type_unfinished(&mut p, "Tracking"); + p.app().run("file.revert", json!({"confirmed": true})).unwrap(); + p.app().run("select.set", json!({"ids": [a]})).unwrap(); + finish_typing(&mut p); + assert_eq!(run_values(&p.app(), a, |s| s.tracking), [("Ab".to_string(), 1.0)], "Revert drops the unfinished value"); +} + +/// Undo drops the value, though the text it takes away and the text made and selected after it +/// have the same id and tracking. +#[test] +fn an_unfinished_character_value_is_dropped_by_undo() { + use crate::tests::panel_harness::Panel; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let a = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let mut p = Panel::new(app, show); + type_unfinished(&mut p, "Tracking"); + p.app().run("edit.undo", json!({})).unwrap(); + let b = p.app().run("text.create", json!({"x": 20, "y": 40, "text": "Cd", "size": 12})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(b, a, "the new text has the undone text's id"); + p.app().run("select.set", json!({"ids": [b]})).unwrap(); + finish_typing(&mut p); + assert_eq!(run_values(&p.app(), b, |s| s.tracking), [("Cd".to_string(), 1.0)], "Undo drops the unfinished value"); +} + +/// With Real-time Drawing off, a Type tool range that reaches into typing not applied yet is +/// another range than the applied text it starts in. +#[test] +fn an_unfinished_character_value_does_not_reach_a_range_with_unapplied_typing() { + use crate::tests::panel_harness::Panel; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.select_tool("type"); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + app.session.set_tool_option("select", &json!({"start": 2, "end": 2})); + let mut app = crate::testing::windowed(app); + let ctx = app.ui_ctx.clone().unwrap(); + // The keymap builds in the first pass. + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![egui::Event::Text("Cd".into())]); + assert_eq!(app.session.tool_options()["typing"], json!(true)); + let tracking = |s: &CharStyle| s.tracking; + assert_eq!(run_values(&app, id, tracking), [("Ab".to_string(), 0.0)], "the typing is not applied yet"); + app.session.set_tool_option("select", &json!({"start": 0, "end": 2})); + let mut p = Panel::new(app, show); + type_unfinished(&mut p, "Tracking"); + p.app().session.set_tool_option("select", &json!({"start": 0, "end": 4})); + finish_typing(&mut p); + assert_eq!(run_values(&p.app(), id, tracking), [("AbCd".to_string(), 1.0)], "the longer range takes 1, not 3+1"); +} + +/// Settling unapplied typing keeps an unfinished Character value for the Select All range. +#[test] +fn an_unfinished_character_value_survives_select_all_typing_settling() { + use crate::tests::panel_harness::Panel; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.select_tool("type"); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + app.session.set_tool_option("select", &json!({"start": 2, "end": 2})); + let mut app = crate::testing::windowed(app); + let ctx = app.ui_ctx.clone().unwrap(); + // The keymap builds in the first pass. + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![egui::Event::Text("Cd".into())]); + assert_eq!(app.session.tool_options()["typing"], json!(true)); + let tracking = |s: &CharStyle| s.tracking; + assert_eq!(run_values(&app, id, tracking), [("Ab".to_string(), 0.0)], "the typing is not applied yet"); + app.run("select.all", json!({})).unwrap(); + assert_eq!(app.session.tool_options()["typing"], json!(true)); + let mut p = Panel::new(app, show); + type_unfinished(&mut p, "Tracking"); + end_typing(&mut p.app()); + assert_eq!(run_values(&p.app(), id, tracking), [("AbCd".to_string(), 0.0)], "the typing is applied"); + finish_typing(&mut p); + assert_eq!(run_values(&p.app(), id, tracking), [("AbCd".to_string(), 4.0)], "settling the typing keeps 3+"); +} + /// The slider list and its gestures are the framework's. What the app decides: which axes the selection /// shares, that a change carries only the axes that moved (so a mixed axis stays as it is), the /// command (the object, or the Type tool's range) and that Reset Panel leaves the settings. diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 542a3e8c41..be756f03de 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6"; +const REV: &str = "53c27ce2422e73784f15ca93a43dd0a32fc33280"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From e91a7fe0fe56cc2b8ed24a41b0945ef4b360f921 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 01:17:12 -0800 Subject: [PATCH 38/88] Screen print marks: marks copied from an unnamed layer paste back into the marks layer A layer without a name gives a copied object no source layer, so Paste Remembers Layers returned early and a marks group copied with an artboard from an unnamed marks layer went into the ordinary paste layer. The marks check now runs before that return; ordinary art with no source layer still pastes where it did. --- .../cmd/addons/color/screen_marks/tests.rs | 14 ++++++++++++++ crates/engine/src/cmd/edit.rs | 19 +++++++++++++++---- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs index 0ee7e71a91..457b0ec11d 100644 --- a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs +++ b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs @@ -383,6 +383,20 @@ fn marks_copied_with_an_artboard_paste_back_into_their_locked_layer() { assert_eq!(marks(&s), Some((true, 2)), "marking the pasted artboard replaces the pasted copy"); } +#[test] +fn marks_copied_from_an_unnamed_marks_layer_paste_back_into_it() { + let mut s = session(); + let r = run(&mut s, json!({})); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let st = s.doc_mut().unwrap(); + std::sync::Arc::make_mut(&mut st.doc).node_mut(layer).unwrap().name = None; + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let marks = |s: &Session| s.doc().unwrap().doc.node(layer).map(|l| (l.locked, l.children().map_or(0, |k| k.len()))); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 2); + assert_eq!(marks(&s), Some((true, 2)), "the pasted marks go into the unnamed marks layer, which stays locked"); +} + #[test] fn marks_pasted_into_another_document_go_into_its_marks_layer_not_a_layer_of_the_same_name() { let mut s = session(); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 3fcc3179b7..6879b8a327 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1876,6 +1876,11 @@ fn remembered_layers(d: &Document, sources: &[Option], marks: &[boo .iter() .enumerate() .map(|(k, src)| { + // A marks group goes into the marks layer even when the layer it was copied from has + // no name. + if marks.get(k).copied().unwrap_or(false) && src.is_none() { + return Ok(Some(marks_layer_target(d))); + } let Some(src) = src else { return Ok(None) }; let key = (src, marks.get(k).copied().unwrap_or(false)); if let Some(r) = found.get(&key) { @@ -1900,10 +1905,7 @@ fn remembered_layer(d: &Document, src: &SourceLayer, marks: bool, same_doc: bool // A marks group goes into the document's marks layer, never into an ordinary layer of the // same name. if marks { - return Ok(match super::addons::screen_marks_layer(d) { - Some(l) => Remembered::Layer(l), - None => Remembered::Make { parent: None, names: vec![super::addons::SCREEN_MARKS_LAYER.to_string()] }, - }); + return Ok(marks_layer_target(d)); } let held = |id: &NodeId| d.node(*id).is_some_and(|n| n.is_layer() && n.name.as_ref() == src.names.last()); let kept = if same_doc && src.ids.last().is_some_and(held) { @@ -1929,6 +1931,15 @@ fn remembered_layer(d: &Document, src: &SourceLayer, marks: bool, same_doc: bool }) } +/// Where a screen print marks group goes: the document's marks layer, locked or hidden as it is, +/// or a new top-level marks layer when the document has none. +fn marks_layer_target(d: &Document) -> Remembered { + match super::addons::screen_marks_layer(d) { + Some(l) => Remembered::Layer(l), + None => Remembered::Make { parent: None, names: vec![super::addons::SCREEN_MARKS_LAYER.to_string()] }, + } +} + /// The deepest chain of layers inside `parent` (none: the top level) named `names` one inside the /// other: its last layer (`parent` when none matches), how many names it matched and whether all /// its layers are shown and unlocked. Of chains as deep, the topmost shown and unlocked one wins. From 570a7bfe6f067a410eb730d600cc41945d8fa667 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 01:42:03 -0800 Subject: [PATCH 39/88] Scripts: the active artboard stays active when the script adds or removes one before it Adding, inserting or removing an artboard from a script now keeps the artboard that was active before the change by its id, as setActiveArtboardIndex does, also when the script never chose one. Before, with no artboard chosen, an artboard inserted at index 0 became the active one, so later app.doScript steps acted on it. A stored id of a removed artboard no longer stops the fallback from being kept, and a document the run made is reported when its active artboard moves. The script run summary in docs/target-app-parity.md now says that showing or hiding a perspective grid and its active plane add no undo step. --- crates/engine/src/script/dom/layers.rs | 38 +++++++++++++++++++++++ crates/engine/src/tests/script_actions.rs | 5 ++- crates/engine/src/tests/script_dom.rs | 32 +++++++++++++++++++ docs/mcp.md | 6 ++-- docs/target-app-parity.md | 4 +-- 5 files changed, 80 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 341505da5f..0d6c200c27 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -1365,7 +1365,9 @@ fn board_set_safe_areas(h: &Host, a: &[Data]) -> Answer { fn board_remove(h: &Host, a: &[Data]) -> Answer { let (b, i) = this_board(h, a)?; + let active = active_board_id(h, b.doc); on_doc(h, b.doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?; + keep_active_board(h, b.doc.uid, active); follow_active_board(h, b.doc.uid); Ok(Data::Undefined) } @@ -1467,6 +1469,7 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { if len >= max { return Err(HostError::Range(format!("a document has at most {max} artboards"))); } + let active = active_board_id(h, doc); let id = super::atomically(h, |h| { on_doc(h, doc.uid, true, |h| { let (_, made) = command_value(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; @@ -1483,6 +1486,7 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into())) }) })?; + keep_active_board(h, doc.uid, active); follow_active_board(h, doc.uid); Ok(board_ref(h, doc.uid, id)) } @@ -1505,11 +1509,45 @@ fn boards_remove(h: &Host, a: &[Data]) -> Answer { let doc = boards_doc(h, a)?; let len = with_doc(h, doc, |_, st| st.doc.artboards.len()); let i = board_index_arg(arg(a, 1), len, "index")?; + let active = active_board_id(h, doc); on_doc(h, doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?; + keep_active_board(h, doc.uid, active); follow_active_board(h, doc.uid); Ok(Data::Undefined) } +/// The id and index of the artboard that is active in `doc` now, chosen or only the fallback. +fn active_board_id(h: &Host, doc: Doc) -> Option<(u32, usize)> { + with_doc(h, doc, |_, st| { + let i = active_artboard(st); + st.doc.artboards.get(i).map(|ab| (ab.id, i)) + }) +} + +/// Keeps artboard `id` active in document `uid` by its id when it is still there, as +/// `setActiveArtboardIndex` does, so an artboard added or removed before it moves its index +/// instead of making another artboard the active one. +/// A stored id of an artboard that is gone is replaced as well. In a document made during the run, +/// the index the artboard had before the change is recorded for the run's report, as the first +/// `setActiveArtboardIndex` records it. +fn keep_active_board(h: &Host, uid: u64, active: Option<(u32, usize)>) { + let Some((id, index)) = active else { return }; + { + let mut s = h.session.borrow_mut(); + let Some(st) = s.document_mut(uid) else { return }; + if !st.doc.artboards.iter().any(|ab| ab.id == id) { + return; + } + st.active_artboard = Some(id); + } + if !h.dom.boards_at_start.iter().any(|(u, _)| *u == uid) { + let mut made = h.dom.boards_chosen_in_new.borrow_mut(); + if !made.iter().any(|(u, _)| *u == uid) { + made.push((uid, index)); + } + } +} + /// After the script adds or removes an artboard in document `uid`, the steps `app.doScript` plays /// act on the document's active artboard by id, at the index the run's report gives it, as after /// `setActiveArtboardIndex`, until the document is reverted. diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index f7d78b4392..cf2010e7a1 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -340,7 +340,8 @@ fn steps_discard_the_chosen_artboard_after_revert() { /// An artboard the script removes or inserts moves the active artboard's index; its played steps act /// on the active artboard at the index `getActiveArtboardIndex()` gives, as the run's report does, -/// also after an undo puts the artboards back. +/// also after an undo puts the artboards back. The artboard that was active stays active, also when +/// none was chosen before the run. #[test] fn steps_follow_the_active_artboard_after_the_script_removes_or_inserts_one_before_it() { let setup = |active: Option| { @@ -365,12 +366,14 @@ fn steps_follow_the_active_artboard_after_the_script_removes_or_inserts_one_befo ]; for (active, edit) in cases { let (mut s, id) = setup(active); + let was = s.active().unwrap().doc.artboards[active.unwrap_or(0)].rect; let source = format!("var A = app.activeDocument.artboards; {edit} vc.log(A.getActiveArtboardIndex()); app.doScript('Align', 'Set');"); let out = log_with(&mut s, &source, &actions); let index = out[0].as_u64().unwrap() as usize; let board = s.active().unwrap().doc.artboards[index].rect; let left = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0; assert_eq!(left, board.x0, "{active:?} {edit}"); + assert_eq!(board, was, "the artboard active before the edit stays active: {active:?} {edit}"); } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 020a49028c..7c7b07a101 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -4577,6 +4577,38 @@ fn a_new_documents_chosen_artboard_is_reported_after_an_insert_before_it() { assert!(list.iter().any(|e| e["artboard"] == json!(1)), "{r}"); } +/// Without a chosen artboard, an artboard inserted before the default active one moves it to the +/// next index, in an open document and in one the run makes, and the report gives that index. +#[test] +fn inserting_before_the_default_active_artboard_keeps_it() { + let (mut s, _, _) = doc(); + let first = s.active().unwrap().doc.artboards[0].id; + let r = run(&mut s, "var A = app.activeDocument.artboards; A.insert([800, 300, 900, 100], 0); vc.log(A.getActiveArtboardIndex());").unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + assert_eq!(s.active().unwrap().active_artboard, Some(first)); + let r = run(&mut s, "var d = app.documents.add(); var A = d.artboards; A.insert([800, 300, 900, 100], 0); vc.log(A.getActiveArtboardIndex());") + .unwrap(); + assert_eq!(r["log"], json!([1])); + let list = r["activeArtboards"].as_array().cloned().unwrap_or_default(); + assert!(list.iter().any(|e| e["artboard"] == json!(1)), "{r}"); +} + +/// After the chosen artboard is removed, the artboard active in its place stays active when one is +/// inserted before it. +#[test] +fn inserting_before_the_fallback_after_the_chosen_artboard_is_removed_keeps_it() { + let (mut s, _, _) = doc(); + let r = run( + &mut s, + "var A = app.activeDocument.artboards; A.add([800, 300, 900, 100]); A.setActiveArtboardIndex(1); A.remove(1);\ + var was = A[A.getActiveArtboardIndex()].name; A.insert([1000, 300, 1100, 100], 0);\ + vc.log(A[A.getActiveArtboardIndex()].name == was);", + ) + .unwrap(); + assert_eq!(r["log"], json!([true]), "{r}"); +} + /// `artboards.insert` gives nothing back; `artboards.add` gives the new artboard. #[test] fn artboards_insert_returns_nothing() { diff --git a/docs/mcp.md b/docs/mcp.md index c1f823f1a4..d5aa0d0835 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3362,8 +3362,10 @@ through `$`: change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the run leaves it). The report also lists a document whose active artboard has another index when the run ends because artboards were inserted, removed or reordered before it, and a document the run opened in which an artboard was - chosen. The chosen artboard stays active when another is inserted before it, even if it was already the active - one. An index outside the list throws a + chosen, or whose active artboard ends at another index after artboards were added, inserted or removed before it. + The chosen artboard stays active when another is inserted before it, even if it was already the active + one. When the script adds, inserts or removes an artboard without having chosen one, the artboard active before + the change stays active. An index outside the list throws a `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and `GroupItems.createFromFile` throw an error that says they are not available yet. `GroupItems.createFromFile` on a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bfd542a01c..0cca5398e4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1114,7 +1114,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Variables: a type object holds one text variable. `variable.bind` and Make Text Dynamic refuse a second one and name the text variable the object has; a visibility variable can still share the object, and a document saved with two text variables on one object opens with both. - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. + - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document; showing or hiding a perspective grid and choosing its active plane change only the view and add no undo step. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: `Document.rasterize` replaces page items with an embedded image and `Document.imageCapture` writes a PNG of the art or of an area of the page, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterizeOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/ImageCaptureOptions/ describe; `object.rasterize` takes `ids` and `clipBounds` for them (`docs/mcp.md`). `Document.windowCapture` is not there yet. `crates/engine/src/tests/script_raster_capture.rs`. - Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. `crates/engine/src/tests/script_dom_images.rs`. @@ -1138,7 +1138,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.rs`. - - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). After the script adds, inserts or removes an artboard, playback acts on the active artboard at the index `getActiveArtboardIndex()` gives. After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; once a script calls `setActiveArtboardIndex` on a document or adds, inserts or removes one of its artboards, untargeted paste and Fit to Artwork Bounds use the active artboard instead of the Artboard tool's selection at the start of the run; File > Revert discards that stored choice. `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. + - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). After the script adds, inserts or removes an artboard, the artboard active before the change stays active, also when the script never chose one, and playback acts on it at the index `getActiveArtboardIndex()` gives. After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; once a script calls `setActiveArtboardIndex` on a document or adds, inserts or removes one of its artboards, untargeted paste and Fit to Artwork Bounds use the active artboard instead of the Artboard tool's selection at the start of the run; File > Revert discards that stored choice. `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. A line's menu copies that line or the selected range. `crates/engine/src/tests/script_console.rs`. - 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 warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`. From cccd31c3aa2a3f1cf124172caf567a3e12332d56 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 02:11:55 -0800 Subject: [PATCH 40/88] Clear: remove a compound path emptied through an emptied inner one Clear and the scripting tracing guard checked only the direct compound parents of the removed objects, once each. A compound path whose members were a removed path and an inner compound path the same clear emptied stayed behind empty, or went, depending on the order of the ids, and the guard could miss it. - emptied_compounds walks up through compound ancestors until nothing changes and returns the emptied compound paths sorted by id; Clear and clearing_makes_tracing both use it. - Clear with direct-selected anchors checks the compound path above each one it removes again. --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/edit.rs | 36 +++++++++++++------ crates/engine/src/cmd/edit/tests.rs | 56 +++++++++++++++++++++++++++++ crates/engine/src/cmd/path.rs | 6 +++- crates/engine/src/script/dom.rs | 10 ++---- 5 files changed, 90 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 586deb604c..652f3e39b5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -885,7 +885,7 @@ pub use colorcmds::{Backdrop, contrast_measure, contrast_pick_backdrop}; /// write a resolution and a number of bytes. pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number}; pub use docmenu::guide_indexes; -pub(crate) use edit::{Unrecorded, artboard_tool_picks, settle_interaction, typing_in_progress}; +pub(crate) use edit::{Unrecorded, artboard_tool_picks, emptied_compounds, settle_interaction, typing_in_progress}; 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. diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 55726c31c9..ea5f688b44 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1363,17 +1363,12 @@ fn clear(s: &mut Session, p: &Value) -> Result { } s.edit("Clear", |d, sel| { let clipped = clipped_ancestors(d, ids.iter().copied()); - let parents: Vec<_> = if keep_empty { - Vec::new() - } else { - ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect() - }; + let emptied = if keep_empty { Vec::new() } else { emptied_compounds(d, &ids) }; + // A compound path inside another emptied one leaves with it. + let outer: Vec = + emptied.iter().copied().filter(|p| !d.ancestry(*p).unwrap_or_default().iter().rev().skip(1).any(|a| emptied.binary_search(a).is_ok())).collect(); d.remove_many(&ids)?; - for p in parents { - if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) { - d.remove(p)?; - } - } + d.remove_many(&outer)?; if with_guides { let gone = sel.guides.clone(); d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id))); @@ -1390,6 +1385,27 @@ fn clear(s: &mut Session, p: &Value) -> Result { ok() } +/// The compound paths that deleting the objects `ids` together leaves with no members, sorted by +/// id: a compound path counts when each of its members is deleted or is such a compound path, so +/// a compound path holding only an emptied inner one is emptied too. +pub(crate) fn emptied_compounds(d: &Document, ids: &[NodeId]) -> Vec { + let mut gone: BTreeSet = ids.iter().copied().collect(); + let mut emptied = BTreeSet::new(); + loop { + let parents: BTreeSet = gone.iter().filter_map(|i| d.parent_of(*i)).filter(|p| !gone.contains(p)).collect(); + let found: BTreeSet = parents + .into_iter() + .filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))) + .filter(|p| d.children(Some(*p)).is_some_and(|k| k.iter().all(|n| gone.contains(&n.id)))) + .collect(); + if found.is_empty() { + return emptied.into_iter().collect(); + } + gone.extend(found.iter().copied()); + emptied.extend(found); + } +} + /// Does Clear remove direct-selected anchors without opening their paths (`keepJoined` param, else /// General › Delete Removes Anchor Points and Keeps Paths Joined)? Noted in the journal, so a /// replay removes them the same way whatever the preference is at the time. A saved step without `keepJoined` diff --git a/crates/engine/src/cmd/edit/tests.rs b/crates/engine/src/cmd/edit/tests.rs index 7e0471f0f5..8764d313b8 100644 --- a/crates/engine/src/cmd/edit/tests.rs +++ b/crates/engine/src/cmd/edit/tests.rs @@ -400,3 +400,59 @@ fn selected_roots_are_found_once_for_each_document_and_selection() { selected_roots(&s).unwrap(); assert_eq!(roots_found() - before, 2, "an edit finds the roots once again"); } + +/// Clear removes a compound path whose members are cleared paths and a compound path the clear +/// empties, whichever order the ids come in, and the tracing guard's set counts both as deleted. +#[test] +fn clear_removes_a_compound_path_emptied_through_an_emptied_inner_one() { + for reversed in [false, true] { + let mut s = new_doc(); + let outer_paths = [(); 2].map(|()| rect(&mut s)); + let (outer, outer_members) = compound(&mut s, &outer_paths); + let inner_paths = [(); 2].map(|()| rect(&mut s)); + let (inner, inner_members) = compound(&mut s, &inner_paths); + s.edit("Nest", |d, _| { + let taken = d.remove_many(&[inner])?; + d.insert(Some(outer), 1, (*taken[0]).clone())?; + Ok(()) + }) + .unwrap(); + let mut ids: Vec = outer_members.iter().chain(&inner_members).copied().collect(); + if reversed { + ids.reverse(); + } + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(inner), Some(outer), "the inner compound path is a member of the outer one"); + let want: Vec = BTreeSet::from([outer, inner]).into_iter().collect(); + assert_eq!(emptied_compounds(d, &ids), want, "reversed: {reversed}"); + run(&mut s, "edit.clear", json!({"ids": ids.iter().map(|id| id.0).collect::>()})); + let d = &s.doc().unwrap().doc; + assert!(d.node(inner).is_none(), "the emptied inner compound path goes (reversed: {reversed})"); + assert!(d.node(outer).is_none(), "the outer compound path it leaves empty goes too (reversed: {reversed})"); + } +} + +/// With a direct-selected anchor of another path in the selection, Clear still removes the outer +/// compound path that an emptied inner one leaves empty. +#[test] +fn clear_with_direct_anchors_removes_a_compound_path_emptied_through_an_emptied_inner_one() { + let mut s = new_doc(); + let outer_paths = [(); 2].map(|()| rect(&mut s)); + let (outer, outer_members) = compound(&mut s, &outer_paths); + let inner_paths = [(); 2].map(|()| rect(&mut s)); + let (inner, inner_members) = compound(&mut s, &inner_paths); + let other = rect(&mut s); + s.edit("Nest", |d, _| { + let taken = d.remove_many(&[inner])?; + d.insert(Some(outer), 1, (*taken[0]).clone())?; + Ok(()) + }) + .unwrap(); + let whole: Vec = outer_members.iter().chain(&inner_members).copied().collect(); + select_direct(&mut s, &whole, &[(other, two_anchors())]); + run(&mut s, "edit.clear", json!({})); + let d = &s.doc().unwrap().doc; + assert!(d.node(inner).is_none(), "the emptied inner compound path goes"); + assert!(d.node(outer).is_none(), "the outer compound path it leaves empty goes too"); + assert!(d.node(other).is_some(), "the path with anchors picked keeps its other sides"); +} diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 190c8b5810..a3234c2264 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1998,9 +1998,13 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo } } emptied.finish(d)?; - for p in compounds { + // A compound path left empty by an inner one that went is checked again after it. + let mut compounds = compounds; + while let Some(p) = compounds.pop_first() { if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) { + let up = d.parent_of(p).filter(|u| matches!(d.node(*u).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); d.remove(p)?; + compounds.extend(up); } } super::edit::release_empty_clips(d, clipped); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 6494a79ee7..511a8b95c2 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -3055,16 +3055,10 @@ fn makes_tracing(d: &Document, parent: NodeId, id: NodeId, at: Option) -> /// Whether deleting the objects `ids` together would leave an image first in an ordinary group /// named as a tracing, which would make that group one. `edit.clear` also deletes a compound path -/// it leaves empty, so such a compound path counts as deleted. +/// it leaves empty, nested ones included, so such a compound path counts as deleted. pub(super) fn clearing_makes_tracing(d: &Document, ids: &[NodeId]) -> bool { let mut gone: HashSet = ids.iter().copied().collect(); - let compounds: HashSet = - ids.iter().filter_map(|i| d.parent_of(*i)).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))).collect(); - for c in compounds { - if d.children(Some(c)).is_some_and(|k| k.iter().all(|n| gone.contains(&n.id))) { - gone.insert(c); - } - } + gone.extend(crate::cmd::emptied_compounds(d, ids)); let parents: HashSet = gone.iter().filter_map(|i| d.parent_of(*i)).filter(|p| !gone.contains(p)).collect(); parents.into_iter().filter(|p| named_as_tracing(d, *p)).any(|p| { d.children(Some(p)).and_then(|c| c.iter().find(|n| !gone.contains(&n.id)).map(|n| matches!(n.kind, NodeKind::Image(_)))).unwrap_or(false) From 7e6cc1beba604000f44119ab62782c7db739641f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 13:47:40 -0800 Subject: [PATCH 41/88] Swatches: the panel looks swatch names up in an index instead of scanning the list The Swatches panel body runs on every repaint while the pointer is over the panel or the Fill/Stroke chip popover is open. Each run looked names up with Document::swatch and swatch_name_taken, which scan every swatch: once per tint swatch, per selected name (selection check, Delete, Merge, the group check), per thumbnail cell and per list row, and the thumbnail highlight scanned the lit list once per cell. With 2,000 swatches all selected, a hovered pass took about 140 ms in a release-profile build, and about 100 ms with this change. - The panel keeps a name-to-position map of the document's swatches and color groups (panels/swatches/index.rs). It is built again only when the document's swatch lists change, so edits of the art alone keep it, and it holds the lists' identity by weak reference. A name that several swatches hold finds the first, as Document::swatch does. - The body, the thumbnails, the row icons, the footer and the panel menu's states look names up through it; the lit names are a set. - The menu states, which also run while the panel is closed, build no index when nothing is selected. - vectorcraft-doc gains a swatch-scans feature (dev-dependencies only) that counts the names Document::swatch and swatch_name_taken compare, for tests that count lookup work. --- crates/doc/Cargo.toml | 2 + crates/doc/src/swatches.rs | 31 ++- crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/panels/swatches.rs | 100 ++++++---- crates/ui-egui/src/panels/swatches/actions.rs | 38 +++- crates/ui-egui/src/panels/swatches/dnd.rs | 6 +- crates/ui-egui/src/panels/swatches/index.rs | 127 +++++++++++++ crates/ui-egui/src/panels/swatches/tests.rs | 7 +- .../src/panels/swatches/tests/lookups.rs | 177 ++++++++++++++++++ 9 files changed, 443 insertions(+), 46 deletions(-) create mode 100644 crates/ui-egui/src/panels/swatches/index.rs create mode 100644 crates/ui-egui/src/panels/swatches/tests/lookups.rs diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index 10adb09199..d018a5f946 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -15,6 +15,8 @@ spine-count = [] symbol-read-count = [] # `vectorcraft_doc::locked_artboard_measures` for other crates' tests (dev-dependencies only). locked-artboard-count = [] +# `vectorcraft_doc::swatches::swatch_scans` for other crates' tests (dev-dependencies only). +swatch-scans = [] [dependencies] vectorcraft-geom = { workspace = true } diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 0ee84dc32c..a9bbc30c04 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -16,6 +16,23 @@ use vectorcraft_color::{Color, Paint, Swatch, tint_percent}; use crate::{AppearanceItem, Document, Node, NodeId, NodeKind}; +#[cfg(any(test, feature = "swatch-scans"))] +thread_local! { + /// How many swatches and color groups [`Document::swatch`] and [`Document::swatch_name_taken`] have compared by + /// name on this thread. + static SWATCH_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many swatches and color groups [`Document::swatch`] and [`Document::swatch_name_taken`] have compared by +/// name on this thread, for other crates' tests that count how much work their lookups by name do (the +/// `swatch-scans` feature, dev-dependencies only). A lookup compares the swatches up to the one it finds, or all of +/// them for a name the document does not hold. +#[cfg(any(test, feature = "swatch-scans"))] +#[doc(hidden)] +pub fn swatch_scans() -> usize { + SWATCH_SCANS.with(std::cell::Cell::get) +} + impl Document { /// Every swatch: the ungrouped ones first, then each colour group's in order. pub fn swatches_iter(&self) -> impl Iterator { @@ -27,7 +44,12 @@ impl Document { /// Swatch `name`, the built-in Registration swatch ([`vectorcraft_color::swatch::registration`]) /// included. pub fn swatch(&self, name: &str) -> Option<&Swatch> { - self.swatches_iter().find(|s| s.name == name).or_else(|| (name == REGISTRATION).then(vectorcraft_color::swatch::registration)) + let found = self.swatches_iter().find(|s| { + #[cfg(any(test, feature = "swatch-scans"))] + SWATCH_SCANS.with(|c| c.set(c.get() + 1)); + s.name == name + }); + found.or_else(|| (name == REGISTRATION).then(vectorcraft_color::swatch::registration)) } pub fn swatch_mut(&mut self, name: &str) -> Option<&mut Swatch> { self.swatches_iter_mut().find(|s| s.name == name) @@ -74,7 +96,12 @@ impl Document { } /// Is `name` used by a swatch or a colour group (they share one namespace)? pub fn swatch_name_taken(&self, name: &str) -> bool { - self.swatch(name).is_some() || self.swatch_groups.iter().any(|g| g.name == name) + self.swatch(name).is_some() + || self.swatch_groups.iter().any(|g| { + #[cfg(any(test, feature = "swatch-scans"))] + SWATCH_SCANS.with(|c| c.set(c.get() + 1)); + g.name == name + }) } /// `base`, or the first of "base 2", "base 3"… no swatch or colour group uses. pub fn free_swatch_name(&self, base: &str) -> String { diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 49fad8d56f..2bfa1ff71d 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -101,6 +101,7 @@ egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } egui_extras = { workspace = true } vectorcraft-apischema = { workspace = true } vectorcraft-testkit = { workspace = true } +vectorcraft-doc = { workspace = true, features = ["swatch-scans"] } vectorcraft-tools = { workspace = true, features = ["testing"] } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index bea36866bb..80cc35c710 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -7,6 +7,7 @@ //! proxy's paint command with the object's id) and onto the Gradient panel's ramp; a Fill/Stroke //! proxy or the Gradient panel's thumbnail dropped on the panel becomes a swatch (`swatch.new`). +use std::collections::BTreeSet; use std::sync::Arc; use craft::behavior::{EditEvent, IconId, Selection}; @@ -36,12 +37,14 @@ use crate::panel_drag::PanelDrag; mod actions; mod dnd; +mod index; mod libraries; #[cfg(test)] use actions::{deletable, delete, mergeable, new_swatch, selected_group}; pub(crate) use actions::{menu_rows, menu_states, run}; pub(crate) use dnd::{HeldRows, follow_drag}; +use index::{IndexCache, SwatchIndex}; pub(crate) use libraries::{ DOCUMENT_SWATCHES, SwatchLibraries, USER_SLOT, colour_libraries, library_entries, limit_key, limit_name, load_library, open_library, other_library, user_library, window_menu, @@ -134,6 +137,8 @@ pub(crate) struct Model { /// The rows of the last drag from the list (as it started) and what its last check found /// ([`dnd::follow`]). drag: Option<(Arc, HeldRows)>, + /// The swatch and color group names of the last document asked for ([`Model::index`]). + index: IndexCache, } impl Model { @@ -193,6 +198,11 @@ impl Model { active.filter(|_| changed).map(str::to_string) } + /// The names of `d`'s swatches and color groups, built again only when they change ([`IndexCache::get`]). + fn index(&self, d: &Document) -> Arc { + self.index.get(d) + } + /// Selected `old` renamed to `new`, or dropped from the selection with `None`; the lead and the anchor follow. fn rename(&mut self, old: &str, new: Option<&str>) { let moved = |k: &SwatchKey| -> Option { @@ -261,31 +271,47 @@ fn name_of(key: &SwatchKey) -> &str { /// The swatches and colour groups selected in the panel, in click order, without names that no longer exist /// (deleted, renamed or undone). pub(crate) fn selected(app: &VectorcraftApp) -> Vec { - selected_in(app, &app.ui.swatches_panel) + if app.ui.swatches_panel.state.selection.items.is_empty() { + return vec![]; + } + selected_in(app, &app.ui.swatches_panel, &index_of(app)) } -/// The swatches and colour groups selected in `model`, as [`selected`] reads them from the app's panel. -fn selected_in(app: &VectorcraftApp, model: &Model) -> Vec { +/// The names of the active document ([`Model::index`]); an empty index without a document. +fn index_of(app: &VectorcraftApp) -> Arc { + app.session.active().map_or_else(Default::default, |st| app.ui.swatches_panel.index(&st.doc)) +} + +/// The swatches and color groups selected in `model`, as [`selected`] reads them from the app's panel, looked up in +/// `index`, the active document's names. +fn selected_in(app: &VectorcraftApp, model: &Model, index: &SwatchIndex) -> Vec { let Some(st) = app.session.active() else { return vec![] }; let mut names = model.names(); - names.retain(|n| n == REGISTRATION || st.doc.swatch_name_taken(n)); + names.retain(|n| n == REGISTRATION || index.name_taken(&st.doc, n)); names } /// The names the panel highlights: `sel` plus the swatches of selected colour groups (clicking a folder selects the /// whole group). -fn highlighted<'a>(d: &'a Document, sel: &'a [String]) -> Vec<&'a str> { - let mut out: Vec<&str> = sel.iter().map(String::as_str).collect(); - for g in d.swatch_groups.iter().filter(|g| sel.contains(&g.name)) { - out.extend(g.swatches.iter().map(|w| w.name.as_str())); +fn highlighted(d: &Document, index: &SwatchIndex, sel: &[String]) -> BTreeSet { + let mut out: BTreeSet = sel.iter().cloned().collect(); + let mut seen = BTreeSet::new(); + for name in sel { + if !seen.insert(name.as_str()) { + continue; + } + for g in index.groups(d, name) { + out.extend(g.swatches.iter().map(|w| w.name.clone())); + } } out } /// The `swatch`'s paint as the panel shows it, and whether it is global and spot. A tint swatch shows its base's kind; /// a spot colour shows the colour its art shows (a Lab one's CMYK equivalent when the Spot Colors options use those). -fn shown(d: &Document, s: &Swatch) -> (Paint, bool, bool) { - let (global, spot) = s.tint_of().and_then(|(base, _)| d.swatch(base)).map_or((s.global, s.spot), |b| (b.global, b.spot)); +/// `index` holds the names of `d`. +fn shown(d: &Document, index: &SwatchIndex, s: &Swatch) -> (Paint, bool, bool) { + let (global, spot) = s.tint_of().and_then(|(base, _)| index.swatch(d, base)).map_or((s.global, s.spot), |b| (b.global, b.spot)); let paint = match s.paint { Paint::Solid { color, swatch: None, .. } if spot => Paint::solid(d.linked_color(color, true)), _ => s.paint.clone(), @@ -302,8 +328,8 @@ fn swatch_color(c: &Color) -> SwatchColor { } } -fn entry(d: &Document, s: &Swatch) -> SwatchEntry { - let (paint, global, spot) = shown(d, s); +fn entry(d: &Document, index: &SwatchIndex, s: &Swatch) -> SwatchEntry { + let (paint, global, spot) = shown(d, index, s); let held = match &paint { Paint::Solid { color, .. } => match s.tint_of() { Some((base, tint)) => SwatchPaint::Tint { base: base.to_string(), tint, color: swatch_color(color) }, @@ -332,19 +358,19 @@ fn registration_entry() -> SwatchEntry { /// The panel's groups for the kind filter and the find field's `query` (a case-insensitive name match; a colour /// group whose name matches shows all its swatches). The first group holds the swatches outside any colour group: -/// None first, then Registration, then the rest (the reference app's order). -fn groups(app: &VectorcraftApp, kind: Kind, query: &str) -> Vec { +/// None first, then Registration, then the rest (the reference app's order). `index` holds the active document's names. +fn groups(app: &VectorcraftApp, index: &SwatchIndex, kind: Kind, query: &str) -> Vec { let Some(st) = app.session.active() else { return vec![] }; let d = &st.doc; let q = query.trim().to_lowercase(); let found = |n: &str| q.is_empty() || n.to_lowercase().contains(&q); let mut top = vec![]; let (specials, rest): (Vec<_>, Vec<_>) = d.swatches.iter().partition(|s| s.paint.is_none()); - top.extend(specials.iter().filter(|s| kind.accepts(&s.paint, false) && found(&s.name)).map(|s| entry(d, s))); + top.extend(specials.iter().filter(|s| kind.accepts(&s.paint, false) && found(&s.name)).map(|s| entry(d, index, s))); if matches!(kind, Kind::All | Kind::Color) && found(REGISTRATION) { top.push(registration_entry()); } - top.extend(rest.iter().filter(|s| kind.accepts(&s.paint, false) && found(&s.name)).map(|s| entry(d, s))); + top.extend(rest.iter().filter(|s| kind.accepts(&s.paint, false) && found(&s.name)).map(|s| entry(d, index, s))); // PLAN: assumed the panel shows the first group, named "", without a folder header (the ungrouped swatches). let mut out = vec![SwatchGroup { name: String::new(), entries: top }]; for g in &d.swatch_groups { @@ -354,7 +380,7 @@ fn groups(app: &VectorcraftApp, kind: Kind, query: &str) -> Vec { if items.is_empty() && !(all && matches!(kind, Kind::Groups | Kind::All)) { continue; } - out.push(SwatchGroup { name: g.name.clone(), entries: items.into_iter().map(|s| entry(d, s)).collect() }); + out.push(SwatchGroup { name: g.name.clone(), entries: items.into_iter().map(|s| entry(d, index, s)).collect() }); } out } @@ -438,6 +464,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { }; // The model leaves the app while the browser borrows the document, and comes back before the events run. let mut model = std::mem::take(&mut app.ui.swatches_panel); + let Some(index) = app.session.active().map(|st| model.index(&st.doc)) else { + app.ui.swatches_panel = model; + return; + }; let view = app.ui.swatches_view; if model.view != Some(view) { (model.state.browser.view, model.state.browser.zoom) = view.preset(); @@ -447,7 +477,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { let active = model.kept(app, active); let focus = model.focus(app, active.as_deref()); let query = if model.show_find { model.state.browser.filter.clone() } else { String::new() }; - let data = groups(app, model.kind, &query); + let data = groups(app, &index, model.kind, &query); // Without a selection the swatch of the active paint is highlighted. let picked = model.names(); let base = if picked.is_empty() { active.into_iter().collect() } else { picked }; @@ -456,7 +486,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { return; }; let revision = (st.uid, st.revision); - let lit: Vec = highlighted(&st.doc, &base).into_iter().map(str::to_string).collect(); + let lit = highlighted(&st.doc, &index, &base); let doc = Arc::clone(&st.doc); let start = dnd::DragStart::of(st); // The row menu, the drop rules and the drag payload read the document, its reverts and the drag start alone, so @@ -464,7 +494,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { let host = start.version(st.revision); let document = st.uid; let reverts = st.reverts; - let foot = Footer::of(app, &model, held); + let foot = Footer::of(app, &model, &index, held); let shown_app: &VectorcraftApp = app; let search = model.show_find; let state = &mut model.state; @@ -478,12 +508,12 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { .footer(|ui, _| footed = Some(foot.show(ui))) .show(ui, |ui, _| { let start = start.clone(); - let thumbs = Thumbs { revision, lit: lit.clone(), doc: Arc::clone(&doc) }; + let thumbs = Thumbs { revision, lit: lit.clone(), doc: Arc::clone(&doc), index: Arc::clone(&index) }; let browser = SwatchesPanel::new(&data, Bind::bound(&mut *state), Srgba::rgb(0.0, 0.0, 0.0)) .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&start, &drag.grabbed, dragged_rows(drag)))) .thumb(thumbs, thumb) .row_icons(|key| match key { - SwatchKey::Swatch(name) => row_icons(shown_app, name), + SwatchKey::Swatch(name) => row_icons(shown_app, &index, name), _ => vec![], }) .row_items(|key| row_items(shown_app, key)) @@ -593,9 +623,12 @@ struct Thumbs { /// The document's uid and revision. revision: (u64, u64), /// The selected swatches, those of selected colour groups, or the active paint's swatch. - lit: Vec, + lit: BTreeSet, #[memo_props(covered_by = "revision", reason = "a document's uid and revision change with every edit of it")] doc: Arc, + /// The names of `doc`. + #[memo_props(covered_by = "revision", reason = "the index is built from the document at this uid and revision")] + index: Arc, } /// The thumbnail of swatch cell `info` (a colour group is the browser's folder row, not a thumbnail). @@ -606,8 +639,8 @@ fn thumb(t: &Thumbs, cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, paint_swatch(cx, rect, &Paint::registration(), selected, (false, false), None); return; } - let Some(s) = t.doc.swatch(name) else { return }; - let (paint, global, spot) = shown(&t.doc, s); + let Some(s) = t.index.swatch(&t.doc, name) else { return }; + let (paint, global, spot) = shown(&t.doc, &t.index, s); paint_swatch(cx, rect, &paint, selected, (global, spot), Some(&t.doc)); } @@ -806,10 +839,11 @@ pub(super) fn kind_icons(paint: &Paint, global: bool, spot: bool) -> Vec<(IconSp } } -fn row_icons(app: &VectorcraftApp, name: &str) -> Vec<(IconSpec<'static>, String)> { +/// The kind icons of swatch row `name`, looked up in `index`, the active document's names. +fn row_icons(app: &VectorcraftApp, index: &SwatchIndex, name: &str) -> Vec<(IconSpec<'static>, String)> { let Some(st) = app.session.active() else { return vec![] }; - let Some(s) = st.doc.swatch(name) else { return vec![] }; - let (paint, global, spot) = shown(&st.doc, s); + let Some(s) = index.swatch(&st.doc, name) else { return vec![] }; + let (paint, global, spot) = shown(&st.doc, index, s); kind_icons(&paint, global, spot) } @@ -856,12 +890,12 @@ struct Footer { impl Footer { /// The footer's state for the panel `model`, which is out of the app while the swatch browser borrows it, with - /// `held` from the drag check ([`Footer::held`]). - fn of(app: &VectorcraftApp, model: &Model, held: bool) -> Self { - let sel = selected_in(app, model); - let del = actions::deletable(app, &sel); + /// `held` from the drag check ([`Footer::held`]); `index` holds the active document's names. + fn of(app: &VectorcraftApp, model: &Model, index: &SwatchIndex, held: bool) -> Self { + let sel = selected_in(app, model, index); + let del = actions::deletable_in(app, index, &sel); let opts = actions::editable(app, &sel); - let group = actions::selected_group(app, &sel).filter(|_| opts.is_none()); + let group = actions::selected_group_in(app, index, &sel).filter(|_| opts.is_none()); Footer { kind: model.kind, libraries_open: library_panel::any_open::(&app.ui), diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index 7fd324a517..6769fe13db 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -4,17 +4,26 @@ use craft::ui::runtime::commands::{CommandState, CommandStates}; use serde_json::{Value, json}; use super::dnd::group_of; +use super::index::SwatchIndex; use super::libraries::SwatchLibraries; use super::library_panel; -use super::{View, active_paint, selected}; +use super::{View, active_paint, index_of, selected}; use crate::VectorcraftApp; /// The selected swatches and groups that can be deleted: every color group in the document and /// every swatch that `Swatch::is_reserved` does not reserve (None and Registration). Names the /// document does not hold are left out. pub(super) fn deletable(app: &VectorcraftApp, sel: &[String]) -> Vec { + if sel.is_empty() { + return vec![]; + } + deletable_in(app, &index_of(app), sel) +} + +/// [`deletable`], looked up in `index`, the active document's names. +pub(super) fn deletable_in(app: &VectorcraftApp, index: &SwatchIndex, sel: &[String]) -> Vec { let Some(d) = app.session.active().map(|st| &st.doc) else { return vec![] }; - sel.iter().filter(|n| d.swatch(n).map_or_else(|| d.swatch_groups.iter().any(|g| g.name == **n), |w| !w.is_reserved())).cloned().collect() + sel.iter().filter(|n| index.swatch(d, n).map_or_else(|| index.is_group(d, n), |w| !w.is_reserved())).cloned().collect() } /// The selected swatch when exactly one swatch with an editor is selected (not None, Registration @@ -28,14 +37,30 @@ pub(super) fn editable(app: &VectorcraftApp, sel: &[String]) -> Option { /// The selected solid-colour swatches in selection order (Merge Swatches keeps the first). pub(super) fn mergeable(app: &VectorcraftApp, sel: &[String]) -> Vec { + if sel.is_empty() { + return vec![]; + } + mergeable_in(app, &index_of(app), sel) +} + +/// [`mergeable`], looked up in `index`, the active document's names. +fn mergeable_in(app: &VectorcraftApp, index: &SwatchIndex, sel: &[String]) -> Vec { let Some(st) = app.session.active() else { return vec![] }; - sel.iter().filter(|n| st.doc.swatch(n).is_some_and(|w| w.paint.color().is_some())).cloned().collect() + sel.iter().filter(|n| index.swatch(&st.doc, n).is_some_and(|w| w.paint.color().is_some())).cloned().collect() } /// The first selected colour group (Ungroup Color Group). pub(super) fn selected_group(app: &VectorcraftApp, sel: &[String]) -> Option { + if sel.is_empty() { + return None; + } + selected_group_in(app, &index_of(app), sel) +} + +/// [`selected_group`], looked up in `index`, the active document's names. +pub(super) fn selected_group_in(app: &VectorcraftApp, index: &SwatchIndex, sel: &[String]) -> Option { let d = &app.session.active()?.doc; - sel.iter().find(|n| d.swatch_groups.iter().any(|g| g.name == **n)).cloned() + sel.iter().find(|n| index.is_group(d, n)).cloned() } /// The selected color group when it is the whole selection (Color Group Options). @@ -175,12 +200,13 @@ pub(crate) fn menu_rows(app: &VectorcraftApp) -> Vec { /// The enabled and checked state of the menu's rows. pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) { let sel = selected(app); - let (del, opts, group) = (deletable(app, &sel), editable(app, &sel), selected_group(app, &sel)); + let index = if sel.is_empty() { Default::default() } else { index_of(app) }; + let (del, opts, group) = (deletable_in(app, &index, &sel), editable(app, &sel), selected_group_in(app, &index, &sel)); let art_selected = app.session.active().is_some_and(|st| !st.selection.objects.is_empty()); let doc = app.session.active().is_some(); let enabled = [ ("duplicate", opts.is_some()), - ("merge", mergeable(app, &sel).len() > 1), + ("merge", mergeable_in(app, &index, &sel).len() > 1), ("delete", !del.is_empty()), ("editGroup", group.is_some()), ("ungroup", group.is_some()), diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index 4b68266bf1..ff32806f8f 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -1,3 +1,4 @@ +use std::collections::HashSet; use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::{Arc, Weak}; @@ -365,9 +366,10 @@ fn footer_rows(app: &VectorcraftApp, r: &SwatchRows) -> Vec { if !sel.contains(&r.grabbed) { return r.names.clone(); } - super::shown_keys(&super::groups(app, super::Kind::All, "")) + let sel: HashSet<&str> = sel.iter().map(String::as_str).collect(); + super::shown_keys(&super::groups(app, &super::index_of(app), super::Kind::All, "")) .iter() - .filter(|k| matches!(k, SwatchKey::Group(_)) == r.groups && sel.iter().any(|s| s == name_of(k))) + .filter(|k| matches!(k, SwatchKey::Group(_)) == r.groups && sel.contains(name_of(k))) .map(|k| name_of(k).to_string()) .collect() } diff --git a/crates/ui-egui/src/panels/swatches/index.rs b/crates/ui-egui/src/panels/swatches/index.rs new file mode 100644 index 0000000000..e091299fda --- /dev/null +++ b/crates/ui-egui/src/panels/swatches/index.rs @@ -0,0 +1,127 @@ +//! The Swatches panel's name lookups: the document's swatches and color groups by name, built for one version of the +//! document's swatch lists and kept in the panel's [`Model`](super::Model) from pass to pass. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, PoisonError, Weak}; + +use vectorcraft_color::swatch::{REGISTRATION, registration}; +use vectorcraft_color::{Swatch, SwatchGroup}; +use vectorcraft_doc::{Document, Shared}; + +/// The swatches and color groups of one version of a document's swatch lists, by name. A name that several swatches +/// hold finds the swatch [`Document::swatch`] finds: the first in [`Document::swatches_iter`] order. +#[derive(Debug, Default)] +pub(crate) struct SwatchIndex { + /// The identity of the document's ungrouped swatch list, without keeping its contents. + listed: Weak>, + /// The identity of the document's color group list, without keeping its contents. + grouped: Weak>, + /// Each swatch name: the color group that holds it (`None` outside any group) and its position there. + swatches: HashMap, usize)>, + /// Each color group name: the positions of the groups of that name, in document order. + groups: HashMap>, +} + +impl SwatchIndex { + /// The names of `d`'s swatches and color groups. + pub(crate) fn new(d: &Document) -> Self { + #[cfg(test)] + counts::built(d.swatches_iter().count() + d.swatch_groups.len()); + let mut swatches = HashMap::new(); + for (i, s) in d.swatches.iter().enumerate() { + swatches.entry(s.name.clone()).or_insert((None, i)); + } + let mut groups: HashMap> = HashMap::new(); + for (g, group) in d.swatch_groups.iter().enumerate() { + groups.entry(group.name.clone()).or_default().push(g); + for (i, s) in group.swatches.iter().enumerate() { + swatches.entry(s.name.clone()).or_insert((Some(g), i)); + } + } + SwatchIndex { listed: Shared::downgrade(&d.swatches), grouped: Shared::downgrade(&d.swatch_groups), swatches, groups } + } + + /// Whether the index holds the names of `d`: `d` has the swatch lists the index was built from. + fn of(&self, d: &Document) -> bool { + std::ptr::eq(Weak::as_ptr(&self.listed), &*d.swatches) && std::ptr::eq(Weak::as_ptr(&self.grouped), &*d.swatch_groups) + } + + /// Swatch `name` of `d`, a document with the lists the index was built from, as [`Document::swatch`] finds it: the + /// built-in Registration swatch when no swatch of the document has its name. + pub(crate) fn swatch<'d>(&self, d: &'d Document, name: &str) -> Option<&'d Swatch> { + #[cfg(test)] + counts::looked_up(1); + let found = self.swatches.get(name).and_then(|&(group, i)| match group { + None => d.swatches.get(i), + Some(g) => d.swatch_groups.get(g)?.swatches.get(i), + }); + found.filter(|s| s.name == name).or_else(|| (name == REGISTRATION).then(registration)) + } + + /// The color groups of `d` named `name`, in document order. + pub(crate) fn groups<'a>(&'a self, d: &'a Document, name: &'a str) -> impl Iterator { + #[cfg(test)] + counts::looked_up(1); + self.groups.get(name).into_iter().flatten().filter_map(|&g| d.swatch_groups.get(g)).filter(move |g| g.name == name) + } + + /// Whether `name` is a color group of `d`. + pub(crate) fn is_group(&self, d: &Document, name: &str) -> bool { + self.groups(d, name).next().is_some() + } + + /// Whether a swatch or a color group of `d` uses `name`, as [`Document::swatch_name_taken`] tells. + pub(crate) fn name_taken(&self, d: &Document, name: &str) -> bool { + self.swatch(d, name).is_some() || self.is_group(d, name) + } +} + +/// The index of the last document asked for, shared by the panel's passes and by the menu states, which read it +/// whether or not the panel is shown. +#[derive(Debug, Default)] +pub(crate) struct IndexCache(Mutex>>); + +impl IndexCache { + /// The names of `d`: the kept index when `d` still has the swatch lists it was built from, otherwise a new one, + /// kept for the calls that follow. Edits that leave the swatches and color groups alone keep the index. + pub(crate) fn get(&self, d: &Document) -> Arc { + let mut kept = self.0.lock().unwrap_or_else(PoisonError::into_inner); + match &*kept { + Some(index) if index.of(d) => Arc::clone(index), + _ => Arc::clone(kept.insert(Arc::new(SwatchIndex::new(d)))), + } + } +} + +impl Clone for IndexCache { + fn clone(&self) -> Self { + IndexCache(Mutex::new(self.0.lock().unwrap_or_else(PoisonError::into_inner).clone())) + } +} + +/// How much work this thread's panel lookups did: the names each index build added and each lookup. +#[cfg(test)] +pub(crate) mod counts { + use std::cell::Cell; + + thread_local! { + /// Names looked up, and names added by index builds. + static LOOKUPS: Cell = const { Cell::new(0) }; + /// Index builds. + static BUILDS: Cell = const { Cell::new(0) }; + } + + pub(super) fn looked_up(n: usize) { + LOOKUPS.with(|c| c.set(c.get() + n)); + } + + pub(super) fn built(names: usize) { + BUILDS.with(|c| c.set(c.get() + 1)); + looked_up(names); + } + + /// The lookups and the index builds since the last call, which starts the counts again. + pub(crate) fn take() -> (usize, usize) { + (LOOKUPS.with(|c| c.replace(0)), BUILDS.with(|c| c.replace(0))) + } +} diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 9f0d992276..fba8f9fef5 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -9,6 +9,7 @@ use vectorcraft_color::Color; use vectorcraft_engine::Session; mod context_menu; +mod lookups; fn app() -> VectorcraftApp { let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); @@ -55,7 +56,7 @@ fn key_of(app: &VectorcraftApp, name: &str) -> SwatchKey { /// The rows in panel order, as the browser shows every swatch. fn shown_rows(app: &VectorcraftApp) -> Vec { - shown_keys(&groups(app, Kind::All, "")) + shown_keys(&groups(app, &index_of(app), Kind::All, "")) } /// Feeds the browser event `event` to the panel's handler. @@ -1388,7 +1389,7 @@ fn the_active_tint_or_gradient_swatch_is_highlighted_and_a_tint_edits_its_base() assert_eq!(active_swatch(&app).as_deref(), Some("Ink"), "no tint swatch yet: its base"); app.run("swatch.new", json!({})).unwrap(); assert_eq!(active_swatch(&app).as_deref(), Some("Ink 40%")); - let tint = groups(&app, Kind::Color, "Ink 40").into_iter().flat_map(|g| g.entries).find(|e| e.name == "Ink 40%").unwrap(); + let tint = groups(&app, &index_of(&app), Kind::Color, "Ink 40").into_iter().flat_map(|g| g.entries).find(|e| e.name == "Ink 40%").unwrap(); assert_eq!(tint.kind, SwatchKind::Spot, "a tint swatch shows its base's kind"); app.run("paint.setFill", json!({"swatch": "Sunset"})).unwrap(); assert_eq!(active_swatch(&app).as_deref(), Some("Sunset"), "the applied gradient swatch"); @@ -1517,7 +1518,7 @@ fn lab_spot_tiles_show_the_colour_the_spot_colors_options_pick() { app.run("swatch.new", json!({"name": "Ink", "color": lab, "spot": true})).unwrap(); let tile = |app: &VectorcraftApp| { let d = doc(app); - shown(&d, d.swatch("Ink").expect("the Ink swatch")).0.color().unwrap() + shown(&d, &index_of(app), d.swatch("Ink").expect("the Ink swatch")).0.color().unwrap() }; assert_eq!(tile(&app), lab); app.run("swatch.spotOptions", json!({"useLab": false})).unwrap(); diff --git a/crates/ui-egui/src/panels/swatches/tests/lookups.rs b/crates/ui-egui/src/panels/swatches/tests/lookups.rs new file mode 100644 index 0000000000..d10e31d938 --- /dev/null +++ b/crates/ui-egui/src/panels/swatches/tests/lookups.rs @@ -0,0 +1,177 @@ +//! The panel's name lookups: what one pass over the panel costs as the swatch list grows, when the name index is built +//! again, and that the index finds what the document finds. + +use super::*; +use crate::tests::panel_harness::Panel; +use egui::Event; +use vectorcraft_color::SwatchGroup; + +/// An app whose document holds `n` swatches besides the defaults: `n / 2` global colors, and a tint of each in color +/// groups of ten. Every swatch and color group is selected in the panel. +fn crowded(n: usize) -> VectorcraftApp { + let mut app = app(); + { + let st = app.session.doc_mut().unwrap(); + let d = Arc::make_mut(&mut st.doc); + let bases: Vec = (0..n / 2).map(|i| format!("Ink {i}")).collect(); + for (i, name) in bases.iter().enumerate() { + let color = Color::cmyk(i as f32 / n as f32, 0.5, 0.2, 0.0); + d.swatches.push(Swatch { name: name.clone(), paint: Paint::solid(color), global: true, spot: false }); + } + for (g, chunk) in bases.chunks(10).enumerate() { + let swatches = chunk + .iter() + .map(|base| { + let paint = Paint::Solid { color: Color::cmyk(0.1, 0.25, 0.1, 0.0), swatch: Some(base.clone()), tint: 0.5 }; + Swatch { name: format!("{base} 50%"), paint, global: false, spot: false } + }) + .collect(); + d.swatch_groups.push(SwatchGroup { name: format!("Tints {g}"), swatches }); + } + } + let d = doc(&app); + let mut keys: Vec = d.swatches_iter().map(|s| SwatchKey::Swatch(s.name.clone())).collect(); + keys.extend(d.swatch_groups.iter().map(|g| SwatchKey::Group(g.name.clone()))); + app.ui.swatches_panel.state.selection = Selection::new(keys.clone(), keys.last().cloned(), keys.first().cloned()); + app +} + +/// One pass of the panel with the pointer moving over it, as while it is hovered. +fn hovered(panel: &mut Panel) { + panel.frame_with(vec![Event::PointerMoved(Pos2::new(140.0, 300.0))]); +} + +/// The app's name lookup work in one hovered pass over [`crowded`]`(n)`, after the panel's first passes: the panel's +/// index lookups and the document's own swatch and color group name comparisons. The browser's work is not counted. +fn lookups_in_a_pass(n: usize) -> usize { + let mut panel = Panel::new(crowded(n), show); + let d = doc(&panel.app()); + assert_eq!(selected(&panel.app()).len(), d.swatches_iter().count() + d.swatch_groups.len(), "every swatch and group is selected"); + index::counts::take(); + let scans = vectorcraft_doc::swatches::swatch_scans(); + hovered(&mut panel); + index::counts::take().0 + vectorcraft_doc::swatches::swatch_scans() - scans +} + +/// With every swatch selected, the app's name lookup work in one hovered pass scales with the swatch count: twice +/// the swatches, at most twice the panel index lookups and document name comparisons. The browser's work is not counted. +#[test] +fn a_hovered_pass_looks_up_names_in_proportion_to_the_swatch_count() { + let small = lookups_in_a_pass(200); + let large = lookups_in_a_pass(400); + assert!(small > 0, "the app looks names up during the pass"); + assert!(large <= 2 * small, "app name lookup work in one pass: {small} with 200 swatches, {large} with 400"); +} + +/// Passes at one revision of the document build no index; after a swatch edit the panel builds one that finds the new +/// swatch, the passes that follow build none, and an edit of the art alone builds none. +#[test] +fn passes_at_one_document_revision_build_no_name_index() { + let mut panel = Panel::new(crowded(40), show); + index::counts::take(); + hovered(&mut panel); + hovered(&mut panel); + assert_eq!(index::counts::take().1, 0, "no index build at the same revision"); + panel.app().run("swatch.new", json!({"name": "Fresh", "color": "#336699"})).unwrap(); + select_rows(&mut panel.app(), &["Fresh"]); + hovered(&mut panel); + assert_eq!(index::counts::take().1, 1, "the edit builds one index"); + hovered(&mut panel); + hovered(&mut panel); + assert_eq!(index::counts::take().1, 0, "no index build at the new revision once a pass built it"); + assert_eq!(selected(&panel.app()), ["Fresh"]); + panel.app().run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + hovered(&mut panel); + assert_eq!(index::counts::take().1, 0, "an edit of the art alone builds no index"); +} + +/// The menu states, which are worked out while the panel is closed too, build one index per version of the swatch +/// lists, and none without a selection. +#[test] +fn menu_states_of_a_closed_panel_build_one_name_index_per_revision() { + let mut app = crowded(40); + let mut states = craft::ui::runtime::commands::CommandStates::new(); + index::counts::take(); + menu_states(&app, &mut states); + menu_states(&app, &mut states); + assert_eq!(index::counts::take().1, 1, "one index build at one revision"); + app.run("swatch.new", json!({"name": "Fresh", "color": "#336699"})).unwrap(); + menu_states(&app, &mut states); + menu_states(&app, &mut states); + assert_eq!(index::counts::take().1, 1, "one index build at the new revision"); + let mut idle = crowded(40); + idle.ui.swatches_panel.state.selection = Selection::new(vec![], None, None); + index::counts::take(); + menu_states(&idle, &mut states); + assert_eq!(index::counts::take().1, 0, "no index build without a selection"); +} + +/// Every name of `app`'s document, a few it does not hold and Registration, as the index and the document find them. +fn check_index(app: &VectorcraftApp) { + let st = app.session.active().unwrap(); + let d = &st.doc; + let index = SwatchIndex::new(d); + let names = d.swatches_iter().map(|s| s.name.as_str()).chain(d.swatch_groups.iter().map(|g| g.name.as_str())); + for name in names.chain(["Missing", REGISTRATION, "", "twin"]) { + let at = |s: Option<&Swatch>| s.map(|s| s as *const Swatch); + assert_eq!(at(index.swatch(d, name)), at(d.swatch(name)), "the swatch named {name:?}"); + assert_eq!(index.name_taken(d, name), d.swatch_name_taken(name), "whether {name:?} is taken"); + let groups = |found: Vec<&SwatchGroup>| found.into_iter().map(|g| g as *const SwatchGroup).collect::>(); + let want = groups(d.swatch_groups.iter().filter(|g| g.name == name).collect()); + assert_eq!(groups(index.groups(d, name).collect()), want, "the color groups named {name:?}"); + } +} + +/// A swatch `name` of color `hex`. +fn named(name: &str, hex: &str) -> Swatch { + Swatch { name: name.into(), paint: Paint::solid(Color::from_hex(hex).unwrap()), global: true, spot: false } +} + +/// A name that two swatches hold finds the first, as the document finds it, and groups of one name are all found; a +/// rename of the first leaves the name to the second. +#[test] +fn repeated_names_find_what_the_document_finds() { + let mut app = app(); + { + let d = Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + d.swatches.push(named("Twin", "#aa0000")); + d.swatch_groups.push(SwatchGroup { name: "Pair".into(), swatches: vec![named("Twin", "#0000aa"), named("Solo", "#00aa00")] }); + d.swatch_groups.push(SwatchGroup { name: "Pair".into(), swatches: vec![] }); + } + check_index(&app); + app.run("swatch.edit", json!({"name": "Twin", "newName": "Once"})).unwrap(); + check_index(&app); + let index = index_of(&app); + let d = &app.session.active().unwrap().doc; + assert_eq!(index.swatch(d, "Twin").and_then(|s| s.paint.color()), Color::from_hex("#0000aa"), "the grouped Twin is left"); +} + +/// The panel lights the swatches of a selected group and deletes what it deleted before; after a rename at a new +/// revision, the selection drops the old name and the index finds the new one. +#[test] +fn renamed_names_leave_the_selection_and_the_index() { + let mut app = app(); + { + let d = Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + d.swatch_groups.push(SwatchGroup { name: "Pair".into(), swatches: vec![named("Deep Sea", "#0000aa"), named("Solo", "#00aa00")] }); + } + select_rows(&mut app, &["Pair", "Solo"]); + let mut panel = Panel::new(app, show); + assert_eq!(selected(&panel.app()), ["Pair", "Solo"]); + let (lit, kinds) = { + let app = panel.app(); + let st = app.session.active().unwrap(); + let index = index_of(&app); + (highlighted(&st.doc, &index, &["Pair".into()]), deletable(&app, &["Pair".into(), "Deep Sea".into(), "[None]".into()])) + }; + assert_eq!(lit, BTreeSet::from(["Pair".into(), "Deep Sea".into(), "Solo".into()]), "a selected group lights its swatches"); + assert_eq!(kinds, ["Pair", "Deep Sea"]); + panel.app().run("swatch.edit", json!({"name": "Solo", "newName": "Renamed"})).unwrap(); + hovered(&mut panel); + assert_eq!(selected(&panel.app()), ["Pair"], "the old name leaves the selection"); + check_index(&panel.app()); + let app = panel.app(); + let index = index_of(&app); + let d = &app.session.active().unwrap().doc; + assert!(index.swatch(d, "Solo").is_none() && index.swatch(d, "Renamed").is_some(), "the index follows the rename"); +} From 07518a53e8f349eeb77e7adec699bbdedcc0c044 Mon Sep 17 00:00:00 2001 From: mcenahle Date: Fri, 4 Dec 2026 22:03:01 +0800 Subject: [PATCH 42/88] i18n(zh-hans): translate Check for Updates menu item --- crates/ui-egui/src/i18n/zh-hans.tsv | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 7631ba753a..37254dc84d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -325,6 +325,7 @@ antiAlias Sharp 锐利 Brush Options… 画笔选项… Options of Selected Object… 所选对象的选项… Options of Selected Object 所选对象的选项 + Check for Updates… 检查更新… @msg no path painted with a brush is selected 未选择用画笔绘制的路径 @msg the selected paths are painted with brushes of different types 所选路径使用了不同类型的画笔 @msg give `params` or `reset`, not both 请提供 `params` 或 `reset`,不能同时提供 From 9d768d61936c70db261b5ec4c991d17ef811fc93 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Fri, 4 Dec 2026 19:42:38 +0530 Subject: [PATCH 43/88] Type menu: show conversions for the selected text kinds --- crates/ui-egui/src/menus/state.rs | 59 ++++++++++++++++++------------- crates/ui-egui/src/menus/tests.rs | 45 +++++++++++++++++++++++ 2 files changed, 80 insertions(+), 24 deletions(-) diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 6ae7c66be0..f00d98a243 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -4,6 +4,37 @@ use super::{Brightness, Value, VectorcraftApp}; use crate::i18n::LangExt as _; use craft::keymap::{Chord, CommandRef}; use craft::ui::runtime::commands; +use vectorcraft_engine::doc::{NodeKind, TextKind, TextObject}; + +/// The first matching text object among the selection and its descendants, in command order. +fn selected_text(app: &VectorcraftApp, matches_kind: fn(&TextKind) -> bool) -> Option<&TextObject> { + let st = app.session.active()?; + for node in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { + let mut found = None; + node.walk(&mut |child| { + if found.is_none() + && let NodeKind::Text(text) = &child.kind + && matches_kind(&text.kind) + { + found = Some(text); + } + }); + if found.is_some() { + return found; + } + } + None +} + +/// Conversion rows in the Type menu require an object of the source kind. +fn type_conversion_hidden(app: &VectorcraftApp, id: &str) -> bool { + let matches_kind: fn(&TextKind) -> bool = match id { + "type.convertToAreaType" => |kind| matches!(kind, TextKind::Point), + "type.convertToPointType" => |kind| matches!(kind, TextKind::Area { .. }), + _ => return false, + }; + selected_text(app, matches_kind).is_none() +} /// Checked state for toggle items. pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { @@ -19,26 +50,6 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { let v = &app.ui.view; // An item that can be on or off is `Some` whatever the document and selection (off with none): // the macOS menu bar can't change an item's kind without rebuilding. - // The first type object of a kind `kinds` takes among the selected objects and the objects - // inside them, in the order the type commands act on them. - let selected_text = |kinds: fn(&vectorcraft_engine::doc::TextKind) -> bool| { - let st = app.session.active()?; - let mut found = None; - for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { - n.walk(&mut |c| { - if found.is_none() - && let vectorcraft_engine::doc::NodeKind::Text(t) = &c.kind - && kinds(&t.kind) - { - found = Some(t); - } - }); - if found.is_some() { - break; - } - } - found - }; Some(match id { "type.orientation.vertical" | "type.orientation.horizontal" => { crate::panels::character::shared_text_flag(app, |t| t.vertical) == Some(id == "type.orientation.vertical") @@ -46,14 +57,14 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { "type.opticalMarginAlignment" => crate::panels::character::shared_text_flag(app, |t| t.optical_margin) == Some(true), // Dynamic Text of the first selected type, which the item turns the other way (point type // counts as off: the item turns it into area type with Block on). - "type.dynamicText" => selected_text(|_| true).is_some_and(|t| t.dynamic_text && !matches!(t.kind, vectorcraft_engine::doc::TextKind::Point)), + "type.dynamicText" => selected_text(app, |_| true).is_some_and(|t| t.dynamic_text && !matches!(t.kind, TextKind::Point)), "view.outline" => app.outline_view(), "view.pixelPreview" => v.pixel_preview, "view.trimView" => v.trim_view, "view.snapToPixel" => v.snap_to_pixel, "view.snapToGlyph" => v.snap_to_glyph, // Type on a Path effect of the selected path type. - "type.pathOptions" if p.get("effect").is_some() => selected_text(|k| matches!(k, vectorcraft_engine::doc::TextKind::OnPath { .. })) + "type.pathOptions" if p.get("effect").is_some() => selected_text(app, |k| matches!(k, TextKind::OnPath { .. })) .is_some_and(|t| p.get("effect").and_then(Value::as_str) == Some(t.path_effect.id())), "view.smartGuides" => v.smart_guides, "edit.autoSpellCheck" => v.auto_spell_check, @@ -172,7 +183,7 @@ fn east_asian_hidden(app: &VectorcraftApp, id: &str) -> bool { /// How the menus show item `id` (params `p`) now: (enabled, checked: `Some` for an item that is on /// or off), or `None` while they leave it out: an empty slot ([`hidden_when_disabled`]), an item /// another stands in for ([`swapped_out`]) or an East Asian item with those options hidden -/// ([`east_asian_hidden`]). +/// ([`east_asian_hidden`]), or a type conversion without eligible text ([`type_conversion_hidden`]). pub fn shown_state(app: &VectorcraftApp, id: &str, p: &Value) -> Option<(bool, Option)> { shown_state_with(app, id, p, &mut |id| why_off(app, id)) } @@ -188,7 +199,7 @@ pub(crate) fn shown_state_with( let en = why_off(id).is_none() && (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p)) && (!vectorcraft_engine::cmd::plugin::is_command_id(id) || crate::dialogs::plugin::canvas_item_enabled(app, id, p)); - if (!en && hidden_when_disabled(id)) || swapped_out(id, why_off) || east_asian_hidden(app, id) { + if (!en && hidden_when_disabled(id)) || swapped_out(id, why_off) || east_asian_hidden(app, id) || type_conversion_hidden(app, id) { return None; } Some((en, checked(app, id, p))) diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 39909b57eb..df23d8edf9 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -164,6 +164,51 @@ fn snapping_menu_clicks_toggle_view_state_and_painted_checkmarks() { assert_eq!(menu.toggled("Pixel Snapping Options…"), None); } +#[test] +fn type_menu_offers_only_conversions_that_apply_to_selected_text() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + + fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + model::refresh(app, ui.ctx()); + craft::menu::MenuBarUi::new(&app.menus.laid).show(ui); + } + + const TO_AREA: &str = "Convert To Area Type"; + const TO_POINT: &str = "Convert To Point Type"; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let point = app.run("text.create", json!({"x": 20, "y": 40, "text": "Point type"})).unwrap()["id"].clone(); + let area = app.run("text.create", json!({"x": 20, "y": 100, "text": "Area type", "area": {"width": 120, "height": 60}})).unwrap()["id"].clone(); + + app.run("select.set", json!({"ids": [point.clone()]})).unwrap(); + let mut menu = Panel::new(app, draw); + menu.click("Type"); + assert!(menu.menu_item_enabled(TO_AREA)); + assert!(!menu.shows_role(TO_POINT, Role::MENU_ITEM)); + menu.click_menu_item(TO_AREA); + menu.click("Type"); + assert!(menu.menu_item_enabled(TO_POINT)); + assert!(!menu.shows_role(TO_AREA, Role::MENU_ITEM)); + menu.click_menu_item(TO_POINT); + menu.click("Type"); + assert!(menu.menu_item_enabled(TO_AREA)); + assert!(!menu.shows_role(TO_POINT, Role::MENU_ITEM)); + menu.click("Type"); + + menu.app().run("select.set", json!({"ids": [point, area]})).unwrap(); + menu.click("Type"); + assert!(menu.menu_item_enabled(TO_AREA)); + assert!(menu.menu_item_enabled(TO_POINT)); + menu.click("Type"); + + menu.app().run("select.set", json!({"ids": []})).unwrap(); + menu.click("Type"); + assert!(!menu.shows_role(TO_AREA, Role::MENU_ITEM)); + assert!(!menu.shows_role(TO_POINT, Role::MENU_ITEM)); +} + /// The Window menu keeps one check column: the labels of checked and unchecked panels, of plain /// commands and of submenus all start at the same x. #[test] From e29814c6dc813da29a68d26595c085a2cca51f84 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Fri, 4 Dec 2026 19:53:47 +0530 Subject: [PATCH 44/88] Borrow the selected text object from its node --- crates/ui-egui/src/menus/state.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index f00d98a243..c102276b0b 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -16,7 +16,7 @@ fn selected_text(app: &VectorcraftApp, matches_kind: fn(&TextKind) -> bool) -> O && let NodeKind::Text(text) = &child.kind && matches_kind(&text.kind) { - found = Some(text); + found = Some(text.as_ref()); } }); if found.is_some() { From eb4b84e601f3c30a9b909d9c3f6a1cfd87c7d56b Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:22:43 +0530 Subject: [PATCH 45/88] Type menu: share conversion availability across commands --- crates/engine/src/cmd/typemenu.rs | 18 ++++++++- crates/engine/src/tests/menucmds.rs | 37 ++++++++++++++--- crates/ui-egui/src/menus/state.rs | 61 ++++++++++++----------------- crates/ui-egui/src/menus/tests.rs | 17 +++++++- 4 files changed, 89 insertions(+), 44 deletions(-) diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index 70aa0ee07c..81f5c7a5ef 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -2,6 +2,8 @@ //! Options, Dynamic Text, Fill with Placeholder Text, Insert Special/Whitespace/Break characters) //! and the text commands of the Edit menu (Find and Replace, Find Next, Paste without Formatting). +use std::ops::ControlFlow; + use serde_json::{Value, json}; use vectorcraft_doc::{AreaFit, CharStyle, Document, Justify, LockedArtboards, Node, NodeId, NodeKind, Quotes, TextKind, TextObject, TextRun}; use vectorcraft_geom::{Affine, Rect, shapes}; @@ -40,7 +42,7 @@ pub fn specs() -> Vec { ["Type"], None, "{ids?|id?} point type → area type framed by its current layout bounds → {ids}", - has_selection, + |s| has_selected_text_kind(s, |kind| matches!(kind, TextKind::Point), "select point type"), to_area ), cmd!( @@ -49,7 +51,7 @@ pub fn specs() -> Vec { ["Type"], None, "{ids?|id?} area type → point type; soft line wraps become line breaks, a frame of threaded text leaves its thread with the text it holds, and Dynamic Text (Block) is turned off, keeping the sizes it set → {ids}", - has_selection, + |s| has_selected_text_kind(s, |kind| matches!(kind, TextKind::Area { .. }), "select area type"), to_point ), cmd!( @@ -154,6 +156,18 @@ pub fn specs() -> Vec { ] } +/// A selected object or one of its descendants has the source kind a conversion needs. +fn has_selected_text_kind(s: &Session, matches_kind: fn(&TextKind) -> bool, reason: &str) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + let found = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).any(|node| { + node.try_walk(&mut |child| { + if matches!(&child.kind, NodeKind::Text(text) if matches_kind(&text.kind)) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) } + }) + .is_break() + }); + found.then_some(()).ok_or_else(|| reason.into()) +} + /// Text objects among `ids` and their descendants. pub(crate) fn text_ids(d: &Document, ids: &[NodeId]) -> Vec { let paths = d.index_paths(ids.iter().copied()); diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 6896802a68..78c0578678 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -4275,19 +4275,44 @@ fn convert_point_area_roundtrip() { assert_eq!(tt.plain_text(), "Some words"); } -/// Convert To Area Type with no point type selected, and Convert To Point Type with no area type -/// selected, record no undo step and reply with the objects. With point type and area type -/// selected, Convert To Area Type converts the point type in one undo step, and Convert To Point -/// Type then converts both in another. #[test] -fn converting_type_to_the_kind_it_is_records_no_undo_step() { +fn type_conversion_availability_requires_its_source_kind() { + let mut s = session(); + let point = text(&mut s, "Point"); + let area = id_of(&s.execute("text.create", &json!({"x": 0, "y": 100, "text": "Area", "area": {"width": 100, "height": 50}})).unwrap()); + let rectangle = rect(&mut s, 200.0, 50.0, 20.0, 20.0); + let to_area = find_command("type.convertToAreaType").unwrap(); + let to_point = find_command("type.convertToPointType").unwrap(); + for (selection, can_convert_to_area, can_convert_to_point) in + [(&[point][..], true, false), (&[area][..], false, true), (&[rectangle][..], false, false), (&[area, point][..], true, true)] + { + sel(&mut s, selection); + for (spec, can_convert) in [(to_area, can_convert_to_area), (to_point, can_convert_to_point)] { + let info = spec.info(&s); + assert_eq!(info.enabled, can_convert, "{} on {selection:?}", info.id); + assert_eq!(info.disabled_reason.is_some(), !can_convert, "{} on {selection:?}", info.id); + } + } + + sel(&mut s, &[rectangle, point]); + let group = id_of(&s.execute("object.group", &json!({})).unwrap()); + sel(&mut s, &[group]); + assert!(to_area.info(&s).enabled); + assert!(!to_point.info(&s).enabled); +} + +/// An inapplicable conversion is disabled and leaves undo history intact. With point type and +/// area type selected, Convert To Area Type converts the point type in one undo step, and +/// Convert To Point Type then converts both in another. +#[test] +fn inapplicable_type_conversions_record_no_undo_step() { let mut s = session(); let p = text(&mut s, "Point"); let a = id_of(&s.execute("text.create", &json!({"x": 0, "y": 100, "text": "Area", "area": {"width": 100, "height": 50}})).unwrap()); for (c, id) in [("type.convertToAreaType", a), ("type.convertToPointType", p)] { select_with_a_step_to_redo(&mut s, &[id]); let before = history(&s); - assert_eq!(s.execute(c, &json!({})).unwrap(), json!({"ids": [id.0]}), "{c}"); + assert!(matches!(s.execute(c, &json!({})), Err(EngineError::Disabled(..))), "{c}"); assert_eq!(history(&s), before, "{c}"); } for c in ["type.convertToAreaType", "type.convertToPointType"] { diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index c102276b0b..d04f5d488a 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -4,37 +4,6 @@ use super::{Brightness, Value, VectorcraftApp}; use crate::i18n::LangExt as _; use craft::keymap::{Chord, CommandRef}; use craft::ui::runtime::commands; -use vectorcraft_engine::doc::{NodeKind, TextKind, TextObject}; - -/// The first matching text object among the selection and its descendants, in command order. -fn selected_text(app: &VectorcraftApp, matches_kind: fn(&TextKind) -> bool) -> Option<&TextObject> { - let st = app.session.active()?; - for node in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { - let mut found = None; - node.walk(&mut |child| { - if found.is_none() - && let NodeKind::Text(text) = &child.kind - && matches_kind(&text.kind) - { - found = Some(text.as_ref()); - } - }); - if found.is_some() { - return found; - } - } - None -} - -/// Conversion rows in the Type menu require an object of the source kind. -fn type_conversion_hidden(app: &VectorcraftApp, id: &str) -> bool { - let matches_kind: fn(&TextKind) -> bool = match id { - "type.convertToAreaType" => |kind| matches!(kind, TextKind::Point), - "type.convertToPointType" => |kind| matches!(kind, TextKind::Area { .. }), - _ => return false, - }; - selected_text(app, matches_kind).is_none() -} /// Checked state for toggle items. pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { @@ -50,6 +19,26 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { let v = &app.ui.view; // An item that can be on or off is `Some` whatever the document and selection (off with none): // the macOS menu bar can't change an item's kind without rebuilding. + // The first type object of a kind `kinds` takes among the selected objects and the objects + // inside them, in the order the type commands act on them. + let selected_text = |kinds: fn(&vectorcraft_engine::doc::TextKind) -> bool| { + let st = app.session.active()?; + let mut found = None; + for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { + n.walk(&mut |c| { + if found.is_none() + && let vectorcraft_engine::doc::NodeKind::Text(t) = &c.kind + && kinds(&t.kind) + { + found = Some(t); + } + }); + if found.is_some() { + break; + } + } + found + }; Some(match id { "type.orientation.vertical" | "type.orientation.horizontal" => { crate::panels::character::shared_text_flag(app, |t| t.vertical) == Some(id == "type.orientation.vertical") @@ -57,14 +46,14 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { "type.opticalMarginAlignment" => crate::panels::character::shared_text_flag(app, |t| t.optical_margin) == Some(true), // Dynamic Text of the first selected type, which the item turns the other way (point type // counts as off: the item turns it into area type with Block on). - "type.dynamicText" => selected_text(app, |_| true).is_some_and(|t| t.dynamic_text && !matches!(t.kind, TextKind::Point)), + "type.dynamicText" => selected_text(|_| true).is_some_and(|t| t.dynamic_text && !matches!(t.kind, vectorcraft_engine::doc::TextKind::Point)), "view.outline" => app.outline_view(), "view.pixelPreview" => v.pixel_preview, "view.trimView" => v.trim_view, "view.snapToPixel" => v.snap_to_pixel, "view.snapToGlyph" => v.snap_to_glyph, // Type on a Path effect of the selected path type. - "type.pathOptions" if p.get("effect").is_some() => selected_text(app, |k| matches!(k, TextKind::OnPath { .. })) + "type.pathOptions" if p.get("effect").is_some() => selected_text(|k| matches!(k, vectorcraft_engine::doc::TextKind::OnPath { .. })) .is_some_and(|t| p.get("effect").and_then(Value::as_str) == Some(t.path_effect.id())), "view.smartGuides" => v.smart_guides, "edit.autoSpellCheck" => v.auto_spell_check, @@ -183,7 +172,7 @@ fn east_asian_hidden(app: &VectorcraftApp, id: &str) -> bool { /// How the menus show item `id` (params `p`) now: (enabled, checked: `Some` for an item that is on /// or off), or `None` while they leave it out: an empty slot ([`hidden_when_disabled`]), an item /// another stands in for ([`swapped_out`]) or an East Asian item with those options hidden -/// ([`east_asian_hidden`]), or a type conversion without eligible text ([`type_conversion_hidden`]). +/// ([`east_asian_hidden`]), or a disabled type conversion. pub fn shown_state(app: &VectorcraftApp, id: &str, p: &Value) -> Option<(bool, Option)> { shown_state_with(app, id, p, &mut |id| why_off(app, id)) } @@ -199,7 +188,9 @@ pub(crate) fn shown_state_with( let en = why_off(id).is_none() && (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p)) && (!vectorcraft_engine::cmd::plugin::is_command_id(id) || crate::dialogs::plugin::canvas_item_enabled(app, id, p)); - if (!en && hidden_when_disabled(id)) || swapped_out(id, why_off) || east_asian_hidden(app, id) || type_conversion_hidden(app, id) { + // Keep conversion labels in the catalog while leaving unavailable rows out of the Type menu. + let hide_disabled = hidden_when_disabled(id) || matches!(id, "type.convertToAreaType" | "type.convertToPointType"); + if (!en && hide_disabled) || swapped_out(id, why_off) || east_asian_hidden(app, id) { return None; } Some((en, checked(app, id, p))) diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index df23d8edf9..51ac2dd658 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -181,6 +181,7 @@ fn type_menu_offers_only_conversions_that_apply_to_selected_text() { app.run("file.new", json!({})).unwrap(); let point = app.run("text.create", json!({"x": 20, "y": 40, "text": "Point type"})).unwrap()["id"].clone(); let area = app.run("text.create", json!({"x": 20, "y": 100, "text": "Area type", "area": {"width": 120, "height": 60}})).unwrap()["id"].clone(); + let rectangle = app.run("shape.rectangle", json!({"x": 160, "y": 40, "width": 40, "height": 40})).unwrap()["id"].clone(); app.run("select.set", json!({"ids": [point.clone()]})).unwrap(); let mut menu = Panel::new(app, draw); @@ -197,7 +198,7 @@ fn type_menu_offers_only_conversions_that_apply_to_selected_text() { assert!(!menu.shows_role(TO_POINT, Role::MENU_ITEM)); menu.click("Type"); - menu.app().run("select.set", json!({"ids": [point, area]})).unwrap(); + menu.app().run("select.set", json!({"ids": [point.clone(), area]})).unwrap(); menu.click("Type"); assert!(menu.menu_item_enabled(TO_AREA)); assert!(menu.menu_item_enabled(TO_POINT)); @@ -207,6 +208,20 @@ fn type_menu_offers_only_conversions_that_apply_to_selected_text() { menu.click("Type"); assert!(!menu.shows_role(TO_AREA, Role::MENU_ITEM)); assert!(!menu.shows_role(TO_POINT, Role::MENU_ITEM)); + menu.click("Type"); + + menu.app().run("select.set", json!({"ids": [rectangle.clone()]})).unwrap(); + menu.click("Type"); + assert!(!menu.shows_role(TO_AREA, Role::MENU_ITEM)); + assert!(!menu.shows_role(TO_POINT, Role::MENU_ITEM)); + menu.click("Type"); + + menu.app().run("select.set", json!({"ids": [rectangle, point]})).unwrap(); + let group = menu.app().run("object.group", json!({})).unwrap()["id"].clone(); + menu.app().run("select.set", json!({"ids": [group]})).unwrap(); + menu.click("Type"); + assert!(menu.menu_item_enabled(TO_AREA)); + assert!(!menu.shows_role(TO_POINT, Role::MENU_ITEM)); } /// The Window menu keeps one check column: the labels of checked and unchecked panels, of plain From 44964cb01998ad6605e50a359cf816de04c7b205 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 07:56:41 -0800 Subject: [PATCH 46/88] Swatches: rows dragged from the list are checked through the name index While rows are dragged from the Swatches list, the panel checks them against the document on every pass and after every command. Each check looked every dragged row up with Document::swatch, and a color group row with a scan of the groups, so a drag of every swatch did work that grew with the square of the swatch count. - HeldRow::of and HeldRow::unchanged_in look names up in a SwatchIndex. follow passes the panel's index of the current document, and checked builds one index for each earlier state whose swatch lists differ from the current ones, and none for a state that shares them. - DragStart carries the panel's index, so starting a drag builds no index for the current document. - New tests count the lookup work of one drag check with 200 and with 400 swatches, check that a drag check after an edit of the art and a drag start build no index, and check that highlighting a selection looks each selected name up once in the index. --- crates/ui-egui/src/panels/swatches.rs | 2 +- crates/ui-egui/src/panels/swatches/dnd.rs | 77 ++++++++++++------- crates/ui-egui/src/panels/swatches/index.rs | 2 +- crates/ui-egui/src/panels/swatches/tests.rs | 2 +- .../src/panels/swatches/tests/lookups.rs | 49 ++++++++++++ 5 files changed, 102 insertions(+), 30 deletions(-) diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 80cc35c710..0f76b62f32 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -488,7 +488,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { let revision = (st.uid, st.revision); let lit = highlighted(&st.doc, &index, &base); let doc = Arc::clone(&st.doc); - let start = dnd::DragStart::of(st); + let start = dnd::DragStart::of(st, Arc::clone(&index)); // The row menu, the drop rules and the drag payload read the document, its reverts and the drag start alone, so // the browser's rows replay while this version holds. let host = start.version(st.revision); diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index ff32806f8f..934233cd7c 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -2,7 +2,7 @@ use std::collections::HashSet; use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::{Arc, Weak}; -use super::{Document, Paint, PanelDrag, REGISTRATION, Swatch, Value, VectorcraftApp, json, name_of, swatch_params}; +use super::{Document, IndexCache, Paint, PanelDrag, REGISTRATION, Swatch, SwatchIndex, Value, VectorcraftApp, json, name_of, swatch_params}; use crate::panel_drag::SwatchRows; use craft::color_ui::ui::SwatchKey; use craft::keymap::Mods; @@ -86,18 +86,18 @@ enum HeldRow { } impl HeldRow { - /// Row `name` of `d`: its swatch, else the colour group of that name. - fn of(d: &Document, name: &str) -> Option { - match d.swatch(name) { + /// Row `name` of `d`: its swatch, else the colour group of that name. `index` holds the names of `d`. + fn of(d: &Document, index: &SwatchIndex, name: &str) -> Option { + match index.swatch(d, name) { Some(w) => Some(HeldRow::Swatch(w.clone())), - None => d.swatch_groups.iter().find(|g| g.name == name).cloned().map(HeldRow::Group), + None => index.groups(d, name).next().cloned().map(HeldRow::Group), } } - /// Whether `d` holds this row unchanged. - fn unchanged_in(&self, d: &Document) -> bool { + /// Whether `d` holds this row unchanged. `index` holds the names of `d`. + fn unchanged_in(&self, d: &Document, index: &SwatchIndex) -> bool { match self { - HeldRow::Swatch(w) => d.swatch(&w.name) == Some(w), - HeldRow::Group(g) => d.swatch_groups.iter().any(|x| x == g), + HeldRow::Swatch(w) => index.swatch(d, &w.name) == Some(w), + HeldRow::Group(g) => index.groups(d, &g.name).any(|x| x == g), } } } @@ -112,20 +112,23 @@ fn steps(st: &DocState) -> [u64; 4] { /// A document as a drag from the list finds it: its `uid` and its count of File › Revert /// ([`DocState::reverts`]), its state, its newest steps ([`steps`]) and the state undoing the newest -/// undo step gives back (that step's document). +/// undo step gives back (that step's document), with the names of the document's swatches and color groups. #[derive(Clone)] pub(super) struct DragStart { uid: u64, reverts: u64, doc: Arc, + index: Arc, steps: [u64; 4], back: Option>, } impl DragStart { - pub(super) fn of(st: &DocState) -> Self { + /// The start of a drag in `st`; `index` holds the names of `st`'s document, and a new one is built when it does not. + pub(super) fn of(st: &DocState, index: Arc) -> Self { + let index = if index.of(&st.doc) { index } else { Arc::new(SwatchIndex::new(&st.doc)) }; let back = st.history.undo.last().map(|e| Arc::clone(&e.doc)); - DragStart { uid: st.uid, reverts: st.reverts, doc: Arc::clone(&st.doc), steps: steps(st), back } + DragStart { uid: st.uid, reverts: st.reverts, doc: Arc::clone(&st.doc), index, steps: steps(st), back } } /// A version of this start in the document's `revision` ([`DocState::revision`]): it changes with @@ -139,8 +142,12 @@ impl DragStart { /// Rows `names` as this document holds them. fn rows(&self, names: &[String]) -> HeldRows { - let rows: Vec<_> = names.iter().map(|n| (n.clone(), HeldRow::of(&self.doc, n))).collect(); - let back = rows.iter().map(|(_, r)| r.as_ref().zip(self.back.as_deref()).is_some_and(|(r, d)| r.unchanged_in(d))).collect(); + let rows: Vec<_> = names.iter().map(|n| (n.clone(), HeldRow::of(&self.doc, &self.index, n))).collect(); + let back = self.back.as_deref().map(|d| { + let index = if self.index.of(d) { Arc::clone(&self.index) } else { Arc::new(SwatchIndex::new(d)) }; + (d, index) + }); + let back = rows.iter().map(|(_, r)| r.as_ref().zip(back.as_ref()).is_some_and(|(r, (d, index))| r.unchanged_in(d, index))).collect(); HeldRows { uid: self.uid, reverts: self.reverts, doc: Arc::downgrade(&self.doc), steps: self.steps, rows, back } } } @@ -193,8 +200,8 @@ impl std::fmt::Debug for HeldRows { /// between are not known, and every row is left out of the drop. The panel checks the rows on every /// pass and after every command the app runs ([`follow_drag`]), so only the steps of one command go /// unseen. One undo step is one change: the states between the commands of a `command.batch` are -/// not kept, and a row the batch leaves as it found it stays in the drop. -fn checked(held: HeldRows, st: &DocState) -> HeldRows { +/// not kept, and a row the batch leaves as it found it stays in the drop. `index` holds the names of `st`'s document. +fn checked(held: HeldRows, st: &DocState, index: &Arc) -> HeldRows { let now = steps(st); let same = std::ptr::eq(held.doc.as_ptr(), Arc::as_ptr(&st.doc)); if same && held.steps == now { @@ -222,15 +229,30 @@ fn checked(held: HeldRows, st: &DocState) -> HeldRows { Some(i) => (undo.get(i..), false), None => (after(undo, below).and_then(|i| undo.get(i..)), true), }; - let unchanged = |r: &HeldRow, b: &[HistoryEntry]| b.iter().chain(left).all(|e| r.unchanged_in(&e.doc)) && r.unchanged_in(&st.doc); - let rows: Vec<_> = held - .rows - .into_iter() - .zip(held.back) - .map(|((name, row), back)| (name, row.filter(|r| (back || !undone) && between.is_some_and(|b| unchanged(r, b))))) - .collect(); - let last = undo.last(); - let back = rows.iter().map(|(_, r)| r.as_ref().zip(last).is_some_and(|(r, e)| r.unchanged_in(&e.doc))).collect(); + // Each state is looked at once for every row still held, and states with the same swatch lists share an index. + let mut kept: Vec = held.rows.iter().zip(&held.back).map(|((_, row), back)| row.is_some() && (*back || !undone)).collect(); + let indexes = IndexCache::default(); + let index_of = |d: &Document| if index.of(d) { Arc::clone(index) } else { indexes.get(d) }; + match between { + Some(b) => { + for e in b.iter().chain(left) { + if !kept.contains(&true) { + break; + } + let at = index_of(&e.doc); + for ((_, row), keep) in held.rows.iter().zip(&mut kept) { + *keep = *keep && row.as_ref().is_some_and(|r| r.unchanged_in(&e.doc, &at)); + } + } + for ((_, row), keep) in held.rows.iter().zip(&mut kept) { + *keep = *keep && row.as_ref().is_some_and(|r| r.unchanged_in(&st.doc, index)); + } + } + None => kept.fill(false), + } + let rows: Vec<_> = held.rows.into_iter().zip(kept).map(|((name, row), keep)| (name, row.filter(|_| keep))).collect(); + let last = undo.last().filter(|_| rows.iter().any(|(_, row)| row.is_some())).map(|e| (&*e.doc, index_of(&e.doc))); + let back = rows.iter().map(|(_, r)| r.as_ref().zip(last.as_ref()).is_some_and(|(r, (d, at))| r.unchanged_in(d, at))).collect(); HeldRows { uid: held.uid, reverts: held.reverts, doc: Arc::downgrade(&st.doc), steps: now, rows, back } } @@ -243,17 +265,18 @@ pub(super) fn follow(app: &mut VectorcraftApp, r: &SwatchRows) -> Vec { if st.uid != r.held.uid || st.reverts != r.held.reverts { return vec![]; } + let index = app.ui.swatches_panel.index(&st.doc); let kept = &mut app.ui.swatches_panel.drag; let from = match kept { Some((start, now)) if Arc::ptr_eq(start, &r.held) => now.clone(), _ => (*r.held).clone(), }; - let now = checked(from, st); + let now = checked(from, st, &index); let names = if now.rows.len() == r.names.len() { r.names .iter() .zip(&now.rows) - .filter(|(n, (h, row))| *n == h && row.as_ref().is_some_and(|row| row.unchanged_in(&st.doc))) + .filter(|(n, (h, row))| *n == h && row.as_ref().is_some_and(|row| row.unchanged_in(&st.doc, &index))) .map(|(n, _)| n.clone()) .collect() } else { diff --git a/crates/ui-egui/src/panels/swatches/index.rs b/crates/ui-egui/src/panels/swatches/index.rs index e091299fda..85dd51e24b 100644 --- a/crates/ui-egui/src/panels/swatches/index.rs +++ b/crates/ui-egui/src/panels/swatches/index.rs @@ -42,7 +42,7 @@ impl SwatchIndex { } /// Whether the index holds the names of `d`: `d` has the swatch lists the index was built from. - fn of(&self, d: &Document) -> bool { + pub(super) fn of(&self, d: &Document) -> bool { std::ptr::eq(Weak::as_ptr(&self.listed), &*d.swatches) && std::ptr::eq(Weak::as_ptr(&self.grouped), &*d.swatch_groups) } diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index fba8f9fef5..2ce6903e02 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -97,7 +97,7 @@ fn dropped_below(app: &mut VectorcraftApp, drag: PanelDrag, mods: Mods) { /// The drag the row `name` starts in the active document, carrying rows `names`. fn rows_drag(app: &VectorcraftApp, name: &str, names: &[&str]) -> PanelDrag { - let start = dnd::DragStart::of(app.session.active().expect("a document")); + let start = dnd::DragStart::of(app.session.active().expect("a document"), index_of(app)); dnd::drag_of(&start, &key_of(app, name), names.iter().map(|n| n.to_string()).collect()) } diff --git a/crates/ui-egui/src/panels/swatches/tests/lookups.rs b/crates/ui-egui/src/panels/swatches/tests/lookups.rs index d10e31d938..039915c0d5 100644 --- a/crates/ui-egui/src/panels/swatches/tests/lookups.rs +++ b/crates/ui-egui/src/panels/swatches/tests/lookups.rs @@ -63,6 +63,55 @@ fn a_hovered_pass_looks_up_names_in_proportion_to_the_swatch_count() { assert!(large <= 2 * small, "app name lookup work in one pass: {small} with 200 swatches, {large} with 400"); } +/// The app's name lookup work in one check of a drag of every swatch of [`crowded`]`(n)` from the list, after an edit +/// of the art: the drag's rows are checked against the new undo step's state and the current one. +fn lookups_in_a_drag_check(n: usize) -> usize { + let mut app = crowded(n); + let names: Vec = doc(&app).swatches_iter().map(|s| s.name.clone()).collect(); + let rows: Vec<&str> = names.iter().map(String::as_str).collect(); + index_of(&app); + index::counts::take(); + let drag = rows_drag(&app, rows[0], &rows); + assert_eq!(index::counts::take().1, 0, "starting a drag builds no index when the panel's index exists"); + let PanelDrag::Paint { rows: Some(held), .. } = &drag else { panic!("a rows drag") }; + assert_eq!(dnd::follow(&mut app, held), names, "the drag holds every swatch"); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + index::counts::take(); + let scans = vectorcraft_doc::swatches::swatch_scans(); + let kept = dnd::follow(&mut app, held); + let (lookups, builds) = index::counts::take(); + let work = lookups + vectorcraft_doc::swatches::swatch_scans() - scans; + assert_eq!(builds, 0, "an edit of the art alone builds no index during the drag check"); + assert_eq!(kept, names, "an edit of the art keeps every row"); + work +} + +/// Checking a drag of every swatch from the list, as the panel does on every pass and after every command, does name +/// lookup work in proportion to the swatch count: twice the swatches, at most twice the work. +#[test] +fn a_drag_check_looks_up_names_in_proportion_to_the_swatch_count() { + let small = lookups_in_a_drag_check(200); + let large = lookups_in_a_drag_check(400); + assert!(small > 0, "the check looks names up"); + assert!(large <= 2 * small, "name lookup work in one drag check: {small} with 200 swatches, {large} with 400"); +} + +/// Highlighting a selection looks each selected name up once in the index, however many color groups the document +/// holds, and lights every selected name. +#[test] +fn highlighting_looks_each_selected_name_up_once() { + for n in [200, 400] { + let app = crowded(n); + let sel = selected(&app); + let st = app.session.active().unwrap(); + let index = index_of(&app); + index::counts::take(); + let lit = highlighted(&st.doc, &index, &sel); + assert_eq!(index::counts::take().0, sel.len(), "index lookups to highlight {} selected names", sel.len()); + assert_eq!(lit.len(), sel.len(), "every selected name is lit"); + } +} + /// Passes at one revision of the document build no index; after a swatch edit the panel builds one that finds the new /// swatch, the passes that follow build none, and an edit of the art alone builds none. #[test] From 0eaa1adba3aa8eac307937bf89fd0ba3a30a4f79 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 10:50:07 -0800 Subject: [PATCH 47/88] Swatches: a one-row drag checks an earlier swatch list without indexing it When a drag of rows from the Swatches list starts, or is checked after a command, the rows are compared with the states of the document before the newest undo steps. When such a state holds other swatch lists than the current document, the check built a name index of that whole state even for a single dragged row. A single row is now looked up directly in that state, and an index is built only when more than one row is checked. A new test starts a one-row drag after a swatch edit and checks that no index is built and that the drag holds its row. --- crates/ui-egui/src/panels/swatches/dnd.rs | 60 ++++++++++++------- .../src/panels/swatches/tests/lookups.rs | 13 ++++ 2 files changed, 51 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index 934233cd7c..f8055527a9 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -86,22 +86,37 @@ enum HeldRow { } impl HeldRow { - /// Row `name` of `d`: its swatch, else the colour group of that name. `index` holds the names of `d`. - fn of(d: &Document, index: &SwatchIndex, name: &str) -> Option { - match index.swatch(d, name) { + /// Row `name` of `d`: its swatch, else the color group of that name. With no index, looks directly in `d`. + fn of(d: &Document, index: Option<&SwatchIndex>, name: &str) -> Option { + match index.map_or_else(|| d.swatch(name), |index| index.swatch(d, name)) { Some(w) => Some(HeldRow::Swatch(w.clone())), - None => index.groups(d, name).next().cloned().map(HeldRow::Group), + None => index + .map_or_else(|| d.swatch_groups.iter().find(|g| g.name == name), |index| index.groups(d, name).next()) + .cloned() + .map(HeldRow::Group), } } - /// Whether `d` holds this row unchanged. `index` holds the names of `d`. - fn unchanged_in(&self, d: &Document, index: &SwatchIndex) -> bool { + /// Whether `d` holds this row unchanged. With no index, looks directly in `d`. + fn unchanged_in(&self, d: &Document, index: Option<&SwatchIndex>) -> bool { match self { - HeldRow::Swatch(w) => index.swatch(d, &w.name) == Some(w), - HeldRow::Group(g) => index.groups(d, &g.name).any(|x| x == g), + HeldRow::Swatch(w) => index.map_or_else(|| d.swatch(&w.name), |index| index.swatch(d, &w.name)) == Some(w), + HeldRow::Group(g) => index.map_or_else(|| d.swatch_groups.iter().any(|x| x == g), |index| index.groups(d, &g.name).any(|x| x == g)), } } } +/// The index that checks `rows` held rows against `d`: `index` when it holds the names of `d`, else an index of `d` +/// from `cache` for more than one row, else none, so that a single row is looked up directly in `d`. +fn checking_index(d: &Document, index: &Arc, cache: &IndexCache, rows: usize) -> Option> { + if index.of(d) { + Some(Arc::clone(index)) + } else if rows > 1 { + Some(cache.get(d)) + } else { + None + } +} + /// The newest undo step of `st` and the one under it, and the next redo step and the one under it /// ([`HistoryEntry::serial`]), 0 for none. fn steps(st: &DocState) -> [u64; 4] { @@ -142,12 +157,12 @@ impl DragStart { /// Rows `names` as this document holds them. fn rows(&self, names: &[String]) -> HeldRows { - let rows: Vec<_> = names.iter().map(|n| (n.clone(), HeldRow::of(&self.doc, &self.index, n))).collect(); - let back = self.back.as_deref().map(|d| { - let index = if self.index.of(d) { Arc::clone(&self.index) } else { Arc::new(SwatchIndex::new(d)) }; - (d, index) - }); - let back = rows.iter().map(|(_, r)| r.as_ref().zip(back.as_ref()).is_some_and(|(r, (d, index))| r.unchanged_in(d, index))).collect(); + let rows: Vec<_> = names.iter().map(|n| (n.clone(), HeldRow::of(&self.doc, Some(&self.index), n))).collect(); + let count = rows.iter().filter(|(_, row)| row.is_some()).count(); + let indexes = IndexCache::default(); + let back = self.back.as_deref().map(|d| (d, checking_index(d, &self.index, &indexes, count))); + let back = + rows.iter().map(|(_, r)| r.as_ref().zip(back.as_ref()).is_some_and(|(r, (d, index))| r.unchanged_in(d, index.as_deref()))).collect(); HeldRows { uid: self.uid, reverts: self.reverts, doc: Arc::downgrade(&self.doc), steps: self.steps, rows, back } } } @@ -232,27 +247,28 @@ fn checked(held: HeldRows, st: &DocState, index: &Arc) -> HeldRows // Each state is looked at once for every row still held, and states with the same swatch lists share an index. let mut kept: Vec = held.rows.iter().zip(&held.back).map(|((_, row), back)| row.is_some() && (*back || !undone)).collect(); let indexes = IndexCache::default(); - let index_of = |d: &Document| if index.of(d) { Arc::clone(index) } else { indexes.get(d) }; match between { Some(b) => { for e in b.iter().chain(left) { - if !kept.contains(&true) { + let count = kept.iter().filter(|&&keep| keep).count(); + if count == 0 { break; } - let at = index_of(&e.doc); + let at = checking_index(&e.doc, index, &indexes, count); for ((_, row), keep) in held.rows.iter().zip(&mut kept) { - *keep = *keep && row.as_ref().is_some_and(|r| r.unchanged_in(&e.doc, &at)); + *keep = *keep && row.as_ref().is_some_and(|r| r.unchanged_in(&e.doc, at.as_deref())); } } for ((_, row), keep) in held.rows.iter().zip(&mut kept) { - *keep = *keep && row.as_ref().is_some_and(|r| r.unchanged_in(&st.doc, index)); + *keep = *keep && row.as_ref().is_some_and(|r| r.unchanged_in(&st.doc, Some(index))); } } None => kept.fill(false), } let rows: Vec<_> = held.rows.into_iter().zip(kept).map(|((name, row), keep)| (name, row.filter(|_| keep))).collect(); - let last = undo.last().filter(|_| rows.iter().any(|(_, row)| row.is_some())).map(|e| (&*e.doc, index_of(&e.doc))); - let back = rows.iter().map(|(_, r)| r.as_ref().zip(last.as_ref()).is_some_and(|(r, (d, at))| r.unchanged_in(d, at))).collect(); + let count = rows.iter().filter(|(_, row)| row.is_some()).count(); + let last = undo.last().filter(|_| count > 0).map(|e| (&*e.doc, checking_index(&e.doc, index, &indexes, count))); + let back = rows.iter().map(|(_, r)| r.as_ref().zip(last.as_ref()).is_some_and(|(r, (d, at))| r.unchanged_in(d, at.as_deref()))).collect(); HeldRows { uid: held.uid, reverts: held.reverts, doc: Arc::downgrade(&st.doc), steps: now, rows, back } } @@ -276,7 +292,7 @@ pub(super) fn follow(app: &mut VectorcraftApp, r: &SwatchRows) -> Vec { r.names .iter() .zip(&now.rows) - .filter(|(n, (h, row))| *n == h && row.as_ref().is_some_and(|row| row.unchanged_in(&st.doc, &index))) + .filter(|(n, (h, row))| *n == h && row.as_ref().is_some_and(|row| row.unchanged_in(&st.doc, Some(&index)))) .map(|(n, _)| n.clone()) .collect() } else { diff --git a/crates/ui-egui/src/panels/swatches/tests/lookups.rs b/crates/ui-egui/src/panels/swatches/tests/lookups.rs index 039915c0d5..ff51d78b46 100644 --- a/crates/ui-egui/src/panels/swatches/tests/lookups.rs +++ b/crates/ui-egui/src/panels/swatches/tests/lookups.rs @@ -96,6 +96,19 @@ fn a_drag_check_looks_up_names_in_proportion_to_the_swatch_count() { assert!(large <= 2 * small, "name lookup work in one drag check: {small} with 200 swatches, {large} with 400"); } +/// Starting a one-row drag after a swatch edit uses the panel's index and checks the undo state without building an index. +#[test] +fn a_one_row_drag_after_a_swatch_edit_builds_no_name_index() { + let mut app = crowded(200); + app.run("swatch.new", json!({"name": "Fresh", "color": "#336699"})).unwrap(); + index_of(&app); + index::counts::take(); + let drag = rows_drag(&app, "Ink 0", &["Ink 0"]); + assert_eq!(index::counts::take().1, 0, "starting a one-row drag builds no index after a swatch edit"); + let PanelDrag::Paint { rows: Some(held), .. } = &drag else { panic!("a rows drag") }; + assert_eq!(dnd::follow(&mut app, held), ["Ink 0"], "the drag holds its row"); +} + /// Highlighting a selection looks each selected name up once in the index, however many color groups the document /// holds, and lights every selected name. #[test] From 19f01cc673b046e42603be92c0706264ac623d6c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 12:12:43 -0800 Subject: [PATCH 48/88] Type: Select All keeps an unfinished Character value for the same characters The Character panel and Properties keyed a Type tool range by the tool's raw offsets. Select All stores an end past the text, so a range dragged over the whole text and Select All gave different keys and dropped a value typed for the same characters. character_target now resolves the range the way the bars' Font Size field does, and that field uses it as well, so the two keys come from one function: the range is clamped to the stored text, or to the length the text has with unapplied typing while Real-time Drawing is off. The Character controls keep a caret's offset for Kerning; the Font Size field keys a caret and a range over the whole text as all of the text. --- crates/ui-egui/src/panels/character.rs | 75 ++++++++------------ crates/ui-egui/src/panels/character/tests.rs | 20 ++++++ 2 files changed, 51 insertions(+), 44 deletions(-) diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 03fa1ec8d0..65081baa4f 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -338,19 +338,37 @@ pub(crate) fn format_target_kept(app: &mut VectorcraftApp) -> Result Option<(u64, u64, u64, FormatTarget)> { +/// What a character field edits, as its edit target: the document, how many times File › Revert +/// and Undo or Redo replaced its content (after which a node id can name another object), and the +/// text the changes go to ([`format_target`]): the range or story the Type tool has selected, else +/// the selected stories. With `caret` set, a caret keeps its offset, since the Character panel's +/// Kerning field sets the pair at the caret ([`set_kerning`]). Without it, a caret and a range over +/// the whole text both key as all of the text, which is what `text.setStyle` changes at a caret +/// ([`range_style`]). A field drops a value typed and not yet committed when this changes, even +/// where the new text has the same value. +fn character_target(app: &VectorcraftApp, caret: bool) -> Option<(u64, u64, u64, FormatTarget)> { let st = app.session.active()?; + // The range [`text_editing`] clamps to the stored text, or, while Real-time Drawing off leaves + // typing unapplied, the Type tool's own offsets, which can reach into that typing, clamped to + // the length the text has with it ([`pending_text_len`]). The same characters key the same + // whether a drag or Select All, whose end lies past the text, selected them. let o = app.session.tool_options(); let offset = |k: &str| o.get(k).and_then(Value::as_u64).map_or(0, |v| v as usize); - let editing = text_editing(app).map(|(id, _, _)| (id, offset("start"), offset("end"))); + let editing = text_editing(app).map(|(id, a, b)| { + let unapplied_typing = o.get("typing").and_then(Value::as_bool) == Some(true) + && st.interaction.as_ref().is_some_and(|it| it.label == "Typing" && it.preview.is_some() && std::sync::Arc::ptr_eq(&it.doc, &st.doc)); + let (a, b, len) = if unapplied_typing { + let (a, b) = (offset("start"), offset("end")); + pending_text_len(st, id).map_or((a, b, None), |len| (a.min(len), b.min(len), Some(len))) + } else { + let len = st.doc.node(id).and_then(|node| match &node.kind { + NodeKind::Text(t) => Some(vectorcraft_text::edit::runs_len(&t.runs)), + _ => None, + }); + (a, b, len) + }; + if caret || (b > a && !(a == 0 && len.is_some_and(|len| b >= len))) { (id, a, b) } else { (id, 0, 0) } + }); Some((st.uid, st.reverts, st.history_restores, format_target(app, editing))) } @@ -1246,7 +1264,7 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow let sets = font_menu::family_sets(hold.document.as_deref(), &hold.recently_added); let sample = font_menu::sample_text(app); let unit = type_unit(app); - let target = character_target(app); + let target = character_target(app, true); let mut source = FontPickerSource::new(catalog) .settings(Bind::bound(&mut hold.settings)) .filters(Bind::bound(&mut hold.filters)) @@ -1341,37 +1359,6 @@ fn snap_to_glyph(app: &mut VectorcraftApp, ui: &mut Ui) { }); } -/// What the bars' Font Size field edits, as its edit target: the document, how many times File › -/// Revert and Undo or Redo replaced its content (after which a node id can name another object), -/// and the text `text.setStyle` changes ([`format_target`]): the range or story the Type tool has -/// selected, all of the edited text at a caret, else the selected stories. The field drops a value -/// typed and not yet committed when this changes, even where the new text has the same size. -fn size_target(app: &VectorcraftApp) -> Option<(u64, u64, u64, FormatTarget)> { - let st = app.session.active()?; - // The range [`text_editing`] clamps to the stored text, or, while Real-time Drawing off leaves - // typing unapplied, the Type tool's own offsets, which can reach into that typing, clamped to - // the length the text has with it ([`pending_text_len`]). A caret changes the whole text - // wherever it is ([`range_style`]); a range over the whole text keys as a caret does. - let o = app.session.tool_options(); - let offset = |k: &str| o.get(k).and_then(Value::as_u64).map_or(0, |v| v as usize); - let editing = text_editing(app).map(|(id, a, b)| { - let unapplied_typing = o.get("typing").and_then(Value::as_bool) == Some(true) - && st.interaction.as_ref().is_some_and(|it| it.label == "Typing" && it.preview.is_some() && std::sync::Arc::ptr_eq(&it.doc, &st.doc)); - let (a, b, len) = if unapplied_typing { - let (a, b) = (offset("start"), offset("end")); - pending_text_len(st, id).map_or((a, b, None), |len| (a.min(len), b.min(len), Some(len))) - } else { - let len = st.doc.node(id).and_then(|node| match &node.kind { - NodeKind::Text(t) => Some(vectorcraft_text::edit::runs_len(&t.runs)), - _ => None, - }); - (a, b, len) - }; - if b > a && !(a == 0 && len.is_some_and(|len| b >= len)) { (id, a, b) } else { (id, 0, 0) } - }); - Some((st.uid, st.reverts, st.history_restores, format_target(app, editing))) -} - /// The byte length text `id` will have once the typing that Real-time Drawing off leaves unapplied /// is applied: the stored text with the `text.editRange` preview's range replaced by its runs. /// `None` for a frame of a threaded story, whose text can reflow from other frames, when the @@ -1398,9 +1385,9 @@ fn pending_text_len(st: &DocState, id: NodeId) -> Option { /// The Font Size field of the bars, named `name`: typed, stepped, scrubbed or picked from the /// presets, in the type unit, blank where the selected text's sizes differ. A value typed and not -/// yet committed stays with the text it was typed for ([`size_target`]). +/// yet committed stays with the text it was typed for ([`character_target`]). fn size_field(app: &mut VectorcraftApp, ui: &mut Ui, name: &'static str) { - let target = size_target(app); + let target = character_target(app, false); let unit = type_unit(app); let scale = unit_scale(unit); let units = Env::of(ui).units(); diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 887a93ca73..22b6114ce8 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -546,6 +546,26 @@ fn an_unfinished_character_value_does_not_reach_another_text_range() { } } +/// While the Type tool edits text, a range dragged over the whole text and Select All select the same +/// characters, so a value typed with one selected is kept when the other replaces it. +#[test] +fn an_unfinished_character_value_survives_select_all_over_the_same_characters() { + use crate::tests::panel_harness::Panel; + for (panel, draw, _) in character_draws() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Abcd", "size": 12})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 0, "caret": 4})); + let mut p = Panel::new(app, draw); + type_unfinished(&mut p, "Tracking"); + p.app().run("select.all", json!({})).unwrap(); + finish_typing(&mut p); + assert_eq!(run_values(&p.app(), id, |s| s.tracking), [("Abcd".to_string(), 4.0)], "{panel}: Select All keeps 3+"); + } +} + /// At a caret the Kerning field sets the pair at the caret, so a value typed there does not reach /// the pair at another caret position in the same text, though both pairs have the same kerning. #[test] From f32218ec96723977d1b307b67a3db571c1f14031 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 14:28:37 -0800 Subject: [PATCH 49/88] Agents: agent_folders shows the folders the open window enforces In front of the open window, plain `vectorcraft-cli mcp` answered `agent_folders` from the saved agent settings. When a saved folder names a deleted folder or a file, the window refuses every file, but the tool still listed that folder. The window now answers the new control method `agent.folders` with the automation roots its requests run inside (`read_folders` / `write_folders` when a kind has several), and the CLI passes that answer on. A window without the method still gets the saved settings. --- crates/mcp/src/agents.rs | 10 ++++++++-- crates/mcp/src/tests/agents.rs | 29 ++++++++++++++++++++++++++--- crates/ui-egui/src/agents.rs | 27 ++++++++++++++++++++++++++- crates/ui-egui/src/agents/tests.rs | 20 ++++++++++++++++++++ crates/ui-egui/src/control.rs | 8 +++++++- docs/mcp.md | 2 +- 6 files changed, 88 insertions(+), 8 deletions(-) diff --git a/crates/mcp/src/agents.rs b/crates/mcp/src/agents.rs index 8f7a8bc8b4..ba9a0b0fa3 100644 --- a/crates/mcp/src/agents.rs +++ b/crates/mcp/src/agents.rs @@ -310,7 +310,8 @@ impl LiveBackend { Self { live: shared::Live::new(shared_cfg), config_dir, read_settings, default_folder } } - /// The folders the open window lets agents use, as the window opens them. + /// The folders the open window lets agents use, read from the saved settings: the answer for a + /// window that doesn't report the folders it enforces itself. fn window_folders(&self) -> Value { folders_answer(&(self.read_settings)(&self.config_dir).folders_with(self.default_folder.as_deref())) } @@ -319,7 +320,12 @@ impl LiveBackend { impl Backend for LiveBackend { fn call(&mut self, method: &str, params: Value) -> Result { match self.live.resolve()? { - Route::Window(_) if method == FOLDERS_METHOD => Ok(self.window_folders()), + // The window answers with the folders it enforces, which are none when a saved folder + // can't be used; a window without the method gets the saved settings. + Route::Window(w) if method == FOLDERS_METHOD => match w.lock().unwrap_or_else(PoisonError::into_inner).call(method, params) { + Err(e) if e.contains(&format!("unknown method `{FOLDERS_METHOD}`")) => Ok(self.window_folders()), + answer => answer, + }, Route::Window(w) => w.lock().unwrap_or_else(PoisonError::into_inner).call(method, params), Route::Headless(h) => h.borrow_mut().call(method, params), } diff --git a/crates/mcp/src/tests/agents.rs b/crates/mcp/src/tests/agents.rs index 4be7aa0e05..1a7a8e111c 100644 --- a/crates/mcp/src/tests/agents.rs +++ b/crates/mcp/src/tests/agents.rs @@ -19,8 +19,13 @@ const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789a /// A stand-in for the window's control server holding `token`: it authenticates as the shared /// server does and answers every request with `{"window": true, "method"}`. The count is of the -/// requests it got after authentication. +/// requests it got after authentication. It doesn't know `agent.folders`, as a window from before it. fn fake_window(token: &'static str) -> (u16, Arc) { + fake_window_with_folders(token, None) +} + +/// [`fake_window`], answering `agent.folders` with `folders` when given. +fn fake_window_with_folders(token: &'static str, folders: Option) -> (u16, Arc) { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); let served = Arc::new(AtomicUsize::new(0)); @@ -29,6 +34,7 @@ fn fake_window(token: &'static str) -> (u16, Arc) { for stream in listener.incoming() { let Ok(stream) = stream else { return }; let count = count.clone(); + let folders = folders.clone(); std::thread::spawn(move || { let mut writer = stream.try_clone().unwrap(); let mut handshake = ServerHandshake::new(); @@ -38,7 +44,11 @@ fn fake_window(token: &'static str) -> (u16, Arc) { let reply = if signed_in { count.fetch_add(1, Ordering::SeqCst); let req: Value = serde_json::from_str(&line).unwrap(); - json!({"id": req["id"], "ok": true, "result": {"window": true, "method": req["method"]}}) + match (&folders, req["method"] == FOLDERS_METHOD) { + (Some(f), true) => json!({"id": req["id"], "ok": true, "result": f}), + (None, true) => json!({"id": req["id"], "ok": false, "error": format!("unknown method `{FOLDERS_METHOD}`")}), + _ => json!({"id": req["id"], "ok": true, "result": {"window": true, "method": req["method"]}}), + } } else { let (reply, step) = handshake.reply(&line, token); signed_in = matches!(step, AuthStep::Authenticated); @@ -102,12 +112,25 @@ fn plain_mcp_reaches_the_window_while_agents_are_allowed() { let r = b.call("document.inspect", json!({})).unwrap(); assert_eq!(r["window"], true, "{r}"); assert!(served.load(Ordering::SeqCst) >= 1); - // The window's folders are the agent folders as the window opens them: the default one here. + // A window without `agent.folders`: the saved agent folders, the default one here. let folders = b.call(FOLDERS_METHOD, json!({})).unwrap(); assert_eq!(folders["read_folder"], json!(dir.file("Agents").to_string_lossy())); assert_eq!(folders["write_folder"], folders["read_folder"]); } +// `agent_folders` shows the folders the window enforces, not the saved ones: none here, as when a +// saved folder can't be used and the window refuses every file. +#[test] +fn the_window_reports_the_folders_it_enforces() { + let dir = TempFolder::new("agents-window-enforced"); + let (port, served) = fake_window_with_folders(TOKEN, Some(json!({"read_folder": null, "write_folder": null}))); + publish(&dir, port); + let mut b = live(&dir, || true, settings_headless, dir.file("Agents")); + let folders = b.call(FOLDERS_METHOD, json!({})).unwrap(); + assert_eq!(folders, json!({"read_folder": null, "write_folder": null})); + assert!(served.load(Ordering::SeqCst) >= 1); +} + // With agents off the app doesn't listen (its link is the gate), and plain `mcp` runs headless with // only the command's folders: the closed-app choice (an error here) is for agents the person let in. #[test] diff --git a/crates/ui-egui/src/agents.rs b/crates/ui-egui/src/agents.rs index 4ab629e70a..0ac04c7751 100644 --- a/crates/ui-egui/src/agents.rs +++ b/crates/ui-egui/src/agents.rs @@ -13,9 +13,10 @@ use std::sync::Arc; use craft::automation::ControlChannel; use craft::automation::agents::{AgentLink, AgentLinkStatus, AgentSettings, AgentSwitch, LinkProblem}; +use craft::control::agents::{AgentFolders, folders_answer}; use craft::ui::runtime::windows::WindowHost; use serde_json::{Value, json}; -use vectorcraft_engine::file_access::{self, AutomationRoots}; +use vectorcraft_engine::file_access::{self, Access, AutomationRoots}; use crate::VectorcraftApp; @@ -112,6 +113,30 @@ fn roots_for(settings: &AgentSettings, default: Option<&std::path::Path>) -> Res Ok(AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none)) } +/// `agent.folders`: the folders the request's own automation roots let it open and save in, as the +/// `agent_folders` tool shows them, with `read_folders` / `write_folders` listing every folder of a +/// kind that has several (`--automation-read-root` given twice). Roots that grant nothing (a saved +/// folder the window can't use) list no folder; a request that isn't confined says so. +pub(crate) fn folders(roots: Option<&AutomationRoots>) -> Value { + let Some(roots) = roots else { + return json!({"read_folder": null, "write_folder": null, "unrestricted": true}); + }; + let (read, write): (Vec<&std::path::Path>, Vec<&std::path::Path>) = + (roots.folders(Access::Read).collect(), roots.folders(Access::Write).collect()); + let mut folders = AgentFolders::default(); + folders.read = read.first().map(|p| p.to_path_buf()); + folders.write = write.first().map(|p| p.to_path_buf()); + let mut answer = folders_answer(&folders); + for (key, all) in [("read_folders", &read), ("write_folders", &write)] { + if all.len() > 1 + && let Some(o) = answer.as_object_mut() + { + o.insert(key.into(), json!(all.iter().map(|p| p.to_string_lossy()).collect::>())); + } + } + answer +} + /// Once per pass: brings the link in line with the launcher's switch and the saved settings. The /// control server starts, moves or stops; while it runs, its requests are the app's control channel /// and run inside the agent folders ([`VectorcraftApp::run_control`]). diff --git a/crates/ui-egui/src/agents/tests.rs b/crates/ui-egui/src/agents/tests.rs index d6b9757e18..c36eeb1d7e 100644 --- a/crates/ui-egui/src/agents/tests.rs +++ b/crates/ui-egui/src/agents/tests.rs @@ -133,3 +133,23 @@ fn prefs_agents_saves_and_agents_cannot_change_it() { assert!(file_access::confine(Some(&roots), || app.run("prefs.agents", json!({}))).is_ok()); let _ = std::fs::remove_dir_all(&base); } + +// `agent.folders` answers with the roots the request runs inside: roots that grant nothing (a saved +// folder the window can't use) list no folder. +#[test] +fn agent_folders_reports_the_roots_a_request_runs_inside() { + let base = folders("agent-folders"); + let roots = AutomationRoots::new(&[&base.join("in")], &[&base.join("out")]).unwrap().unwrap(); + let answer = super::folders(Some(&roots)); + assert!(answer["read_folder"].as_str().is_some_and(|f| f.ends_with("in")), "{answer}"); + assert!(answer["write_folder"].as_str().is_some_and(|f| f.ends_with("out")), "{answer}"); + assert!(answer.get("read_folders").is_none(), "{answer}"); + let two = AutomationRoots::new(&[&base.join("in"), &base.join("outside")], &[&base.join("out")]).unwrap().unwrap(); + let answer = super::folders(Some(&two)); + assert_eq!(answer["read_folders"].as_array().map(Vec::len), Some(2), "{answer}"); + assert!(answer.get("write_folders").is_none(), "{answer}"); + let none = super::folders(Some(&AutomationRoots::none())); + assert_eq!((&none["read_folder"], &none["write_folder"]), (&Value::Null, &Value::Null), "{none}"); + assert_eq!(super::folders(None)["unrestricted"], true); + let _ = std::fs::remove_dir_all(&base); +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 158cf852f8..ef4079e98c 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1198,7 +1198,10 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques } }; let Reply::Done(mut reply) = reply else { return reply }; - hide_in_reply(app, &mut reply, &req.params, before); + // `agent.folders` names the request's own roots, which it may use whole. + if method != "agent.folders" { + hide_in_reply(app, &mut reply, &req.params, before); + } Reply::Done(reply) } @@ -1398,6 +1401,9 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val } "engine.commands" => ok(all_commands(app)), "document.inspect" => wrap(app.run("document.inspect", p.clone())), + // Each request runs confined to the window's automation roots ([`VectorcraftApp::run_control`]). + #[cfg(not(target_arch = "wasm32"))] + "agent.folders" => ok(crate::agents::folders(vectorcraft_engine::file_access::current().as_deref())), "ui.inspect" => ok(inspect(app, ctx)), "ui.docking" => ok(crate::panel_docking::inspect(app, ctx)), // A request that stops with a panic quoting the status text, after clearing the Color Guide's diff --git a/docs/mcp.md b/docs/mcp.md index 2fd8648262..80254caa9f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -876,7 +876,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. A type object in `ids` with another of them above it in its layer is the text to wrap, not a wrap object, so the objects and the type can be selected together. The reply has a `warning` when no area type lies below any of the wrap objects. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | | `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | -| `agent_folders` | `{}` | Where VectorCraft opens and saves files for this session: `{read_folder, write_folder}`, each a path or `null`. In the open window, the agent folders of Preferences › AI Integrations (`Documents/ArtCraft/Agents/VectorCraft` for an empty one); in a headless session started for agents, the folders it was confined to (`read_folders` / `write_folders` list them all when a kind has several); a session started without automation roots answers `unrestricted: true`. An app reached with the deprecated `--connect` answers an error: its own `--automation-*-root` flags, if any, confine it. | +| `agent_folders` | `{}` | Where VectorCraft opens and saves files for this session: `{read_folder, write_folder}`, each a path or `null`. In the open window, the agent folders the window enforces: those of Preferences › AI Integrations (`Documents/ArtCraft/Agents/VectorCraft` for an empty one), or `null` for both when a saved folder can't be used (a deleted folder, a file) and the window refuses every file (a window from before `agent.folders` was added answers with the saved folders, even one it can't use); in a headless session started for agents, the folders it was confined to (`read_folders` / `write_folders` list them all when a kind has several); a session started without automation roots answers `unrestricted: true`. An app reached with the deprecated `--connect` answers an error: its own `--automation-*-root` flags, if any, confine it. | For example, create editable Japanese area type with the engine's vertical writing mode: From ef11e6f6ecc75dfb6523f3b504b1a1eaa8c47700 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 14:51:25 -0800 Subject: [PATCH 50/88] Agents: agent.folders refuses parameters, tested through the window The window's `agent.folders` method now refuses any parameter. A new test sends real `agent.folders` requests to a window whose saved read folder is a file and checks that both folders come back null and that a request with a parameter is refused. --- crates/ui-egui/src/agents/tests.rs | 22 ++++++++++++++++++++++ crates/ui-egui/src/control.rs | 7 ++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/agents/tests.rs b/crates/ui-egui/src/agents/tests.rs index c36eeb1d7e..4825fc6570 100644 --- a/crates/ui-egui/src/agents/tests.rs +++ b/crates/ui-egui/src/agents/tests.rs @@ -114,6 +114,28 @@ fn with_the_switch_off_nothing_listens() { let _ = std::fs::remove_dir_all(&base); } +#[test] +fn agent_folders_reaches_the_window_with_unusable_saved_roots() { + let base = folders("agent-folders-window"); + let (mut app, _) = app_with_agents(&base, AgentSwitch::fixed(true, true)); + app.run("prefs.agents", json!({"readRoot": s(base.join("in/a.svg"))})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap_or_default(); + super::sync(&mut app, &ctx); + let connection = read_connection(&base.join("settings")).unwrap().expect("the connection file is published"); + let token = std::fs::read_to_string(&connection.token_file).unwrap(); + let mut client = Some(ControlClient::connect(([127, 0, 0, 1], connection.port).into(), token.trim()).unwrap()); + + for params in [json!({}), Value::Null] { + let answer = agent_request(&mut app, &mut client, "agent.folders", params).unwrap(); + assert_eq!(answer.get("read_folder"), Some(&Value::Null), "{answer}"); + assert_eq!(answer.get("write_folder"), Some(&Value::Null), "{answer}"); + assert_ne!(answer.get("unrestricted"), Some(&Value::Bool(true)), "{answer}"); + } + let unexpected = agent_request(&mut app, &mut client, "agent.folders", json!({"unexpected": true})); + assert!(unexpected.as_ref().is_err_and(|e| e.contains("takes no parameters")), "{unexpected:?}"); + let _ = std::fs::remove_dir_all(&base); +} + // `prefs.agents` saves the person's settings, refuses unknown keys, and refuses every change from a // confined request: agents can't widen their own folders. #[test] diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index ef4079e98c..96a63d3c2a 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1403,7 +1403,12 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val "document.inspect" => wrap(app.run("document.inspect", p.clone())), // Each request runs confined to the window's automation roots ([`VectorcraftApp::run_control`]). #[cfg(not(target_arch = "wasm32"))] - "agent.folders" => ok(crate::agents::folders(vectorcraft_engine::file_access::current().as_deref())), + "agent.folders" => { + if !p.is_null() && !p.as_object().is_some_and(|fields| fields.is_empty()) { + return err("`agent.folders` takes no parameters"); + } + ok(crate::agents::folders(vectorcraft_engine::file_access::current().as_deref())) + } "ui.inspect" => ok(inspect(app, ctx)), "ui.docking" => ok(crate::panel_docking::inspect(app, ctx)), // A request that stops with a panic quoting the status text, after clearing the Color Guide's From 335c7c64dda6e073a064222acb8b3ad64dc45271 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 14:32:36 -0800 Subject: [PATCH 51/88] DWG: export writes the DXF drawing as DWG 2000 to 2018 DWG was read only: Export As listed it grayed out, document.export answered with a hint to export DXF, and a script's AutoCADExportFileFormat.DWG, the default, threw an error. - document.export {format: dwg}, a .dwg path, and document.exportDxf with format: dwg write the drawing the DXF export writes, with the same options, converted by craft-dwg in the --dwg-worker copy of the app. Versions are 2000, 2004, 2007, 2010, 2013 and 2018; R12, R13 and R14 are refused with an error that names them. Records the DWG writer can't write in that version are left out with a warning that counts them by type. - Export As lists DWG and opens DWG Options: DXF Options with the DWG versions. A version remembered from DXF Options that DWG isn't written as starts on 2018. - Scripts: AutoCADExportFileFormat.DWG writes a .dwg file; AutoCADRelease13 and 14 with DWG throw an error. Docs: docs/mcp.md, docs/control-protocol.md, docs/file-format-parity.md, docs/target-app-parity.md, docs/roadmap.md. Co-authored-by: Alex-BB44 <273073052+Alex-BB44@users.noreply.github.com> --- crates/cad/src/dwg.rs | 70 ++++++++++- crates/engine/src/cmd/fileio.rs | 2 +- crates/engine/src/cmd/fileio/action_batch.rs | 1 + crates/engine/src/cmd/fileio/dxf.rs | 119 +++++++++++------- crates/engine/src/cmd/fileio/encode.rs | 5 +- crates/engine/src/cmd/fileio/formats.rs | 14 ++- crates/engine/src/cmd/fileio/screens.rs | 2 +- crates/engine/src/cmd/fileio/tests.rs | 8 +- .../engine/src/cmd/fileio/tests_dwgimport.rs | 65 ++++++++-- crates/engine/src/cmd/fileio/tests_dxf.rs | 8 +- crates/engine/src/script/dom/save_open.rs | 31 +++-- crates/engine/src/tests/script_save_open.rs | 27 ++-- crates/mcp/src/tests.rs | 2 +- crates/ui-egui/src/dialogs/dxf_options.rs | 49 +++++--- crates/ui-egui/src/dialogs/export_as.rs | 34 ++--- crates/ui-egui/src/dialogs/tests_dxf.rs | 40 ++++-- crates/ui-egui/src/io.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/control-protocol.md | 6 +- docs/file-format-parity.md | 4 +- docs/mcp.md | 16 ++- docs/roadmap.md | 2 +- docs/target-app-parity.md | 5 +- 23 files changed, 357 insertions(+), 157 deletions(-) diff --git a/crates/cad/src/dwg.rs b/crates/cad/src/dwg.rs index b6e4b545c4..6921c307e4 100644 --- a/crates/cad/src/dwg.rs +++ b/crates/cad/src/dwg.rs @@ -1,9 +1,11 @@ //! DWG drawings, read as DXF: `craft_dwg` converts the bytes and the DXF reader reads the result. +//! Export writes a DWG the other way: the DXF writer's drawing, converted by `craft_dwg` ([`from_dxf`]). //! -//! The conversion runs in a child process once the program has called [`use_own_worker`] (and +//! Each conversion runs in a child process once the program has called [`use_own_worker`] (and //! [`serve_if_asked`] first thing in `main`), so a damaged file that makes the DWG reader abort //! ends that process, not VectorCraft. Without a worker the conversion is refused, unless -//! [`allow_in_process`] was called (tests). Web builds answer that DWG can't be read there. +//! [`allow_in_process`] was called (tests). Web builds answer that DWG can't be read or written +//! there. use std::hash::BuildHasher; use std::sync::{Arc, LazyLock, Mutex, PoisonError, Weak}; @@ -11,7 +13,7 @@ use std::time::Duration; use web_time::Instant; -pub use craft_dwg::{WORKER_ARG, allow_in_process, use_own_worker}; +pub use craft_dwg::{Unwritten, WORKER_ARG, allow_in_process, use_own_worker}; /// The worker argument after [`WORKER_ARG`] that gives its deadline in milliseconds since the UNIX epoch /// ([`use_own_worker_for`]). @@ -174,7 +176,48 @@ fn convert(bytes: &[u8]) -> Result { Ok(Converted { dxf, notes: notes.iter().map(|n| worded(n)).collect() }) } -/// craft-dwg's message or note in VectorCraft's words: VectorCraft opens a DWG and never saves one. +/// Can a DWG file of `version` be written? craft-dwg writes 2000, 2004, 2007, 2010, 2013 and 2018. +pub fn writes(version: crate::DxfVersion) -> bool { + craft_dwg::VERSIONS.iter().any(|(code, _)| *code == version.acadver()) +} + +/// A DWG file of `version` from `dxf`, an ASCII DXF of that version as [`crate::export_drawings`] +/// writes it, and what the DWG writer left out: how many records of each DXF type. The conversion +/// runs in the worker, as reading does. +/// +/// # Errors +/// +/// When `version` is one a DWG can't be written as, or the conversion fails. +pub fn from_dxf(dxf: &[u8], version: crate::DxfVersion) -> Result<(Vec, craft_dwg::Unwritten), String> { + if !writes(version) { + return Err(format!("DWG version `{}` can't be written: use {}", version.id(), written_versions())); + } + craft_dwg::encode_noted(dxf, version.acadver()) +} + +/// The versions a DWG can be written as, as the `version` param names them ("2000, 2004 … or 2018"). +pub fn written_versions() -> String { + let ids: Vec<&str> = crate::DxfVersion::ALL.iter().rev().filter(|v| writes(**v)).map(|v| v.id()).collect(); + match ids.split_last() { + Some((last, rest)) if !rest.is_empty() => format!("{} or {last}", rest.join(", ")), + Some((last, _)) => (*last).to_string(), + None => String::new(), + } +} + +/// The warning for what the DWG writer left out of `files` files, by DXF type, else none. +pub fn left_out_warning(left_out: &craft_dwg::Unwritten, files: usize) -> Option { + let total: usize = left_out.values().sum(); + if total == 0 { + return None; + } + let kinds: Vec = left_out.iter().map(|(kind, n)| format!("{kind} × {n}")).collect(); + let of = if files > 1 { format!("these {files} drawings") } else { "this drawing".to_string() }; + let records = if total == 1 { "record" } else { "records" }; + Some(format!("DWG: {total} {records} of {of} can't be written in this DWG version and were left out ({})", kinds.join(", "))) +} + +/// craft-dwg's message or note on reading a DWG, in VectorCraft's words. fn worded(message: &str) -> String { message .replace("accepted by this bridge", "VectorCraft opens") @@ -275,4 +318,23 @@ mod tests { let n = worded("DWG: 2 objects of types this bridge can't preserve were left out (X × 2); saving over the original file would lose them"); assert_eq!(n, "DWG: 2 objects of types VectorCraft can't read were left out (X × 2)"); } + + #[test] + fn a_version_before_2000_is_refused_before_converting() { + // No worker is configured here, so a conversion that ran would fail for that reason instead. + let e = from_dxf(b" 0\nEOF\n", crate::DxfVersion::R14).unwrap_err(); + assert!(e.starts_with("DWG version `R14` can't be written: use 2000,") && e.ends_with("or 2018"), "{e}"); + assert!(writes(crate::DxfVersion::R2000) && !writes(crate::DxfVersion::R13) && !writes(crate::DxfVersion::R12)); + } + + #[test] + fn records_the_dwg_writer_left_out_are_counted_by_type() { + assert_eq!(left_out_warning(&craft_dwg::Unwritten::new(), 1), None); + let one: craft_dwg::Unwritten = [("ACME_WIDGET".to_string(), 1)].into_iter().collect(); + let w = left_out_warning(&one, 1).unwrap(); + assert!(w.contains("1 record of this drawing") && w.contains("ACME_WIDGET × 1"), "{w}"); + let some: craft_dwg::Unwritten = [("ACME_WIDGET".to_string(), 2), ("ACME_OBJECT".to_string(), 1)].into_iter().collect(); + let w = left_out_warning(&some, 3).unwrap(); + assert!(w.contains("3 records of these 3 drawings") && w.contains("ACME_OBJECT × 1, ACME_WIDGET × 2"), "{w}"); + } } diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 1a24bf623b..20a493f00b 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -13,7 +13,7 @@ //! per-format options (`file.formatOptions`); [`save_with`] is the one save path of every frontend. //! - `pdf`: PDF settings and presets for every PDF export, `document.exportPdf`. //! - `pdfimport`: the PDF pages, box and password `document.open` and Place read, `document.pdfInfo`. -//! - `dxf`: DXF export options, `document.exportDxf`, and the formats that can't be written (DWG, PageMaker). +//! - `dxf`: DXF and DWG export options, `document.exportDxf`, and the formats that can't be written (PageMaker). //! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`. //! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`. //! - `metafile`: EMF and WMF export, open and place; PICT open and place. diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 9beed7e8a2..7d717e7adf 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -570,6 +570,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def | "tga" | "psd" | "dxf" + | "dwg" | "emf" | "wmf" | "hpgl" diff --git a/crates/engine/src/cmd/fileio/dxf.rs b/crates/engine/src/cmd/fileio/dxf.rs index c92d9b8ad0..f92eaf5126 100644 --- a/crates/engine/src/cmd/fileio/dxf.rs +++ b/crates/engine/src/cmd/fileio/dxf.rs @@ -1,7 +1,8 @@ -//! DXF export for every DXF path (`document.export {format: dxf}`, `document.exportDxf`, Export As -//! → DXF Options): the options parsed from the params, one drawing per artboard with Use -//! Artboards, and the formats that can't be written (DWG, which opens, and PageMaker) with what to -//! use instead. +//! DXF and DWG export for every path (`document.export {format: dxf|dwg}`, `document.exportDxf`, +//! Export As → DXF Options and DWG Options): the options parsed from the params, one drawing per +//! artboard with Use Artboards, and the formats that can't be written (PageMaker) with what to use +//! instead. A DWG file is the DXF drawing converted by craft-dwg (`vectorcraft_cad::dwg::from_dxf`), +//! from version 2000. use std::sync::Arc; @@ -22,14 +23,27 @@ pub fn specs() -> Vec { "Export DXF", [], None, - "{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; includeImages and includeHatches false, so fills are their outlines and no image files are written; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), includeImages?: true (false: placed images and their files are left out), includeHatches?: true (false: fills are their outlines, without solid hatches), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused", + "{path?, format?: dxf (default)|dwg (a DWG file of the same drawing, version 2000 to 2018; records the DWG writer can't write in that version are left out with a warning), dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; includeImages and includeHatches false, so fills are their outlines and no image files are written; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), includeImages?: true (false: placed images and their files are left out), includeHatches?: true (false: fills are their outlines, without solid hatches), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf} (or dwg). A key DXF doesn't take is refused", has_doc, export_dxf )] } /// The DXF options `document.formats` lists. -pub(crate) const OPTIONS: &[FormatOption] = &[ +pub(crate) const OPTIONS: &[FormatOption] = &DXF_OPTIONS; + +/// The DWG options `document.formats` lists: the DXF ones, with the versions a DWG is written as. +pub(crate) const DWG_OPTIONS: &[FormatOption] = &{ + let mut o = DXF_OPTIONS; + assert!(matches!(o[VERSION].name.as_bytes(), b"version"), "VERSION is the index of the version option"); + o[VERSION] = FormatOption { name: "version", ty: "string", default: "\"2018\"", description: "2000, 2004, 2007, 2010, 2013 or 2018" }; + o +}; + +/// Where the version option is in [`DXF_OPTIONS`]. +const VERSION: usize = 5; + +const DXF_OPTIONS: [FormatOption; 17] = [ super::ARTBOARD, super::ARTBOARDS, super::RANGE, @@ -113,14 +127,10 @@ pub fn unsupported(id_or_ext: &str) -> Option<&'static Unsupported> { UNSUPPORTED.iter().find(|u| u.id == k || u.extensions.contains(&k.as_str())) } -/// Formats VectorCraft opens but doesn't write, with what to export instead. -const READ_ONLY_HINTS: &[(&str, &str)] = &[("dwg", "DWG files open but can't be written: export DXF instead, which CAD apps open")]; - /// What to write instead of the format an id or extension (any case, leading dot allowed) names, -/// when that format can't be written: an unsupported format's hint, or a read-only one's (DWG). +/// when that format can't be written: an unsupported format's hint. pub fn write_hint(id_or_ext: &str) -> Option<&'static str> { - let k = id_or_ext.trim_start_matches('.').to_ascii_lowercase(); - unsupported(&k).map(|u| u.hint).or_else(|| READ_ONLY_HINTS.iter().find(|(id, _)| *id == k).map(|(_, hint)| *hint)) + unsupported(id_or_ext).map(|u| u.hint) } impl Unsupported { @@ -157,39 +167,42 @@ pub(crate) fn text(v: &Value) -> String { } } -/// `field` read by `read`, or an error listing what it may be. -fn choice(field: &str, v: Option, read: impl Fn(&str) -> Option, default: T, allowed: &str) -> Result { +/// `field` of a `kind` (DXF or DWG) export read by `read`, or an error listing what it may be. +fn choice(kind: &str, field: &str, v: Option, read: impl Fn(&str) -> Option, default: T, allowed: &str) -> Result { match v { None => Ok(default), - Some(s) => read(&s).ok_or_else(|| bad(C, format!("DXF {field} `{s}`: {allowed}"))), + Some(s) => read(&s).ok_or_else(|| bad(C, format!("{kind} {field} `{s}`: {allowed}"))), } } -/// The DXF options in `p` (the region and crop are set per drawing) and the artboard choice. -fn parse(p: &Value) -> Result<(DxfOptions, ArtboardPick)> { - let q: Params = if p.is_object() { Params::deserialize(p).map_err(|e| bad(C, format!("DXF options: {e}")))? } else { Params::default() }; +/// The DXF options in `p` (the region and crop are set per drawing) and the artboard choice; with +/// `dwg`, a version a DWG file is written as. +fn parse(p: &Value, dwg: bool) -> Result<(DxfOptions, ArtboardPick)> { + let kind = if dwg { "DWG" } else { "DXF" }; + let q: Params = if p.is_object() { Params::deserialize(p).map_err(|e| bad(C, format!("{kind} options: {e}")))? } else { Params::default() }; // The options a preset sets are the defaults of those `p` leaves out. - let d = choice("dxfPreset", q.dxf_preset, DxfPreset::from_id, DxfPreset::Custom, "custom or cnc")?.options(); + let d = choice(kind, "dxfPreset", q.dxf_preset, DxfPreset::from_id, DxfPreset::Custom, "custom or cnc")?.options(); let scale = q.scale.unwrap_or(d.scale); if !(scale.is_finite() && vectorcraft_cad::SCALE_RANGE.contains(&scale)) { - return Err(bad(C, format!("DXF scale must be a positive number up to {}, not {scale}", vectorcraft_cad::SCALE_RANGE.end()))); + return Err(bad(C, format!("{kind} scale must be a positive number up to {}, not {scale}", vectorcraft_cad::SCALE_RANGE.end()))); } + let version = q.version.as_ref().map(text); + let version = if dwg { + let read = |s: &str| DxfVersion::from_id(s).filter(|v| vectorcraft_cad::dwg::writes(*v)); + choice(kind, "version", version, read, d.version, &vectorcraft_cad::dwg::written_versions())? + } else { + choice(kind, "version", version, DxfVersion::from_id, d.version, "R12, R13, R14, 2000, 2004, 2007, 2010, 2013 or 2018")? + }; let opts = DxfOptions { - version: choice( - "version", - q.version.as_ref().map(text), - DxfVersion::from_id, - d.version, - "R12, R13, R14, 2000, 2004, 2007, 2010, 2013 or 2018", - )?, - unit: choice("unit", q.unit, Unit::named, d.unit, "a unit such as mm, cm, in or pt")?, + version, + unit: choice(kind, "unit", q.unit, Unit::named, d.unit, "a unit such as mm, cm, in or pt")?, scale, scale_lineweights: q.scale_lineweights.unwrap_or(d.scale_lineweights), - colors: choice("colors", q.colors.as_ref().map(text), ColorDepth::from_id, d.colors, "8, 16, 256 or true")?, - raster: choice("rasterFormat", q.raster_format, RasterFormat::from_id, d.raster, "png or jpeg")?, + colors: choice(kind, "colors", q.colors.as_ref().map(text), ColorDepth::from_id, d.colors, "8, 16, 256 or true")?, + raster: choice(kind, "rasterFormat", q.raster_format, RasterFormat::from_id, d.raster, "png or jpeg")?, include_images: q.include_images.unwrap_or(d.include_images), include_hatches: q.include_hatches.unwrap_or(d.include_hatches), - preserve: choice("preserve", q.preserve, Preserve::from_id, d.preserve, "appearance or editability")?, + preserve: choice(kind, "preserve", q.preserve, Preserve::from_id, d.preserve, "appearance or editability")?, alter_paths: q.alter_paths.unwrap_or(d.alter_paths), outline_text: q.outline_text.unwrap_or(d.outline_text), ..d @@ -197,21 +210,27 @@ fn parse(p: &Value) -> Result<(DxfOptions, ArtboardPick)> { Ok((opts, q.boards)) } -/// Check the DXF options in `p` without exporting (dialogs keep themselves open on an error). +/// Is `p` a DWG export (`format: dwg`, or `.dwg` and the other names of the DWG format)? +fn is_dwg(p: &Value) -> bool { + p.get("format").and_then(Value::as_str).and_then(super::format).is_some_and(|f| f.id == "dwg") +} + +/// Check the DXF options in `p` without exporting (dialogs keep themselves open on an error); +/// with `format: dwg`, as DWG options. pub fn check(p: &Value) -> std::result::Result<(), String> { - parse(p).map(|_| ()).map_err(|e| e.to_string()) + parse(p, is_dwg(p)).map(|_| ()).map_err(|e| e.to_string()) } /// The DXF options in `p` (the region and crop left at their defaults). pub fn options(p: &Value) -> std::result::Result { - parse(p).map(|(o, _)| o).map_err(|e| e.to_string()) + parse(p, false).map(|(o, _)| o).map_err(|e| e.to_string()) } -/// Encode `doc` as DXF: one drawing whose origin is the chosen artboard's bottom-left corner -/// (default the first), or with `use_artboards` one drawing per chosen artboard (default all) -/// holding the art over it. -pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> Result { - let (opts, pick) = parse(p)?; +/// Encode `doc` as DXF, or with `dwg` as DWG: one drawing whose origin is the chosen artboard's +/// bottom-left corner (default the first), or with `use_artboards` one drawing per chosen artboard +/// (default all) holding the art over it. +pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option, dwg: bool) -> Result { + let (opts, pick) = parse(p, dwg)?; let n = doc.artboards.len(); let rect = |b: usize| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))); let drawings: Vec<(Option, Rect, bool)> = match use_artboards { @@ -224,7 +243,7 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> let b = match pick.resolve(n).map_err(|e| bad(C, e))?.as_deref() { None => 0, Some([b]) => *b, - Some(_) => return Err(bad(C, "a DXF drawing has one origin: pass useArtboards: true for one drawing per artboard")), + Some(_) => return Err(bad(C, "a DXF or DWG drawing has one origin: pass useArtboards: true for one drawing per artboard")), }; vec![(Some(b), rect(b)?, false)] } @@ -232,9 +251,22 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> let regions: Vec<(Rect, bool)> = drawings.iter().map(|&(_, region, crop)| (region, crop)).collect(); let outs = vectorcraft_cad::export_drawings(doc, &opts, ®ions).map_err(|e| bad(C, e))?; let mut enc = Encoded::default(); + let mut left_out = vectorcraft_cad::dwg::Unwritten::new(); for ((board, _, _), out) in drawings.into_iter().zip(outs) { - enc.files.push((board, out.bytes)); - for w in out.warnings { + let mut warnings = out.warnings; + let bytes = if dwg { + let (bytes, unwritten) = vectorcraft_cad::dwg::from_dxf(&out.bytes, opts.version).map_err(|e| bad(C, e))?; + for (kind, n) in unwritten { + *left_out.entry(kind).or_insert(0) += n; + } + // The DXF writer's version notes ("true colour needs DXF 2004 or later") hold for the DWG. + warnings = warnings.into_iter().map(|w| w.replacen("needs DXF ", "needs DWG ", 1)).collect(); + bytes + } else { + out.bytes + }; + enc.files.push((board, bytes)); + for w in warnings { if !enc.warnings.contains(&w) { enc.warnings.push(w); } @@ -249,11 +281,12 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> if enc.files.is_empty() { return Err(bad(C, "the document has no artboard")); } + enc.warnings.extend(vectorcraft_cad::dwg::left_out_warning(&left_out, enc.files.len())); Ok(enc) } fn export_dxf(s: &mut Session, p: &Value) -> Result { let mut q = if p.is_object() { p.clone() } else { json!({}) }; - q["format"] = json!("dxf"); + q["format"] = json!(if is_dwg(p) { "dwg" } else { "dxf" }); super::export::export(s, &q) } diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 96e5d2210f..2108db6557 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -1110,7 +1110,8 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { let doc = &*doc.without_edit_modes(); let n = doc.artboards.len(); // SVG reads its own `useArtboards` (an SVG option). - let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None }; + let use_artboards = + if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "dwg" | "emf" | "wmf" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None }; // `rect`: that area of the page, as if it were the only artboard (the document is not changed). if let Some(rect) = page_rect(f, p)? { let mut q = super::export::without_artboards(p); @@ -1150,7 +1151,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { } "txt" => super::text::encode(doc, p)?, "svg" | "svgz" => return super::svg::encode(doc, p, f.id == "svgz").map_err(|e| bad(C, e)), - "dxf" => return super::dxf::encode(doc, p, use_artboards), + "dxf" | "dwg" => return super::dxf::encode(doc, p, use_artboards, f.id == "dwg"), // EPS reads its own `useArtboards` (the art's bounds unless asked). "eps" => return super::eps::encode(doc, p), "emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf), diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index f8da5b941c..277aa77570 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -562,8 +562,18 @@ pub const FORMATS: &[Format] = &[ // composite, the layers combined, or the preview with a note. Exports don't write them. reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true), // DWG drawings, converted to DXF by craft-dwg (`vectorcraft_cad::dwg`) and read by the DXF - // reader with the DXF import options. Exports don't write them. - reader("dwg", "DWG", &["dwg"], "image/vnd.dwg", false), + // reader with the DXF import options. Exports write the DXF writer's drawing, converted by + // craft-dwg, as versions 2000 to 2018. + Format { + id: "dwg", + label: "DWG", + extensions: &["dwg"], + mime: "image/vnd.dwg", + read: true, + write: true, + raster: false, + options: dxf::DWG_OPTIONS, + }, ]; /// Every extension `document.open` reads (the "All readable files" filter of open dialogs). diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 4cc3cad433..d666722a24 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -196,7 +196,7 @@ pub(super) fn name_without_device(name: &str) -> String { pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"]; /// The writable formats a format row can't name. -pub(crate) const UNWRITTEN_FORMATS: [&str; 7] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx"]; +pub(crate) const UNWRITTEN_FORMATS: [&str; 8] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx", "dwg"]; /// One format row: what to write, at which size, with which suffix, into which sub-folder. struct Row { diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index ed0034b99e..f3580dbca6 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -533,7 +533,8 @@ fn export_extensions_name_every_writable_format() { "plt", "tga", "psd", - "cmx" + "cmx", + "dwg" ] ); for e in exts { @@ -570,7 +571,8 @@ fn formats_query_lists_readers_writers_and_options() { "hpgl", "tga", "psd", - "cmx" + "cmx", + "dwg" ] ); assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string())); @@ -657,7 +659,7 @@ fn export_without_path_returns_bytes_and_never_retargets() { let r = s.execute("document.export", &json!({"format": "jpg"})).unwrap(); assert_eq!(&b64(&r)[..2], [0xFF, 0xD8]); assert!(r.get("path").is_none()); - assert!(s.execute("document.export", &json!({"path": dir.join("x.dwg").to_string_lossy()})).is_err(), "DWG can't be written"); + assert!(s.execute("document.export", &json!({"path": dir.join("x.pmd").to_string_lossy()})).is_err(), "PageMaker can't be written"); // A never-saved document hands its native bytes back. let mut s = session(10.0, 10.0, 1); let r = s.execute("document.save", &json!({})).unwrap(); diff --git a/crates/engine/src/cmd/fileio/tests_dwgimport.rs b/crates/engine/src/cmd/fileio/tests_dwgimport.rs index d4aa2ad348..d64c58ca67 100644 --- a/crates/engine/src/cmd/fileio/tests_dwgimport.rs +++ b/crates/engine/src/cmd/fileio/tests_dwgimport.rs @@ -1,7 +1,7 @@ //! DWG through the commands: `document.open`, `document.dxfInfo` and File → Place read a DWG -//! drawing as the DXF it converts to, with the DXF options; DWG is in the format table as read -//! only, and exporting one says to write DXF. craft-dwg reads and writes DWG everywhere but wasm32 -//! and FreeBSD on aarch64. +//! drawing as the DXF it converts to, with the DXF options; `document.export` writes the DXF +//! writer's drawing as a DWG of version 2000 or later. craft-dwg reads and writes DWG everywhere but +//! wasm32 and FreeBSD on aarch64. #![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] use serde_json::{Value, json}; @@ -73,12 +73,59 @@ fn a_dwg_opened_is_never_written_back_as_dwg() { s.execute("document.open", &json!({"path": path.to_string_lossy()})).unwrap(); let e = s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap_err().to_string(); assert!(e.contains("not DWG"), "{e}"); - let e = s.execute("document.export", &json!({"format": "dwg"})).unwrap_err().to_string(); - assert!(e.contains("export DXF instead"), "{e}"); assert_eq!(std::fs::read(&path).unwrap(), dwg, "the drawing is unchanged"); let _ = std::fs::remove_dir_all(&dir); } +/// The bytes of the one file `document.export` handed back. +fn exported(r: &Value) -> Vec { + vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap() +} + +#[test] +fn document_export_writes_a_dwg_that_opens_as_the_drawing_its_dxf_holds() { + vectorcraft_cad::dwg::allow_in_process(); + let mut s = Session::new(); + open(&mut s, "plan.dxf", &plan(), json!({})).unwrap(); + let dxf = exported(&s.execute("document.export", &json!({"format": "dxf", "version": "2000"})).unwrap()); + let r = s.execute("document.export", &json!({"format": "dwg", "version": "2000"})).unwrap(); + let dwg = exported(&r); + assert_eq!(craft_dwg::version(&dwg).as_deref(), Some("AC1015")); + assert!(r["warnings"].as_array().is_none_or(|w| w.iter().all(|w| !w.as_str().unwrap_or("").starts_with("DWG:"))), "{r}"); + open(&mut s, "again.dxf", &dxf, json!({})).unwrap(); + let (want_layers, want_leaves) = (layer_names(&s), leaves(&s).len()); + open(&mut s, "again.dwg", &dwg, json!({})).unwrap(); + assert_eq!(layer_names(&s), want_layers); + assert_eq!(leaves(&s).len(), want_leaves); + // The default version is 2018, and `.dwg` in the path picks the format. + let dir = std::env::temp_dir().join(format!("vc-dwg-export-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("out.dwg"); + let r = s.execute("document.export", &json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!(r["format"], "dwg"); + assert_eq!(craft_dwg::version(&std::fs::read(&path).unwrap()).as_deref(), Some("AC1032")); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_dwg_version_before_2000_is_refused_and_nothing_is_written() { + vectorcraft_cad::dwg::allow_in_process(); + let mut s = Session::new(); + open(&mut s, "plan.dxf", &plan(), json!({})).unwrap(); + let dir = std::env::temp_dir().join(format!("vc-dwg-r14-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("old.dwg"); + for version in ["R12", "R13", "R14"] { + let e = s.execute("document.export", &json!({"path": path.to_string_lossy(), "version": version})).unwrap_err().to_string(); + assert!(e.contains(&format!("DWG version `{version}`")) && e.contains("2000") && e.contains("2018"), "{e}"); + } + assert!(!path.exists()); + // The same versions are DXF versions. + let r = s.execute("document.export", &json!({"format": "dxf", "version": "R14"})).unwrap(); + assert!(String::from_utf8_lossy(&exported(&r)).contains("AC1014")); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn dxf_info_and_place_read_a_dwg() { let mut s = Session::new(); @@ -100,14 +147,16 @@ fn dxf_info_and_place_read_a_dwg() { } #[test] -fn dwg_is_read_only_and_detected_by_content() { +fn dwg_is_read_and_written_and_detected_by_content() { let f = format("dwg").unwrap(); - assert!(f.read && !f.write); + assert!(f.read && f.write); + let version = f.options.iter().find(|o| o.name == "version").unwrap(); + assert!(!version.description.contains("R14") && version.description.contains("2000"), "{}", version.description); assert!(OPEN_EXTS.contains(&"dwg") && PLACE_EXTS.contains(&"dwg") && UNASSOCIATED_EXTS.contains(&"dwg")); assert_eq!(detect("drawing.bin", &plan_dwg()).map(|f| f.id), Some("dwg"), "the content tells"); let mut s = Session::new(); let r = s.execute("document.formats", &json!({})).unwrap(); assert!(r["readable"].as_array().unwrap().contains(&json!("dwg"))); - assert!(!r["writable"].as_array().unwrap().contains(&json!("dwg"))); + assert!(r["writable"].as_array().unwrap().contains(&json!("dwg"))); assert!(r["unsupported"].as_array().unwrap().iter().all(|u| u["id"] != "dwg")); } diff --git a/crates/engine/src/cmd/fileio/tests_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index 7a04d93ddc..990d7ba4c6 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -1,5 +1,5 @@ //! DXF export through the commands: options, artboards, selection, images, and the formats that -//! can't be written (DWG, which opens, and PageMaker). +//! can't be written (PICT, which opens, and PageMaker). use serde_json::{Value, json}; @@ -297,12 +297,8 @@ fn formats_list_dxf_and_what_can_not_be_written() { } #[test] -fn dwg_and_pagemaker_say_what_to_use_instead() { +fn pict_and_pagemaker_say_what_to_use_instead() { let mut s = two_boards(); - for p in [json!({"format": "dwg"}), json!({"path": "/tmp/plan.DWG"})] { - let e = s.execute("document.export", &p).unwrap_err().to_string(); - assert!(e.contains("DWG files open but can't be written") && e.contains("export DXF instead"), "{p}: {e}"); - } // PICT opens; it isn't written. let e = s.execute("document.export", &json!({"format": "pict"})).unwrap_err().to_string(); assert!(e.contains("PICT files can be opened but not written"), "{e}"); diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 34f7755d1a..b16de491e1 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -28,9 +28,10 @@ //! one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. //! An SVG with `embedRasterImages` false also writes the document's embedded images beside it, //! and when one of those files may not be written, none of them is. -//! - `ExportType.AUTOCAD` is the same value as `ExportType.AutoCAD`. An AutoCAD export writes DXF -//! (`.dxf`) only: `AutoCADExportFileFormat.DWG`, the default, throws an error that says DWG is not -//! available. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page +//! - `ExportType.AUTOCAD` is the same value as `ExportType.AutoCAD`. An AutoCAD export writes DWG +//! (`.dwg`) with `AutoCADExportFileFormat.DWG`, the default, and DXF (`.dxf`) with +//! `AutoCADExportFileFormat.DXF`. A DWG is written as version 2000 or later: `AutoCADRelease13` +//! and `AutoCADRelease14` with DWG throw an error that names `AutoCADRelease15`. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page //! gives; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to //! true colors, PNG, millimeters and 100. `unitScaleRatio` is a percentage: at 100 one `unit` is //! one drawing unit. It is at least 0.0001 and at most 1000. @@ -704,11 +705,7 @@ fn autocad_map(name: &str, d: &Data, p: &mut Map) -> std::result: p.insert("outlineText".into(), json!(boolean(d, &what)?)); } "exportFileFormat" => { - if pick("AutoCADExportFileFormat")? == "DWG" { - return Err(HostError::Error( - "AutoCADExportFileFormat.DWG is not available: set exportFileFormat to AutoCADExportFileFormat.DXF".into(), - )); - } + p.insert("_dwg".into(), json!(pick("AutoCADExportFileFormat")? == "DWG")); } "exportOption" => { let preserve = if pick("AutoCADExportOption")? == "PreserveAppearance" { "appearance" } else { "editability" }; @@ -1007,9 +1004,17 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))), }, }; - // A DXF version before 2004 holds no true color: with `colors` left out it takes 256 indexed - // colors, and `AutoCADColors.TrueColors` with it throws. - if kind.format == "dxf" && matches!(p.get("version").and_then(Value::as_str), Some("R13" | "R14" | "2000")) { + // `AutoCADExportFileFormat.DWG` writes the same drawing as a DWG file. + let kind = match p.remove("_dwg") { + Some(Value::Bool(true)) => ExportKind { format: "dwg", extensions: &["dwg"], options: kind.options }, + _ => kind, + }; + if kind.format == "dwg" && matches!(p.get("version").and_then(Value::as_str), Some("R13" | "R14")) { + return Err(HostError::Error("AutoCADExportFileFormat.DWG needs AutoCADRelease15 or a later version".into())); + } + // A DXF or DWG version before 2004 holds no true color: with `colors` left out it takes 256 + // indexed colors, and `AutoCADColors.TrueColors` with it throws. + if matches!(kind.format, "dxf" | "dwg") && matches!(p.get("version").and_then(Value::as_str), Some("R13" | "R14" | "2000")) { match p.get("colors") { None => { p.insert("colors".into(), json!(256)); @@ -1027,8 +1032,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into())); } // A raster file has one pixel per point at 100%, whatever the document's raster effects resolution. - // A DXF's `scale` is its drawing units per unit, from `unitScaleRatio` divided by 100. - if !matches!(kind.format, "svg" | "dxf") { + // A DXF's or DWG's `scale` is its drawing units per unit, from `unitScaleRatio` divided by 100. + if !matches!(kind.format, "svg" | "dxf" | "dwg") { p.insert("scale".into(), json!(hs / 100.0)); } let format = if svgz { "svgz" } else { kind.format }; diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 5a58964284..a088f4afe1 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -661,10 +661,13 @@ fn dxf_xs(dxf: &str) -> Vec { xs } -/// `exportFile` with `ExportType.AutoCAD` writes a DXF with the `ExportOptionsAutoCAD` options, and -/// DWG, the help page's default format, throws without writing a file. +/// `exportFile` with `ExportType.AutoCAD` writes a DWG, the help page's default format, or a DXF +/// with the `ExportOptionsAutoCAD` options; a DWG of a release before 2000 throws without writing a +/// file. craft-dwg writes DWG everywhere but wasm32 and FreeBSD on aarch64. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] -fn an_autocad_export_writes_a_dxf_with_its_options() { +fn an_autocad_export_writes_a_dwg_or_a_dxf_with_its_options() { + vectorcraft_cad::dwg::allow_in_process(); let base = folder("autocad"); let mut s = session(&base); let dir = data_folder(&mut s, &base); @@ -676,7 +679,9 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ var o = new ExportOptionsAutoCAD(); vc.log([o.typename, o.exportFileFormat, o.version, ExportType.AUTOCAD === ExportType.AutoCAD]);\n\ - try {{ d.exportFile(new File(dir + '/w'), ExportType.AutoCAD, o); }} catch (e) {{ vc.log(String(e)); }}\n\ + d.exportFile(new File(dir + '/w'), ExportType.AutoCAD, o);\n\ + o.version = AutoCADCompatibility.AutoCADRelease14;\n\ + try {{ d.exportFile(new File(dir + '/old'), ExportType.AutoCAD, o); }} catch (e) {{ vc.log(String(e)); }}\n\ o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease15;\n\ o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 1000; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\ d.exportFile(new File(dir + '/a'), ExportType.AutoCAD, o);\n\ @@ -687,8 +692,11 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { ), ); assert_eq!(out[0], json!(["ExportOptionsAutoCAD", "AutoCADExportFileFormat.DWG", "AutoCADCompatibility.AutoCADRelease24", true])); - assert!(out[1].as_str().is_some_and(|e| e.contains("DWG is not available")), "{}", out[1]); - assert!(!dir.join("w.dxf").exists() && !dir.join("w.dwg").exists() && !dir.join("w").exists(), "DWG writes nothing"); + let w = std::fs::read(dir.join("w.dwg")).unwrap(); + assert_eq!(&w[..6], b"AC1024", "the default AutoCADRelease24 is the 2010 format"); + assert!(!dir.join("w.dxf").exists()); + assert!(out[1].as_str().is_some_and(|e| e.contains("DWG needs AutoCADRelease15")), "{}", out[1]); + assert!(!dir.join("old.dwg").exists() && !dir.join("old").exists(), "a refused DWG writes nothing"); let a = std::fs::read_to_string(dir.join("a.dxf")).unwrap(); let b = std::fs::read_to_string(dir.join("b.DXF")).unwrap(); assert!(!dir.join("b.DXF.dxf").exists(), "a name that ends with the extension keeps it"); @@ -1189,10 +1197,11 @@ fn bad_arguments_are_refused_with_an_error() { "from 0 to 100", ), (format!("app.activeDocument.exportFile({f}, ExportType.GIF, {{}});"), "not available yet"), - (format!("app.activeDocument.exportFile({f}, ExportType.AutoCAD);"), "DWG is not available"), ( - format!("var o = new ExportOptionsAutoCAD(); o.exportFileFormat = undefined; app.activeDocument.exportFile({f}, ExportType.AUTOCAD, o);"), - "DWG is not available", + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = undefined; o.version = AutoCADCompatibility.AutoCADRelease13; app.activeDocument.exportFile({f}, ExportType.AUTOCAD, o);" + ), + "DWG needs AutoCADRelease15", ), ( format!( diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index d8eaa4fd4d..ff4518ad73 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -900,7 +900,7 @@ fn errors_are_tool_results_not_crashes() { ("type_text", json!({"text": "hi"})), ("screenshot", json!({"window": true})), ("open_file", json!({"path": "/definitely/not/here.svg"})), - ("export", json!({"path": "/tmp/out.dwg"})), + ("export", json!({"path": "/tmp/out.pmd"})), ("redo", json!({})), ("press_key", json!({"key": "F13"})), ]; diff --git a/crates/ui-egui/src/dialogs/dxf_options.rs b/crates/ui-egui/src/dialogs/dxf_options.rs index a23a07e757..1d75fb1a94 100644 --- a/crates/ui-egui/src/dialogs/dxf_options.rs +++ b/crates/ui-egui/src/dialogs/dxf_options.rs @@ -2,11 +2,12 @@ //! cutting software and shows Custom again once one is changed), version, scale (1 unit of the //! art = N drawing units) and lineweights, number of colours, the format of placed images and //! Include Placed Images, Preserve Appearance or Maximize Editability, and Export Selected Art -//! Only, Alter Paths for Appearance, Outline Text and Include Fill Hatches. +//! Only, Alter Paths for Appearance, Outline Text and Include Fill Hatches. DWG Options (Export As +//! → DWG) is the same dialog for a DWG file of the same drawing, offering the versions from 2000. //! -//! Fields: `document.export` params (`format: dxf`, `path?`, the artboard choice) and the DXF -//! options of `document.exportDxf`. OK remembers the options for next time and writes the file -//! (asking where when there is no path); bad options keep the dialog open. +//! Fields: `document.export` params (`format: dxf|dwg`, `path?`, the artboard choice) and the DXF +//! options of `document.exportDxf`. OK remembers the options for next time (DXF and DWG share them) +//! and writes the file (asking where when there is no path); bad options keep the dialog open. use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; use craft::ui::display::{Shade, Text}; @@ -69,7 +70,12 @@ fn dialog_fields(map: &Map) -> DialogFields { /// The rows as far as their kinds go, for reading values to and from JSON. fn kinds() -> Vec { - rows(false, false, false) + rows(false, false, false, false) +} + +/// Is `format` (an id or extension) DWG? +fn is_dwg(format: Option<&str>) -> bool { + format.and_then(fileio::format).is_some_and(|f| f.id == "dwg") } /// Gives the dialog the fields the current preset sets and the others have lost (a change of the preset row removes @@ -104,12 +110,14 @@ pub(super) fn check_param(key: &str, label: &'static str) -> Param { } /// The rows. Export Selection leaves Export Selected Art Only out, as it writes the selected art alone; -/// without a selection that row is off. `note` shows the true-colour note. -fn rows(selection: bool, has_selection: bool, note: bool) -> Vec { +/// without a selection that row is off. `note` shows the true-colour note; `dwg` offers the versions a +/// DWG file is written as. +fn rows(selection: bool, has_selection: bool, note: bool, dwg: bool) -> Vec { let keys: Vec = preset_fields(DxfPreset::Custom).keys().cloned().collect(); + let versions = DxfVersion::ALL.iter().filter(|v| !dwg || vectorcraft_cad::dwg::writes(**v)); let mut rows = vec![ choice_param(PRESET, tl!("Preset:"), DxfPreset::ALL.iter().map(|p| (p.id(), p.label()))).resets(keys), - choice_param("version", tl!("Version:"), DxfVersion::ALL.iter().map(|v| (v.id(), v.label()))), + choice_param("version", tl!("Version:"), versions.map(|v| (v.id(), v.label()))), scale_param(None), check_param("scaleLineweights", tl!("Scale Lineweights")), choice_param("colors", tl!("Number of Colors:"), ColorDepth::ALL.iter().map(|c| (c.id(), c.label()))), @@ -179,17 +187,25 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) { /// [`open`] for Export Selection when `selection` is set: the options then write the selected art alone. pub fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) { + let dwg = is_dwg(params.get("format").and_then(Value::as_str)); let mut fields = defaults(); if let Some(o) = app.ui.dxf_options.as_object() { fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))); } + // DWG Options start on the default version when the version used last is one a DWG isn't + // written as; a version `params` gives is kept, for OK to refuse. + // `version` may be a number: 2018 and "2018" alike. + let version = fields.get("version").and_then(|v| DxfVersion::from_id(&v.as_str().map_or_else(|| v.to_string(), str::to_string))); + if dwg && !version.is_some_and(vectorcraft_cad::dwg::writes) { + fields.insert("version".into(), json!(DxfVersion::default().id())); + } if let Some(o) = params.as_object() { if let Some(p) = o.get(PRESET).and_then(Value::as_str).and_then(DxfPreset::from_id) { fields.extend(preset_fields(p)); } fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))); } - fields.insert("format".into(), json!("dxf")); + fields.insert("format".into(), json!(if dwg { "dwg" } else { "dxf" })); let mut values = dialog_fields(&fields); settle(&mut values); let has_selection = app.session.active().is_some_and(|st| !st.selection.is_empty()); @@ -198,10 +214,9 @@ pub fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) { settle(fields); let note = fields.text("colors").and_then(ColorDepth::from_id) == Some(ColorDepth::True) && fields.text("version").and_then(DxfVersion::from_id).unwrap_or_default() < DxfVersion::R2004; - ParamDialog::new(KIND, tl!("DXF Options"), rows(selection, has_selection, note)) - .values(Bind::bound(fields)) - .ok_label(tl!("Export").into()) - .below(|ui, fields| { + let heading = if dwg { tl!("DWG Options") } else { tl!("DXF Options") }; + ParamDialog::new(KIND, heading, rows(selection, has_selection, note, dwg)).values(Bind::bound(fields)).ok_label(tl!("Export").into()).below( + |ui, fields| { Text::new(match fields.text("preserve").and_then(Preserve::from_id).unwrap_or_default() { Preserve::Appearance => tl!("Type becomes outlines, and strokes a CAD line can't draw become filled shapes."), Preserve::Editability => tl!("Type stays text, and every stroke is a line with its lineweight and dashes."), @@ -209,7 +224,8 @@ pub fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) { .role(TypeRole::Caption) .shade(Shade::Muted) .show(ui); - }) + }, + ) }); export_host::open(app, Export::Dxf, selection, dialog); } @@ -220,7 +236,8 @@ pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFiel // drawing) counts as drawn. let mut fields = fields.clone(); settle(&mut fields); - let map = form::json_of(&rows(open.selection, true, false), &fields); + let format = if is_dwg(fields.text("format")) { "dwg" } else { "dxf" }; + let map = form::json_of(&rows(open.selection, true, false, false), &fields); let params = Value::Object(map.clone()); fileio::dxf::check(¶ms)?; // Nothing selected keeps the dialog open too. @@ -229,5 +246,5 @@ pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFiel } app.ui.dxf_options = Value::Object(map.into_iter().filter(|(k, _)| !PER_EXPORT.contains(&k.as_str())).collect()); let path = fields.text("path").map(str::to_string); - io::export(app, Some("dxf"), path, &super::export_as::exported(open.selection, params)).map(|_| None) + io::export(app, Some(format), path, &super::export_as::exported(open.selection, params)).map(|_| None) } diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index e98d212976..0e78837610 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -2,8 +2,8 @@ //! artboard, after a central file of the whole document for EPS with two or more when art shows, //! or one page each in a PDF); without artboards the export covers the visible art. OK //! picks the file, then the format's options dialog follows (PNG/JPEG/WebP/PNG-8/GIF Options, SVG -//! Options, Text Export Options, DXF Options, EPS Options, HP-GL Options, and Save PDF), -//! else the file is written. DWG is listed, greyed out, with what to use instead. The formats of +//! Options, Text Export Options, DXF Options, DWG Options, EPS Options, HP-GL Options, and Save +//! PDF), else the file is written. The formats of //! installed exporter plug-ins come after the built-in ones: they write the whole document (from //! Export Selection, the selection), and one with parameters asks for them before writing //! (`plugin::open_export`). Export Selection ([`export_selection`]) takes the same route after its @@ -29,8 +29,6 @@ pub(super) const KIND: &str = "exportAs"; /// The built-in formats Export As writes (the native format and `.ai` are Save As's). static BUILT_IN: LazyLock> = LazyLock::new(|| fileio::FORMATS.iter().filter(|f| f.write && !matches!(f.id, "vectorcraft" | "ai")).collect()); -/// Formats listed after them that can't be written (`fileio::write_hint` ids), greyed out. -const UNAVAILABLE: [(&str, &str); 1] = [("dwg", "DWG (use DXF)")]; /// The formats Export As writes: the built-in ones, then those of the installed exporter plug-ins. pub(super) fn formats() -> Vec<&'static Format> { @@ -42,13 +40,6 @@ fn from_plugin(f: &Format) -> bool { vectorcraft_plugins::export::by_format(f.id).is_some() } -/// What to use instead when the format field names a format that can't be written (DWG). -fn unavailable(fields: &DialogFields) -> Option<(&'static str, &'static str)> { - let id = fields.text("format")?; - let (_, label) = UNAVAILABLE.iter().find(|u| u.0 == id)?; - Some((label, fileio::write_hint(id)?)) -} - /// The chosen format (PNG when the field names none Export As writes). fn chosen(fields: &DialogFields) -> Option<&'static Format> { let all = formats(); @@ -64,7 +55,7 @@ fn is_all(fields: &DialogFields) -> bool { /// The rows, from the formats installed now. fn params() -> Vec { let all = formats(); - let choices = all.iter().map(|f| (f.id, f.label)).chain(UNAVAILABLE); + let choices = all.iter().map(|f| (f.id, f.label)); // An exporter plug-in writes the whole document: Use Artboards is not its to apply. let whole: Vec<&str> = all.iter().filter(|f| !from_plugin(f)).map(|f| f.id).collect(); vec![ @@ -72,8 +63,7 @@ fn params() -> Vec { "format", tl!("Format:"), ParamKind::choice(choices.map(|(id, label)| (id.to_string(), Label::from(label))).collect(), Some("png".into())), - ) - .disabled_options(UNAVAILABLE.map(|u| u.0)), + ), Param::new("useArtboards", tl!("Use Artboards"), ParamKind::bool(false)).enabled_when_in("format", whole), Param::new( "all", @@ -85,11 +75,8 @@ fn params() -> Vec { ] } -/// The line under the rows: what the export writes, or what to use instead of DWG. +/// The line under the rows: what the export writes. fn summary(fields: &DialogFields) -> String { - if let Some((_, hint)) = unavailable(fields) { - return hint.to_string(); - } let Some(f) = chosen(fields) else { return String::new() }; let whole = from_plugin(f); let use_artboards = fields.bool("useArtboards").unwrap_or(false) && !whole; @@ -114,11 +101,7 @@ fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Res let source = app.session.active(); let document = source.map(|source| (source.uid, source.reverts)); let n = source.map_or(0, |source| source.doc.artboards.len()); - let missing = format.and_then(|f| UNAVAILABLE.iter().find(|u| u.0.eq_ignore_ascii_case(f.trim_start_matches('.')))); - let format = match missing { - Some((id, _)) => id, - None => format.and_then(fileio::format).filter(|f| formats().iter().any(|g| g.id == f.id)).map_or("png", |f| f.id), - }; + let format = format.and_then(fileio::format).filter(|f| formats().iter().any(|g| g.id == f.id)).map_or("png", |f| f.id); let range = p.get("range").and_then(Value::as_str); let initial = json!({ "format": format, @@ -152,9 +135,6 @@ fn require_source(app: &VectorcraftApp, document: Option<(u64, u64)>) -> Result< /// the file follow once the dialog has closed. pub(super) fn confirm(app: &mut VectorcraftApp, document: Option<(u64, u64)>, fields: &DialogFields) -> Result { require_source(app, document)?; - if let Some((_, hint)) = unavailable(fields) { - return Err(hint.into()); - } let f = chosen(fields).ok_or("no format to export to")?; let plugin = vectorcraft_plugins::export::by_format(f.id); let use_artboards = fields.bool("useArtboards").unwrap_or(false) && plugin.is_none(); @@ -273,7 +253,7 @@ fn options_or_write( return Ok(Value::Null); } match f.id { - "dxf" => dxf_options::open(app, ¶ms), + "dxf" | "dwg" => dxf_options::open(app, ¶ms), "eps" => eps_options::open(app, ¶ms), "hpgl" => hpgl_options::open(app, ¶ms), _ => return io::export(app, Some(f.id), Some(path), ¶ms), diff --git a/crates/ui-egui/src/dialogs/tests_dxf.rs b/crates/ui-egui/src/dialogs/tests_dxf.rs index de20d0fde1..158c0fe596 100644 --- a/crates/ui-egui/src/dialogs/tests_dxf.rs +++ b/crates/ui-egui/src/dialogs/tests_dxf.rs @@ -1,4 +1,4 @@ -//! Export As → DXF Options, and DWG listed as unavailable, drawn headlessly. +//! Export As → DXF Options and DWG Options, drawn headlessly. use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; use serde_json::json; @@ -175,17 +175,43 @@ fn bad_dxf_options_keep_the_dialog_open() { assert_eq!(names(&written), ["/out/a.dxf"]); } +/// craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD on aarch64. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] -fn dwg_is_listed_but_points_to_dxf() { +fn export_as_dwg_shows_dwg_options_then_writes_a_dwg() { + vectorcraft_engine::dwg::allow_in_process(); let (mut app, written) = app(1); + // A version used last that a DWG isn't written as: DWG Options start on 2018, the other options carry over. + app.ui.dxf_options = json!({"version": "R12", "unit": "Inches"}); app.run("file.exportAs", json!({"format": "dwg"})).unwrap(); assert_eq!(show(&fields(&app), "format"), "dwg"); frame(&mut app); - let e = try_confirm(&mut app).unwrap_err(); - assert!(e.contains("DWG") && e.contains("DXF"), "{e}"); - assert_eq!(kind(&app).as_deref(), Some("exportAs"), "the dialog stays open to pick DXF"); - set(&mut app, "format", json!("dxf")); confirm(&mut app); + assert_eq!(kind(&app).as_deref(), Some("dxfOptions"), "DWG Options follow"); + let d = fields(&app); + let shown = [show(&d, "format"), show(&d, "path"), show(&d, "version"), show(&d, "unit")]; + assert_eq!(shown, ["dwg", "/out/Untitled-1.dwg", "2018", "Inches"]); + frame(&mut app); + // The version row offers the versions from 2000. + assert!(try_set(&mut app, "version", json!("R14")).is_err()); + set(&mut app, "version", json!("2000")); + frame(&mut app); + confirm(&mut app); + assert!(kind(&app).is_none()); + assert_eq!(names(&written), ["/out/Untitled-1.dwg"]); + assert_eq!(&written.borrow()[0].1[..6], b"AC1015"); + assert_eq!(app.ui.dxf_options["version"].as_str(), Some("2000"), "DXF and DWG share the options"); + // A version the command gives is kept, and OK refuses it. + app.run("ui.dxfOptionsDialog", json!({"format": "dwg", "version": "R13", "path": "/out/b.dwg"})).unwrap(); + assert_eq!(show(&fields(&app), "version"), "R13"); + let e = try_confirm(&mut app).unwrap_err(); + assert!(e.contains("DWG version `R13`"), "{e}"); assert_eq!(kind(&app).as_deref(), Some("dxfOptions")); - assert!(written.borrow().is_empty()); + assert_eq!(written.borrow().len(), 1); + // DXF Options still offer every DXF version. + cancel(&mut app); + app.run("ui.dxfOptionsDialog", json!({"path": "/out/c.dxf"})).unwrap(); + set(&mut app, "version", json!("R14")); + confirm(&mut app); + assert!(text(&written.borrow()[1].1).contains("AC1014")); } diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index 8d311212aa..5d08bbf110 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -437,7 +437,7 @@ mod tests { assert!(vectorcraft_format::sniff(&w[1].1)); assert_eq!(app.session.active().unwrap().path.as_deref(), Some("/tmp/doc.vectorcraft")); drop(w); - assert!(export(&mut app, None, Some("/tmp/x.dwg".into()), &Value::Null).is_err(), "DWG can't be written"); + assert!(export(&mut app, None, Some("/tmp/x.pmd".into()), &Value::Null).is_err(), "PageMaker can't be written"); } #[test] diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index ebdb694870..d8cb62ecde 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1757,7 +1757,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.dxfOptionsDialog", "DXF Options Dialog", "", - "{path?, useArtboards?, range?, …document.exportDxf options} open DXF Options (dialog `dxfOptions`: fields = these options over the ones used last, a dxfPreset's options under them; the dxfPreset field shows cnc while every field it sets matches, else custom); OK checks them, remembers them and writes path (else asks). Export As… → DXF opens it too", + "{format?: dxf (default)|dwg, path?, useArtboards?, range?, …document.exportDxf options} open DXF Options, or DWG Options for format: dwg (dialog `dxfOptions`: fields = these options over the ones used last, a dxfPreset's options under them; the dxfPreset field shows cnc while every field it sets matches, else custom; DWG offers the versions from 2000, and a version used last that DWG isn't written as starts on 2018); OK checks them, remembers them and writes path (else asks). Export As… → DXF or DWG opens it too", ), ( "links.editOriginal", diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 23ab4f671a..99fdedfa29 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -881,8 +881,10 @@ Placed Images), `preserve` (`appearance`, `editability`), `selectedOnly`, `alter `cnc` sets the fields it sets (see `document.exportDxf`), and `dxfPreset` reads `custom` again once one of them is changed; setting it to `custom` puts back the defaults. `ui.dialog.confirm` checks them (a bad value, or Export Selected Art Only with nothing selected, keeps the dialog open), remembers them for the next DXF Options and -writes the file (asking for a path when there is none). Export As also lists DWG, greyed out: setting its `format` to -`dwg` shows, and on confirm answers, the hint to export DXF instead. +writes the file (asking for a path when there is none). Export As → DWG, and `ui.dxfOptionsDialog` with +`format: "dwg"`, open the same dialog as DWG Options: its `version` offers `2000` to `2018`, a version remembered from +DXF Options that a DWG isn't written as starts on `2018`, and OK writes a `.dwg` file. DXF and DWG Options share the +remembered options. DXF Import Options: opening a DXF drawing through the app (`app.open`, `file.open`, a drop) or placing one (`file.place` with a `.dxf` file and no `dxf` options, which answers `{"dialog": "dxfImport"}`) opens the `dxfImport` diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 31f0da4316..3f834f89b3 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -63,7 +63,7 @@ Ordinary File > Save offers Save As when its own location refuses writes with a |---|---:|---:|---| | Formats opened or placed | ~30 | 37 | missing: FreeHand | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, gradients, patterns, images, type, symbols, artboards, transparency, opacity masks, clipping, text wrap options) or as legacy version 7 (layers and groups, one artboard per file) | -| Formats exported | ~16 | 20 | missing: DWG; extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | +| Formats exported | ~16 | 21 | extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | EPS editing-data follow-up (2026-10-16): both mesh-corner layouts (with and without opacity) @@ -373,7 +373,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as ``, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); a masked group, or a knockout group's masked group, whose content has a shadow, glow, blur or feather starts with a hidden, unpainted rectangle over the mask's region, so readers that draw a masked group only inside the box of its shapes draw those effects too (`crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`); SVG Options › Units writes `width` and `height` in px (bare numbers, the default), pt, mm, cm or in, the `viewBox` staying in points, for software that reads physical size such as LaserGRBL (#4462, `crates/svg/tests/it/roundtrip.rs`) | | DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open | | HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines; Export As opens HP-GL Options) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | -| DWG | open, export | yes (open and place: craft-dwg converts the drawing to DXF, in a child process on desktop, and the DXF reader reads it with the DXF import options) | no (export DXF instead) | `crates/cad/src/import/tests_dwg.rs`, `crates/engine/src/cmd/fileio/tests_dwgimport.rs` (drawings written as DXF and converted to DWG by craft-dwg's writer); not in the web build | +| DWG | open, export | yes (open and place: craft-dwg converts the drawing to DXF, in a child process on desktop, and the DXF reader reads it with the DXF import options) | yes (2000–2018, the drawing the DXF export writes, converted by craft-dwg in a child process on desktop; DWG Options; R12, R13 and R14 refused) | `crates/cad/src/import/tests_dwg.rs`, `crates/engine/src/cmd/fileio/tests_dwgimport.rs` (drawings written as DXF and converted to DWG by craft-dwg's writer; exported DWG files opened again), `crates/ui-egui/src/dialogs/tests_dxf.rs`; not in the web build | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776); a picture cut short by a reader limit, images and pattern brushes that are not read, clips that are not applied and raster operations other than a plain copy come back as warnings; tests in `crates/metafile/src/tests/import.rs` | | PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability, point type as editable type layers with `preserveText`; `tests_psd.rs`) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) | | PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | | diff --git a/docs/mcp.md b/docs/mcp.md index 2fd8648262..24fcbb70a5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3509,8 +3509,9 @@ through `$`: `unitScaleRatio`, which have none there, default to true colors, PNG, millimeters and 100, VectorCraft's own values. `AutoCADRelease13`, `14` and `15` hold no true color: with them `colors` defaults to `Max256Colors`, and `AutoCADColors.TrueColors` throws an error. - `AutoCADExportFileFormat.DWG`, the help page's default, throws an error that says DWG is not available, so an - AutoCAD export sets `exportFileFormat` to `AutoCADExportFileFormat.DXF`. The enumerations `AutoCADColors`, + `AutoCADExportFileFormat.DWG`, the help page's default, writes a `.dwg` file of the drawing the DXF export writes, + and `AutoCADExportFileFormat.DXF` writes a `.dxf` file. A DWG is written as `AutoCADRelease15` (2000) or later: + `AutoCADRelease13` and `14` with DWG throw an error that names `AutoCADRelease15`. The enumerations `AutoCADColors`, `AutoCADCompatibility`, `AutoCADExportFileFormat`, `AutoCADExportOption`, `AutoCADRasterFormat` and `AutoCADUnit` hold the members the scripting constants page lists. `app.open`'s `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with @@ -12670,9 +12671,14 @@ blending, opacity masks, raster effects, clipping) comes back in `warnings`. In no linked file, and `warnings` carries "an image couldn't be decoded and is missing from the picture" once for all such images. -DWG drawings open and place (see DXF import) but can't be written: `document.formats` lists `dwg` as readable and -not writable, and exporting to it answers with the hint to export DXF. PICT files open and place (see PICT -import) but can't be written. +`document.export` with `format: "dwg"` (or a `.dwg` path, or `document.exportDxf` with `format: "dwg"`) writes the +drawing the DXF export writes, with the same options, as a DWG file: craft-dwg converts it, in the `--dwg-worker` +copy of the program in the desktop app and `vectorcraft-cli` (see DXF import). `version` is `2000`, `2004`, `2007`, +`2010`, `2013` or `2018` (default); `R12`, `R13` and `R14` are refused with an error that names these. Placed images +are written next to the file as for DXF. Records the DWG writer can't write in the chosen version are left out, and +`warnings` carries "DWG: n records of this drawing can't be written in this DWG version and were left out" with their +DXF types. Export As → DWG opens DWG Options, the DXF Options dialog with the DWG versions. The web build answers an +error that says to save as DXF. PICT files open and place (see PICT import) but can't be written. ```json {"name":"run_command","arguments":{"command":"document.exportDxf","params":{"path":"/tmp/plan.dxf","version":"2013","unit":"mm","scale":10,"preserve":"editability"}}} diff --git a/docs/roadmap.md b/docs/roadmap.md index a86bbe6ebe..f6cafcea06 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -199,7 +199,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them); Layers own appearance has a hollow diamond and tooltip distinct from targeting/selection (#8710), retaining Hassan1305's #8757 ring-visibility fix; validation pending | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); View › Snapping consolidates five existing toggles and Pixel Snapping Options…, retaining top-level entries and shortcuts (G13); Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655); in a document with more than 20,000 anchors the topmost, newest objects keep their Smart Guides targets (#8531) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028; Recolor with Preset asks whether to limit the colors to a swatch library first); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); the stop editor offers the five Color panel modes (#7918); native port validation pending | 4–8 | -| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | DWG import: DWG drawings open and place through the DXF reader (#10802; estimates unchanged); `.ai` import: type takes the installed copy of its font that sets its PDF part's widths (#8087; estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG export (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; View and Links controls and command access for transient missing-link canvas markers (#5547); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | +| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | DWG import: DWG drawings open and place through the DXF reader (#10802; estimates unchanged); DWG export: Export As → DWG writes the DXF export's drawing as DWG 2000 to 2018 (estimates unchanged); `.ai` import: type takes the installed copy of its font that sets its PDF part's widths (#8087; estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG export as R13 and R14, PSD placement as layers, overprint read back from PDF, Affinity export, polish; View and Links controls and command access for transient missing-link canvas markers (#5547); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; in the web build an edit while the view of a heavy document moves draws only the part it changed into the last frame (#8688); dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934), keeping even spacing as tracking and making stacked, aligned lines one area type object; Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders done (#1880); vertical type in progress (Type › Type Orientation, #5027) | 45–60 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 99255fa880..5649e233a3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1132,7 +1132,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; compound paths expose `PathItems` objects and reject unsupported path creation; `removeAll()` on a compound path's `pathItems` throws when it would empty a compound path that clips a group or layer keeping other objects that are not ruler guides. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`. - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`. - - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available, and `unitScaleRatio` is a percentage, with 100 at full size (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. + - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DWG file (`AutoCADExportFileFormat.DWG`, the default; version 2000 or later) or a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe, and `unitScaleRatio` is a percentage, with 100 at full size (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`); a batch submitted after a spool failure was reported clears it once the worker sends every job of the batch without a failure, while a failure reported after submission stays. `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). @@ -2566,7 +2566,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - DXF export with Use Artboards applies live effects and places symbols' art once for all the artboards' drawings instead of once for each drawing; each drawing's bytes, linked images, warnings and notes are the same as before (`drawings_apply_the_live_effects_once_and_match_drawings_written_alone`, `each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone`). - - DWG drawings open and place in the desktop build, and `document.dxfInfo` reads them: craft-dwg converts the drawing to DXF, in a copy of the app started with `--dwg-worker`, off the UI thread when the user opens or places it, and the DXF reader reads it with the DXF Import Options. The web build and R1.x and R2.x drawings return an error that says to save the drawing as DXF. DWG is not written: Export As keeps it greyed out, exporting to it says to export DXF, and Save over the drawing is refused (`a_dwg_drawing_comes_in_as_its_dxf_does`, `document_open_reads_a_dwg_drawing_as_its_dxf`, `dxf_info_and_place_read_a_dwg`, `a_dwg_opened_is_never_written_back_as_dwg`; scores and estimates unchanged). + - DWG drawings open and place in the desktop build, and `document.dxfInfo` reads them: craft-dwg converts the drawing to DXF, in a copy of the app started with `--dwg-worker`, off the UI thread when the user opens or places it, and the DXF reader reads it with the DXF Import Options. The web build and R1.x and R2.x drawings return an error that says to save the drawing as DXF. Save over the drawing is refused (`a_dwg_drawing_comes_in_as_its_dxf_does`, `document_open_reads_a_dwg_drawing_as_its_dxf`, `dxf_info_and_place_read_a_dwg`, `a_dwg_opened_is_never_written_back_as_dwg`; scores and estimates unchanged). + - DWG export (https://helpx.adobe.com/illustrator/using/supported-file-formats.html, https://helpx.adobe.com/illustrator/using/exporting-artwork.html): Export As → DWG, `document.export {format: dwg}` and a script's `AutoCADExportFileFormat.DWG` write the drawing the DXF export writes as a DWG file of version 2000, 2004, 2007, 2010, 2013 or 2018, converted by craft-dwg in the `--dwg-worker` copy of the app. DWG Options is DXF Options with those versions; R12, R13 and R14 are refused with an error that names them. Records the DWG writer can't write in the chosen version are left out with a warning (`document_export_writes_a_dwg_that_opens_as_the_drawing_its_dxf_holds`, `a_dwg_version_before_2000_is_refused_and_nothing_is_written`, `export_as_dwg_shows_dwg_options_then_writes_a_dwg`, `an_autocad_export_writes_a_dwg_or_a_dxf_with_its_options`; scores and estimates unchanged). - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `craft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill, or scaled with the object's matrix, where the file says so), an object without a fill or outline of its own taking its style's, hidden and locked layers, groups and objects, the winding flag as the nonzero fill rule, and a uniform transparency of version 13 and later as the object's opacity and blend mode. A library color stored with its name and values (version 13 and later, in a fill or an outline) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, other transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`). Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`craft-cdr` `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - `.cmx` exchange files with 32-bit coordinates open and place: `craft-cdr` reads their color, pen, line type, dash and outline tables and each page's instructions, and the importer maps pages, layers (a layer that holds nothing is left out), groups and curves, with uniform fills and outlines, as it maps a `.cdr` drawing's. Text, images, rectangles, ellipses, clipping paths, other fills, arrowheads and lenses are named in the warnings, and big-endian files and files with 16-bit coordinates are refused with a message (`craft-cdr` `storytold/craft-libs@9b28b56bc7` `crates/cdr/tests/it/cmx.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs`, `crates/engine/tests/import_fuzz.rs`). From b6860419878bc6b7e55279e38b74526962eace19 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 15:53:43 -0800 Subject: [PATCH 52/88] DWG: MCP catalog mirror and docs follow DWG Options - crates/mcp/src/ui_catalog.rs: ui.dxfOptionsDialog carries the description crates/ui-egui/src/menus/ui_commands.rs gives it, with format: dwg and DWG Options, so `cargo xtask ui-commands --check` passes. - docs/target-app-parity.md: the DWG export and script export entries say that writing DWG needs the --dwg-worker copy of the program in the desktop app and vectorcraft-cli, and returns an error in the web build. --- crates/mcp/src/ui_catalog.rs | 2 +- docs/target-app-parity.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 62d9ac97f8..a0bdd4ffd5 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1756,7 +1756,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.dxfOptionsDialog", "DXF Options Dialog", "", - "{path?, useArtboards?, range?, …document.exportDxf options} open DXF Options (dialog `dxfOptions`: fields = these options over the ones used last, a dxfPreset's options under them; the dxfPreset field shows cnc while every field it sets matches, else custom); OK checks them, remembers them and writes path (else asks). Export As… → DXF opens it too", + "{format?: dxf (default)|dwg, path?, useArtboards?, range?, …document.exportDxf options} open DXF Options, or DWG Options for format: dwg (dialog `dxfOptions`: fields = these options over the ones used last, a dxfPreset's options under them; the dxfPreset field shows cnc while every field it sets matches, else custom; DWG offers the versions from 2000, and a version used last that DWG isn't written as starts on 2018); OK checks them, remembers them and writes path (else asks). Export As… → DXF or DWG opens it too", ), ( "links.editOriginal", diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d360530d39..13a08451af 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1132,7 +1132,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; compound paths expose `PathItems` objects and reject unsupported path creation; `removeAll()` on a compound path's `pathItems` throws when it would empty a compound path that clips a group or layer keeping other objects that are not ruler guides. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`. - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`. - - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DWG file (`AutoCADExportFileFormat.DWG`, the default; version 2000 or later) or a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe, and `unitScaleRatio` is a percentage, with 100 at full size (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. + - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DWG file (`AutoCADExportFileFormat.DWG`, the default; version 2000 or later; desktop app and `vectorcraft-cli` only, through the `--dwg-worker` copy of the program, so the web build throws an error) or a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe, and `unitScaleRatio` is a percentage, with 100 at full size (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`); a batch submitted after a spool failure was reported clears it once the worker sends every job of the batch without a failure, while a failure reported after submission stays. `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). @@ -2567,7 +2567,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - DXF export with Use Artboards applies live effects and places symbols' art once for all the artboards' drawings instead of once for each drawing; each drawing's bytes, linked images, warnings and notes are the same as before (`drawings_apply_the_live_effects_once_and_match_drawings_written_alone`, `each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone`). - DWG drawings open and place in the desktop build, and `document.dxfInfo` reads them: craft-dwg converts the drawing to DXF, in a copy of the app started with `--dwg-worker`, off the UI thread when the user opens or places it, and the DXF reader reads it with the DXF Import Options. The web build and R1.x and R2.x drawings return an error that says to save the drawing as DXF. Save over the drawing is refused (`a_dwg_drawing_comes_in_as_its_dxf_does`, `document_open_reads_a_dwg_drawing_as_its_dxf`, `dxf_info_and_place_read_a_dwg`, `a_dwg_opened_is_never_written_back_as_dwg`; scores and estimates unchanged). - - DWG export (https://helpx.adobe.com/illustrator/using/supported-file-formats.html, https://helpx.adobe.com/illustrator/using/exporting-artwork.html): Export As → DWG, `document.export {format: dwg}` and a script's `AutoCADExportFileFormat.DWG` write the drawing the DXF export writes as a DWG file of version 2000, 2004, 2007, 2010, 2013 or 2018, converted by craft-dwg in the `--dwg-worker` copy of the app. DWG Options is DXF Options with those versions; R12, R13 and R14 are refused with an error that names them. Records the DWG writer can't write in the chosen version are left out with a warning (`document_export_writes_a_dwg_that_opens_as_the_drawing_its_dxf_holds`, `a_dwg_version_before_2000_is_refused_and_nothing_is_written`, `export_as_dwg_shows_dwg_options_then_writes_a_dwg`, `an_autocad_export_writes_a_dwg_or_a_dxf_with_its_options`; scores and estimates unchanged). + - DWG export (https://helpx.adobe.com/illustrator/using/supported-file-formats.html, https://helpx.adobe.com/illustrator/using/exporting-artwork.html): Export As → DWG, `document.export {format: dwg}` and a script's `AutoCADExportFileFormat.DWG` write the drawing the DXF export writes as a DWG file of version 2000, 2004, 2007, 2010, 2013 or 2018, converted by craft-dwg in the `--dwg-worker` copy of the app, in the desktop app and `vectorcraft-cli`. The web build can't write DWG, and these paths return an error there. DWG Options is DXF Options with those versions; R12, R13 and R14 are refused with an error that names them. Records the DWG writer can't write in the chosen version are left out with a warning (`document_export_writes_a_dwg_that_opens_as_the_drawing_its_dxf_holds`, `a_dwg_version_before_2000_is_refused_and_nothing_is_written`, `export_as_dwg_shows_dwg_options_then_writes_a_dwg`, `an_autocad_export_writes_a_dwg_or_a_dxf_with_its_options`; scores and estimates unchanged). - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `craft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill, or scaled with the object's matrix, where the file says so), an object without a fill or outline of its own taking its style's, hidden and locked layers, groups and objects, the winding flag as the nonzero fill rule, and a uniform transparency of version 13 and later as the object's opacity and blend mode. A library color stored with its name and values (version 13 and later, in a fill or an outline) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, other transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`). Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`craft-cdr` `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). - `.cmx` exchange files with 32-bit coordinates open and place: `craft-cdr` reads their color, pen, line type, dash and outline tables and each page's instructions, and the importer maps pages, layers (a layer that holds nothing is left out), groups and curves, with uniform fills and outlines, as it maps a `.cdr` drawing's. Text, images, rectangles, ellipses, clipping paths, other fills, arrowheads and lenses are named in the warnings, and big-endian files and files with 16-bit coordinates are refused with a message (`craft-cdr` `storytold/craft-libs@9b28b56bc7` `crates/cdr/tests/it/cmx.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs`, `crates/engine/tests/import_fuzz.rs`). From 9ef408dbd8921354a7422088a82eb5161faa3d5a Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 16:20:39 -0800 Subject: [PATCH 53/88] File formats: CGM files open and place File > Open and File > Place read Computer Graphics Metafiles in the binary encoding of ISO/IEC 8632-3 (.cgm), and a binary CGM also opens by its content. The first picture comes in on one artboard, its VDC extent at its metric scale or 576 pt on its longer side, with the extent's first corner at the bottom left. - Polylines, disjoint polylines, polybeziers and open arcs are stroked with the line width, color, type, caps and joins, and line types the picture defines take their dashes from it. - Polygons, polygon sets, rectangles, circles, ellipses, closed arcs and figures are filled by the interior style and outlined with the edge attributes while edges are visible. - Markers become small paths, text becomes point type in the font the font list names, and cell arrays become images. - The clip rectangle clips what follows it. craft-metafile's CGM reader (craft-libs#5410) plays the picture into the same model as the PICT reader, so it becomes document objects the same way; craft-metafile is pinned at that pull request's head until it merges. Place puts the picture in one group clipped to its frame. What isn't read comes back as warnings, a picture cut short keeps what came before it, and clear text and character encoded files are refused with a message. CGM is not written. Docs: docs/mcp.md, docs/file-format-parity.md, docs/target-app-parity.md. --- Cargo.lock | 2 +- Cargo.toml | 4 +- crates/engine/src/cmd/fileio.rs | 4 +- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/formats.rs | 11 +- crates/engine/src/cmd/fileio/load.rs | 7 + crates/engine/src/cmd/fileio/metafile.rs | 9 +- crates/engine/src/cmd/fileio/tests_cgm.rs | 118 ++++++ crates/engine/src/cmd/place.rs | 4 +- crates/engine/tests/import_fuzz.rs | 114 +++++- crates/metafile/Cargo.toml | 2 +- crates/metafile/src/import.rs | 32 +- crates/metafile/src/lib.rs | 15 +- crates/metafile/src/tests.rs | 1 + crates/metafile/src/tests/cgm.rs | 441 ++++++++++++++++++++++ docs/file-format-parity.md | 3 +- docs/mcp.md | 41 +- docs/target-app-parity.md | 1 + 18 files changed, 793 insertions(+), 18 deletions(-) create mode 100644 crates/engine/src/cmd/fileio/tests_cgm.rs create mode 100644 crates/metafile/src/tests/cgm.rs diff --git a/Cargo.lock b/Cargo.lock index b53df9115b..2a7ac2cb80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1852,7 +1852,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=800ea5b587058832ed118c680cdba16b36789340#800ea5b587058832ed118c680cdba16b36789340" dependencies = [ "encoding_rs", "image", diff --git a/Cargo.toml b/Cargo.toml index 89a8feda76..fe8a7213b0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,8 +36,8 @@ craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "77ade5 craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } # DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified). craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -# WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +# WMF, EMF and EMF+ reader (craft-libs#778), and the binary CGM reader (craft-libs#5410). +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "800ea5b587058832ed118c680cdba16b36789340" } craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 1a24bf623b..22d4f28333 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -16,7 +16,7 @@ //! - `dxf`: DXF export options, `document.exportDxf`, and the formats that can't be written (DWG, PageMaker). //! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`. //! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`. -//! - `metafile`: EMF and WMF export, open and place; PICT open and place. +//! - `metafile`: EMF and WMF export, open and place; PICT and CGM open and place. //! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, and `.cmx` files with //! 32-bit coordinates, open and place. //! - `cmx`: `.cmx` export (a page for each chosen artboard, a layer for each layer with art on it). @@ -246,6 +246,8 @@ mod tests_svgimport; #[cfg(test)] mod tests_eps; +#[cfg(test)] +mod tests_cgm; #[cfg(test)] mod tests_dwgimport; #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 94565b3ce8..9e0cb072fa 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a file with that PieceInfo key: its trim box when no box is named, its crop box with cropTo: crop or crop: crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a file with that PieceInfo key: its trim box when no box is named, its crop box with cropTo: crop or crop: crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), binary CGM .cgm (the first picture: one artboard, its VDC extent at its metric scale, else 576 pt on its longer side; lines, shapes and markers as paths, text as point type, cell arrays as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index f8da5b941c..1d362fd1e6 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -558,6 +558,9 @@ pub const FORMATS: &[Format] = &[ Format { id: "cmx", label: "CMX", extensions: &["cmx"], mime: "image/x-cmx", read: true, write: true, raster: false, options: cmx::OPTIONS }, // QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images. reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false), + // Binary Computer Graphics Metafiles, read by `vectorcraft_metafile::import_cgm` into paths, + // type and images. + reader("cgm", "CGM", &["cgm"], "image/cgm", false), // Layered raster `.pcraft` documents, read by `pcraftread` as one image: the full-size // composite, the layers combined, or the preview with a note. Exports don't write them. reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true), @@ -611,6 +614,7 @@ pub const OPEN_EXTS: &[&str] = &[ "pct", "pic", "pict", + "cgm", "plt", "hpgl", "hgl", @@ -633,11 +637,11 @@ pub const OPEN_EXTS: &[&str] = &[ /// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib` and `.rle` names of /// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS /// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it. -/// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft` -/// documents or DWG drawings either. +/// The packaging declares no type for HP-GL plot files, PICT pictures, CGM files, layered raster +/// `.pcraft` documents or DWG drawings either. pub const UNASSOCIATED_EXTS: &[&str] = &[ "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc", - "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", + "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "cgm", "pcraft", "dwg", ]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares @@ -714,6 +718,7 @@ pub const PLACE_EXTS: &[&str] = &[ "pct", "pic", "pict", + "cgm", "plt", "hpgl", "hgl", diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index f152132c69..557352ae86 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -131,6 +131,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if let Some(kind) = vectorcraft_metafile::sniff(bytes) { return format(kind.id()); } + if vectorcraft_metafile::is_cgm(bytes) { + return format("cgm"); + } if psdread::is_psd(bytes) { return format(if psdread::is_psb(bytes) { "psb" } else { "psd" }); } @@ -576,6 +579,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded> let (doc, warnings) = super::metafile::import_pict(bytes)?; (doc, warnings, false) } + "cgm" => { + let (doc, warnings) = super::metafile::import_cgm(bytes)?; + (doc, warnings, false) + } "hpgl" => { let i = vectorcraft_cad::hpgl::import(bytes).map_err(err)?; (i.document, i.warnings, false) diff --git a/crates/engine/src/cmd/fileio/metafile.rs b/crates/engine/src/cmd/fileio/metafile.rs index 3012f7c238..23d4978218 100644 --- a/crates/engine/src/cmd/fileio/metafile.rs +++ b/crates/engine/src/cmd/fileio/metafile.rs @@ -2,7 +2,8 @@ //! `document.export {format: emf|wmf}` and Export As (one picture of an artboard, or one per //! artboard with Use Artboards; raster effects as images, rendered at the document's raster //! effects resolution), `document.open` and File → Place (one artboard, the picture's frame). -//! QuickDraw pictures (PICT) open and place the same way; they are never written. +//! QuickDraw pictures (PICT) and binary Computer Graphics Metafiles (CGM) open and place the same +//! way; they are never written. use serde_json::Value; use vectorcraft_doc::Document; @@ -78,3 +79,9 @@ pub(super) fn import_pict(bytes: &[u8]) -> Result<(Document, Vec<String>)> { let p = vectorcraft_metafile::import_pict(bytes).map_err(super::err)?; Ok((p.document, p.warnings)) } + +/// A binary CGM's first picture as a document, and the import's warnings. +pub(super) fn import_cgm(bytes: &[u8]) -> Result<(Document, Vec<String>)> { + let p = vectorcraft_metafile::import_cgm(bytes).map_err(super::err)?; + Ok((p.document, p.warnings)) +} diff --git a/crates/engine/src/cmd/fileio/tests_cgm.rs b/crates/engine/src/cmd/fileio/tests_cgm.rs new file mode 100644 index 0000000000..3317d66e5a --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_cgm.rs @@ -0,0 +1,118 @@ +//! Binary CGM files through the commands: `document.open` by extension or by content, File › Place +//! as one group clipped to the picture's frame, the dialogs' filters and the format list, and +//! files that aren't binary CGM, or a CGM export, refused with a message. + +use serde_json::json; +use vectorcraft_doc::NodeKind; + +use super::*; + +fn b64(bytes: &[u8]) -> String { + vectorcraft_format::base64_encode(bytes) +} + +/// One element, padded to an even length. +fn el(class: u16, id: u16, data: &[u8]) -> Vec<u8> { + let mut b = ((class << 12) | (id << 5) | data.len() as u16).to_be_bytes().to_vec(); + b.extend(data); + if data.len() % 2 == 1 { + b.push(0); + } + b +} + +fn words(v: &[i16]) -> Vec<u8> { + v.iter().flat_map(|x| x.to_be_bytes()).collect() +} + +/// A binary CGM whose picture is 1000 × 500 units at 0.2 mm a unit (200 × 100 mm): a solid +/// rectangle and a line. +fn picture() -> Vec<u8> { + let mut b = el(0, 1, b"\x04logo"); + b.extend(el(1, 1, &words(&[1]))); + b.extend(el(0, 3, b"\x01p")); + b.extend(el(2, 1, &[words(&[1]), 0.2f32.to_be_bytes().to_vec()].concat())); + b.extend(el(2, 6, &words(&[0, 0, 1000, 500]))); + b.extend(el(0, 4, &[])); + b.extend(el(5, 22, &words(&[1]))); + b.extend(el(4, 11, &words(&[100, 100, 400, 300]))); + b.extend(el(4, 1, &words(&[0, 450, 1000, 450]))); + b.extend(el(0, 5, &[])); + b.extend(el(0, 2, &[])); + b +} + +const MM: f64 = 72.0 / 25.4; + +#[test] +fn document_open_reads_a_picture() { + let mut s = Session::new(); + let r = s.execute("document.open", &json!({"name": "part.cgm", "dataBase64": b64(&picture())})).unwrap(); + assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("cgm"), Some("part.cgm")), "{r}"); + assert_eq!(r["warnings"], json!([])); + let st = s.doc().unwrap(); + let size = st.doc.artboards[0].rect.size(); + assert!((size.width - 200.0 * MM).abs() < 1e-3 && (size.height - 100.0 * MM).abs() < 1e-3, "{size:?}"); + let mut paths = vec![]; + st.doc.walk(|n| { + if let NodeKind::Path { .. } = n.kind { + paths.push(n.clone()); + } + }); + assert_eq!(paths.len(), 2); + let b = paths[0].geometric_bounds().unwrap(); + assert!((b.x0 - 20.0 * MM).abs() < 1e-3 && (b.width() - 60.0 * MM).abs() < 1e-3, "{b:?}"); + assert!(st.path.is_none(), "opened as artwork: Save asks for a name"); + + // A CGM opens by its content under a name no format reads. + for name in ["part.CGM", "part.bin", "part"] { + let r = Session::new().execute("document.open", &json!({"name": name, "dataBase64": b64(&picture())})).unwrap(); + assert_eq!(r["format"].as_str(), Some("cgm"), "{name}: {r}"); + } + assert_eq!(detect("part.dat", &picture()).map(|f| f.id), Some("cgm")); +} + +#[test] +fn file_place_places_a_picture_as_one_clipped_group() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let p = json!({"name": "part.cgm", "dataBase64": b64(&picture()), "at": [400, 400]}); + let info = s.execute("file.place.info", &p).unwrap(); + assert_eq!(info["format"], "cgm", "{info}"); + assert!((info["width"].as_f64().unwrap() - 200.0 * MM).abs() < 1e-3, "{info}"); + let r = s.execute("file.place", &p).unwrap(); + assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("cgm"), Some(1)), "{r}"); + let doc = &s.doc().unwrap().doc; + let group = doc.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); + assert_eq!(group.name.as_deref(), Some("part.cgm")); + let NodeKind::Group { clip: true, .. } = &group.kind else { panic!("a clipping group, got {:?}", group.kind) }; + let b = group.geometric_bounds().unwrap(); + assert!((b.width() - 200.0 * MM).abs() < 1e-3 && (b.height() - 100.0 * MM).abs() < 1e-3, "{b:?}"); +} + +#[test] +fn files_that_are_not_cgm_are_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let e = s.execute("document.open", &json!({"name": "old.cgm", "dataBase64": b64(&[0; 64])})).expect_err("refused"); + assert!(e.to_string().contains("not a CGM file"), "{e}"); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), (100.0, 50.0).into()); + assert!(s.execute("file.place", &json!({"name": "old.cgm", "dataBase64": b64(&[0; 64])})).is_err()); + let e = s.execute("document.open", &json!({"name": "text.cgm", "dataBase64": b64(b"BEGMF 'x';")})).expect_err("refused"); + assert!(e.to_string().contains("only binary CGM files"), "{e}"); + let e = s.execute("document.export", &json!({"format": "cgm"})).expect_err("refused").to_string(); + assert!(e.contains("CGM files can be opened but not written"), "{e}"); +} + +#[test] +fn the_dialogs_and_the_format_list_name_cgm() { + assert!(OPEN_EXTS.contains(&"cgm") && PLACE_EXTS.contains(&"cgm") && UNASSOCIATED_EXTS.contains(&"cgm")); + assert_eq!(format_for_name("a.cgm").map(|f| f.id), Some("cgm")); + let filter = ("CGM", &["cgm"][..]); + assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter)); + let r = Session::new().execute("document.formats", &json!({})).unwrap(); + let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "cgm").unwrap().clone(); + assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(false), Some(false)), "{f}"); + assert_eq!(f["mime"], "image/cgm"); + assert!(writable_format(None, Some("x/part.cgm")).is_err()); +} diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 9d145853b9..4f2a1ec854 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -10,7 +10,7 @@ //! [`fileio::psd_slices`]). //! - An SVG becomes one group of its art; so does a DXF drawing, read with the DXF options //! (`dxf`, [`fileio::dxfimport`]), and an HP-GL plot file (`vectorcraft_cad::hpgl`). -//! - An EMF, WMF or PICT picture becomes one group, clipped to its frame (`crop: "crop"`) or +//! - An EMF, WMF, PICT or CGM picture becomes one group, clipped to its frame (`crop: "crop"`) or //! bounded by its art (`crop: "bounding"`). //! - An EPS file (or a PostScript .ai) becomes one group, clipped to its bounding box or bounded by //! its art: the document an EPS file of ours carries, else what its PostScript draws, else its @@ -88,7 +88,7 @@ pub fn specs() -> Vec<CommandSpec> { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; an image changed by Perspective Distort or Free Distort keeps its corners, which a raster image or a DCS file's image fills, with its file's clipping path drawn through them, and other files but text are refused; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.<id>\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed order (returned object order without layers), embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; an image changed by Perspective Distort or Free Distort keeps its corners, which a raster image or a DCS file's image fills, with its file's clipping path drawn through them, and other files but text are refused; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.<id>\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed order (returned object order without layers), embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF, PICT (.pct, .pic, .pict) and binary CGM (.cgm, its first picture) (clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index c6f02b9240..5938ad0e14 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -4,7 +4,8 @@ //! must load as an error or as a document that then renders and exports, without a panic; nor may //! bitmaps, PDF and text pasted from other apps, nor EMF and WMF pictures (damaged files, records //! of every kind with random contents) opened, placed or pasted, nor PICT pictures (damaged files, -//! opcodes with random contents) opened or placed, nor EPS and PostScript files +//! opcodes with random contents) opened or placed, nor binary CGM files (damaged files, elements +//! with random contents) opened or placed, nor EPS and PostScript files //! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of //! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor the widths a //! `.ai`'s PDF part gives its fonts' characters (hostile font dictionaries), nor Affinity documents @@ -4022,6 +4023,117 @@ proptest! { } } +// ---------- Binary CGM files: opened and placed ---------- + +/// One CGM element, in the long form past 30 bytes, padded to an even length. +fn cgm_el(class: u16, id: u16, data: &[u8]) -> Vec<u8> { + let mut b = Vec::new(); + if data.len() < 31 { + b.extend(((class << 12) | (id << 5) | data.len() as u16).to_be_bytes()); + } else { + b.extend(((class << 12) | (id << 5) | 31).to_be_bytes()); + b.extend((data.len() as u16).to_be_bytes()); + } + b.extend(data); + if data.len() % 2 == 1 { + b.push(0); + } + b +} + +/// A metafile of one picture holding `body`. +fn cgm_of(body: &[(u16, u16, Vec<u8>)]) -> Vec<u8> { + let mut b = cgm_el(0, 1, b"\x01x"); + b.extend(cgm_el(1, 1, &be16(&[3]))); + b.extend(cgm_el(1, 13, b"\x09Helvetica")); + b.extend(cgm_el(0, 3, b"\x01p")); + b.extend(cgm_el(2, 6, &be16(&[0, 0, 1000, 500]))); + b.extend(cgm_el(0, 4, &[])); + for (class, id, data) in body { + b.extend(cgm_el(*class, *id, data)); + } + b.extend(cgm_el(0, 5, &[])); + b.extend(cgm_el(0, 2, &[])); + b +} + +/// A picture with lines, shapes, arcs, a figure, markers, text, a cell array and a clip. +fn cgm_sample() -> Vec<u8> { + cgm_of(&[ + (5, 34, vec![8, 10, 20, 30, 40, 50, 60]), + (5, 3, be16(&[3])), + (5, 2, be16(&[2])), + (4, 1, be16(&[0, 0, 100, 100, 200, 0])), + (4, 2, be16(&[0, 10, 50, 10, 60, 10, 90, 10])), + (5, 22, be16(&[1])), + (5, 30, be16(&[1])), + (4, 7, be16(&[300, 0, 400, 0, 350, 80])), + (4, 8, be16(&[0, 200, 1, 100, 200, 1, 100, 300, 3])), + (4, 11, be16(&[500, 0, 600, 100])), + (4, 12, be16(&[700, 100, 50])), + (4, 14, be16(&[800, 0, 850, 50, 900, 0, 0])), + (4, 16, be16(&[100, 400, 1, 0, 0, 1, 50, 1])), + (4, 19, be16(&[300, 400, 350, 400, 300, 420, 1, 0, 0, 1, 0])), + (4, 26, be16(&[2, 0, 0, 10, 20, 30, 20, 40, 0])), + (0, 8, vec![]), + (4, 1, be16(&[500, 300, 600, 300])), + (4, 15, be16(&[600, 350, 0, -1, 0, 1, 50])), + (3, 10, vec![]), + (0, 9, vec![]), + (5, 6, be16(&[3])), + (4, 3, be16(&[900, 400, 950, 450])), + (3, 5, be16(&[0, 0, 500, 250])), + (5, 15, be16(&[40])), + (4, 4, [be16(&[100, 100, 0]), b"\x03abc".to_vec()].concat()), + (4, 6, [be16(&[1]), b"\x02de".to_vec()].concat()), + (4, 9, [be16(&[0, 0, 200, 100, 200, 0, 2, 2, 4, 1]), vec![0x12, 0, 0x34, 0]].concat()), + ]) +} + +/// The sample the mutations start from opens with art, type and an image. +#[test] +fn the_cgm_sample_opens() { + let l = vectorcraft_engine::cmd::fileio::load("x.cgm", &cgm_sample()).unwrap(); + assert_eq!(l.format.id, "cgm"); + let (mut paths, mut images, mut texts) = (0, 0, 0); + l.doc.walk(|n| match n.kind { + vectorcraft_doc::NodeKind::Path { .. } => paths += 1, + vectorcraft_doc::NodeKind::Image(_) => images += 1, + vectorcraft_doc::NodeKind::Text(_) => texts += 1, + _ => {} + }); + assert!(paths > 10 && images == 1 && texts == 1, "{paths} paths, {images} images, {texts} texts, warnings {:?}", l.warnings); +} + +/// CGM elements VectorCraft reads, and some it skips: the class in the high byte, the id in the +/// low one. +const CGM_ELEMENTS: [u16; 44] = [ + 0x0008, 0x0009, 0x0103, 0x0104, 0x0105, 0x0107, 0x010A, 0x010C, 0x010D, 0x0113, 0x0201, 0x0202, 0x0203, 0x0207, 0x0301, 0x0302, 0x0305, 0x0306, + 0x030A, 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0406, 0x0407, 0x0408, 0x0409, 0x040B, 0x040C, 0x040D, 0x040F, 0x0411, 0x0412, 0x0414, 0x0418, + 0x041A, 0x0503, 0x0504, 0x050F, 0x0510, 0x0512, 0x0522, 0x0801, +]; + +proptest! { + #![proptest_config(config())] + + #[test] + fn mutated_cgm_pictures_never_panic(cut in 0usize..4096, edits in prop::collection::vec((0usize..4096, any::<u8>()), 0..16)) { + let mut bytes = cgm_sample(); + let n = bytes.len(); + for &(at, b) in &edits { + bytes[at % n] = b; + } + bytes.truncate(cut); + survive_metafile("mutated CGM", "x.cgm", &bytes)?; + } + + #[test] + fn random_cgm_elements_never_panic(els in prop::collection::vec((prop::sample::select(CGM_ELEMENTS.to_vec()), arb_body()), 0..32)) { + let body: Vec<(u16, u16, Vec<u8>)> = els.into_iter().map(|(e, d)| (e >> 8, e & 0xFF, d)).collect(); + survive_metafile("CGM elements", "x.cgm", &cgm_of(&body))?; + } +} + // ---------- HP-GL plot files: opened and placed ---------- /// A plot file with every kind of instruction the reader plays, printer escapes around it. diff --git a/crates/metafile/Cargo.toml b/crates/metafile/Cargo.toml index 364f5c55d3..5afc04a19a 100644 --- a/crates/metafile/Cargo.toml +++ b/crates/metafile/Cargo.toml @@ -3,7 +3,7 @@ name = "vectorcraft-metafile" version.workspace = true edition.workspace = true license.workspace = true -description = "VectorCraft metafiles: EMF and WMF export and EMF, EMF+, WMF and QuickDraw PICT import through craft-metafile" +description = "VectorCraft metafiles: EMF and WMF export and EMF, EMF+, WMF, QuickDraw PICT and binary CGM import through craft-metafile" [lints] workspace = true diff --git a/crates/metafile/src/import.rs b/crates/metafile/src/import.rs index 63ba902cef..d2e3f99de2 100644 --- a/crates/metafile/src/import.rs +++ b/crates/metafile/src/import.rs @@ -1,5 +1,6 @@ //! The metafile readers. EMF (with its EMF+ records) and WMF files, and QuickDraw pictures (PICT), -//! are read by `craft_metafile`, and `picture` turns what they draw into document objects. +//! and binary CGM files are read by `craft_metafile`, and `picture` turns what they draw into +//! document objects. //! //! Fills and strokes become paths with a fill and a stroke; lines drawn one after another with the //! same pen join into one path. Clips become clipping groups around what they clip. Images keep @@ -92,3 +93,32 @@ pub(crate) fn import_pict(bytes: &[u8]) -> Result<crate::Picture, String> { })?; Ok(picture::convert(pic)) } + +/// The longer side of a CGM picture without a metric scale, points (8 inches). +const CGM_SIDE: f64 = 576.0; + +/// Read the first picture of a binary CGM (ISO/IEC 8632-3) through `craft_metafile`. +pub(crate) fn import_cgm(bytes: &[u8]) -> Result<crate::Picture, String> { + let cgm = craft_metafile::parse_cgm(bytes, CGM_SIDE).map_err(|e| e.to_string())?; + let n = cgm.notes; + let mut p = picture::convert(cgm.picture); + let notes = [ + (n.fills_approximated, "hatch, pattern and interpolated fills were filled with their fill color"), + (n.more_pictures, "the file holds more than one picture: only the first was read"), + (n.cie_colors, "colors in a CIE color model were read as RGB"), + (n.text_path, "text set to run left, up or down was set to run right"), + (n.restricted_text, "restricted text was set at its character height without fitting it to its box"), + (n.character_spacing, "character spacing was not applied"), + (n.text_cut, "text past 16,384 characters in one string was cut"), + ]; + p.warnings.extend(notes.iter().filter(|(on, _)| *on).map(|(_, w)| (*w).to_string())); + if n.damaged_elements > 0 { + let k = n.damaged_elements; + p.warnings.push(format!( + "{k} drawing element{} cut short or describing no shape {} left out", + if k == 1 { "" } else { "s" }, + if k == 1 { "was" } else { "were" } + )); + } + Ok(p) +} diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 66f3c4327b..1394a75bb0 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -20,7 +20,7 @@ //! A picture cut short by a reader limit, images and pattern brushes that can't be read, clips //! that can't be applied and raster operations other than a plain copy each add a warning. //! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of -//! document. +//! document, and [`import_cgm`] the first picture of a binary Computer Graphics Metafile (CGM). //! //! [`painted_layers`] gives the same walk's fills and strokes, layer by layer, to writers of other //! formats. @@ -236,5 +236,18 @@ pub fn import_pict(bytes: &[u8]) -> Result<Picture, String> { Ok(p) } +/// Do `bytes` start like a binary CGM: BEGIN METAFILE, then METAFILE VERSION? +pub fn is_cgm(bytes: &[u8]) -> bool { + craft_metafile::is_cgm(bytes) +} + +/// Read the first picture of a binary Computer Graphics Metafile (CGM, ISO/IEC 8632-3) into a +/// document whose one artboard is the picture's VDC extent. +pub fn import_cgm(bytes: &[u8]) -> Result<Picture, String> { + let mut p = import::import_cgm(bytes)?; + p.document.limit_depth_noting(&mut p.warnings); + Ok(p) +} + #[cfg(test)] mod tests; diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index eeb30ec846..2bce1ded94 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -11,6 +11,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, shapes}; use crate::*; +mod cgm; mod import; mod pict; diff --git a/crates/metafile/src/tests/cgm.rs b/crates/metafile/src/tests/cgm.rs new file mode 100644 index 0000000000..a9cbca18fc --- /dev/null +++ b/crates/metafile/src/tests/cgm.rs @@ -0,0 +1,441 @@ +//! Binary Computer Graphics Metafiles read from hand-built elements: the picture's frame and its +//! scale, lines, shapes, arcs, figures, markers, text, cell arrays and clips; elements written in +//! partitions; and files that aren't binary CGM, hold no picture, are cut short or hold more than +//! one picture. + +use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind}; +use vectorcraft_geom::{Point, Rect}; + +use crate::{import_cgm, is_cgm}; + +/// Big-endian 16-bit words. +fn be(v: &[i16]) -> Vec<u8> { + v.iter().flat_map(|x| x.to_be_bytes()).collect() +} + +/// One element in the short form (or the long form past 30 bytes, in one partition), padded to +/// an even length. +fn el(class: u16, id: u16, data: &[u8]) -> Vec<u8> { + let mut b = Vec::new(); + if data.len() < 31 { + b.extend(((class << 12) | (id << 5) | data.len() as u16).to_be_bytes()); + } else { + b.extend(((class << 12) | (id << 5) | 31).to_be_bytes()); + b.extend((data.len() as u16).to_be_bytes()); + } + b.extend(data); + if data.len() % 2 == 1 { + b.push(0); + } + b +} + +/// A string parameter. +fn s(text: &str) -> Vec<u8> { + [vec![text.len() as u8], text.as_bytes().to_vec()].concat() +} + +/// A metafile of one picture: `descriptor` after METAFILE VERSION, `picture` after BEGIN PICTURE +/// and `body` after BEGIN PICTURE BODY. +fn cgm(descriptor: &[Vec<u8>], picture: &[Vec<u8>], body: &[Vec<u8>]) -> Vec<u8> { + let mut b = el(0, 1, &s("test")); + b.extend(el(1, 1, &be(&[1]))); + descriptor.iter().for_each(|e| b.extend(e)); + b.extend(el(0, 3, &s("p1"))); + picture.iter().for_each(|e| b.extend(e)); + b.extend(el(0, 4, &[])); + body.iter().for_each(|e| b.extend(e)); + b.extend(el(0, 5, &[])); + b.extend(el(0, 2, &[])); + b +} + +/// A VDC extent of 1000 × 500 units: abstract, so 576 × 288 pt (0.576 pt a unit). +fn extent() -> Vec<u8> { + el(2, 6, &be(&[0, 0, 1000, 500])) +} + +/// Direct color selection: colors as 8-bit RGB. +fn direct() -> Vec<u8> { + el(2, 2, &be(&[1])) +} + +/// A VDC point (x, y) in points: y runs up from the bottom of the 1000 × 500 extent. +fn pt(x: f64, y: f64) -> Point { + Point::new(x * 0.576, (500.0 - y) * 0.576) +} + +fn all(d: &Document) -> Vec<Node> { + let mut v = vec![]; + for l in &d.layers { + for c in l.children().into_iter().flatten() { + c.walk(&mut |n| v.push(n.clone())); + } + } + v +} + +fn paths(d: &Document) -> Vec<Node> { + all(d).into_iter().filter(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })).collect() +} + +fn near(a: Rect, b: Rect, tol: f64) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() <= tol) +} + +fn fill_rgb(n: &Node) -> Option<[u8; 3]> { + n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) => f.paint.color().map(|c| { + let [r, g, b, _] = c.to_rgba8(1.0); + [r, g, b] + }), + _ => None, + }) +} + +fn stroke(n: &Node) -> Option<([u8; 3], f64)> { + n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Stroke(s) => s.paint.color().map(|c| { + let [r, g, b, _] = c.to_rgba8(1.0); + ([r, g, b], s.width) + }), + _ => None, + }) +} + +fn images(d: &Document) -> Vec<(Node, image::RgbaImage)> { + all(d) + .into_iter() + .filter_map(|n| match &n.kind { + NodeKind::Image(im) => { + let decoded = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap(); + Some((n.clone(), image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap())) + } + _ => None, + }) + .collect() +} + +#[test] +fn a_picture_opens_on_its_extent_with_the_first_corner_at_the_bottom_left() { + let bytes = cgm(&[], &[extent(), direct()], &[el(5, 22, &be(&[1])), el(5, 23, &[255, 0, 0]), el(4, 11, &be(&[100, 100, 300, 200]))]); + assert!(is_cgm(&bytes)); + let p = import_cgm(&bytes).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + assert!(near(p.document.artboards[0].rect, Rect::new(0.0, 0.0, 576.0, 288.0), 1e-9)); + let v = paths(&p.document); + assert_eq!(v.len(), 1, "{v:?}"); + assert_eq!(fill_rgb(&v[0]), Some([255, 0, 0])); + assert!(v[0].appearance.stroke().is_none(), "edges are off by default"); + let b = v[0].geometric_bounds().unwrap(); + assert!(near(b, Rect::from_points(pt(100.0, 100.0), pt(300.0, 200.0)), 1e-4), "{b:?}"); + + // An extent whose first corner is its top left turns the picture over: the same rectangle + // is then as far from the top as it was from the bottom. + let flipped = cgm(&[], &[el(2, 6, &be(&[0, 500, 1000, 0])), direct()], &[el(5, 22, &be(&[1])), el(4, 11, &be(&[100, 100, 300, 200]))]); + let b = paths(&import_cgm(&flipped).unwrap().document)[0].geometric_bounds().unwrap(); + assert!(near(b, Rect::new(57.6, 57.6, 172.8, 115.2), 1e-4), "{b:?}"); +} + +#[test] +fn a_metric_picture_keeps_its_size() { + // 0.1 mm a unit: 100 × 50 mm. + let metric = el(2, 1, &[be(&[1]), 0.1f32.to_be_bytes().to_vec()].concat()); + let p = import_cgm(&cgm(&[], &[metric, extent()], &[el(4, 1, &be(&[0, 0, 1000, 500]))])).unwrap(); + let size = p.document.artboards[0].rect.size(); + let mm = 72.0 / 25.4; + assert!((size.width - 100.0 * mm).abs() < 1e-3 && (size.height - 50.0 * mm).abs() < 1e-3, "{size:?}"); +} + +#[test] +fn lines_take_their_width_color_type_caps_and_joins() { + let bytes = cgm( + &[], + // Widths in VDC units. + &[extent(), el(2, 3, &be(&[0])), el(2, 17, &be(&[-1, 200, 1, 3]))], + &[ + // Color 9 from the color table: green. + el(5, 34, &[9, 0, 200, 0]), + el(5, 4, &[9]), + el(5, 3, &be(&[10])), + el(5, 2, &be(&[2])), + el(5, 37, &be(&[2, 2])), + el(5, 38, &be(&[4])), + el(4, 1, &be(&[0, 0, 500, 0, 500, 250])), + // Default color index 1 (black), a disjoint polyline: two separate lines. + el(5, 4, &[1]), + el(5, 2, &be(&[1])), + el(4, 2, &be(&[0, 400, 100, 400, 200, 400, 300, 400])), + // Line type -1 as the picture defines it: 200 units, a quarter on and three off. + el(5, 2, &be(&[-1])), + el(4, 1, &be(&[0, 450, 1000, 450])), + ], + ); + let p = import_cgm(&bytes).unwrap(); + let v = paths(&p.document); + assert_eq!(v.len(), 3, "{v:?}"); + let dash = v[2].appearance.stroke().unwrap().dash.clone().unwrap(); + assert!(dash.pattern.len() == 2 && (dash.pattern[0] - 28.8).abs() < 1e-3 && (dash.pattern[1] - 86.4).abs() < 1e-3, "{dash:?}"); + let (rgb, w) = stroke(&v[0]).unwrap(); + assert_eq!(rgb, [0, 200, 0]); + assert!((w - 5.76).abs() < 1e-4, "{w}"); + let st = v[0].appearance.stroke().unwrap(); + assert!(st.dash.as_ref().is_some_and(|d| d.is_dashed()), "line type 2 is dashed"); + assert_eq!((st.cap, st.join), (vectorcraft_doc::LineCap::Butt, vectorcraft_doc::LineJoin::Bevel)); + let NodeKind::Path { path, .. } = &v[1].kind else { panic!("a path") }; + assert_eq!(path.subpaths.len(), 2); + assert_eq!(stroke(&v[1]).unwrap().0, [0, 0, 0]); +} + +#[test] +fn circles_ellipses_and_arcs_are_curves_in_their_place() { + let bytes = cgm( + &[], + &[extent()], + &[ + el(5, 22, &be(&[1])), + // A circle of radius 100 at (500, 250). + el(4, 12, &be(&[500, 250, 100])), + // An ellipse 200 across and 50 high at (200, 100). + el(4, 17, &be(&[200, 100, 300, 100, 200, 125])), + // A half circle from (900, 250) through (800, 350) to (700, 250): the top half. + el(4, 13, &be(&[900, 250, 800, 350, 700, 250])), + // A quarter circle around (100, 400), from east to north, closed as a pie. + el(4, 16, &be(&[100, 400, 1, 0, 0, 1, 50, 0])), + ], + ); + let p = import_cgm(&bytes).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + let v = paths(&p.document); + assert_eq!(v.len(), 4, "{v:?}"); + // Cubic Béziers stand in for the curves: within 0.03% of the radius. + let tol = 0.05; + assert!(near(v[0].geometric_bounds().unwrap(), Rect::from_points(pt(400.0, 150.0), pt(600.0, 350.0)), tol)); + assert!(near(v[1].geometric_bounds().unwrap(), Rect::from_points(pt(100.0, 75.0), pt(300.0, 125.0)), tol)); + assert!(near(v[2].geometric_bounds().unwrap(), Rect::from_points(pt(700.0, 250.0), pt(900.0, 350.0)), tol)); + assert!(v[2].appearance.fill().is_none(), "an open arc is stroked"); + assert!(near(v[3].geometric_bounds().unwrap(), Rect::from_points(pt(100.0, 400.0), pt(150.0, 450.0)), tol)); + assert!(fill_rgb(&v[3]).is_some(), "a closed arc is filled"); +} + +#[test] +fn edges_outline_shapes_and_polygon_sets_skip_their_hidden_edges() { + let bytes = cgm( + &[], + &[extent(), direct()], + &[ + el(5, 22, &be(&[1])), + el(5, 30, &be(&[1])), + el(5, 29, &[0, 0, 255]), + // Two squares; the first one's left edge (from its last point) is hidden. + el(4, 8, &be(&[0, 0, 1, 100, 0, 1, 100, 100, 1, 0, 100, 2, 200, 0, 1, 300, 0, 1, 300, 100, 1, 200, 100, 3])), + ], + ); + let p = import_cgm(&bytes).unwrap(); + let v = paths(&p.document); + assert_eq!(v.len(), 2, "a fill and its edges: {v:?}"); + let NodeKind::Path { path, .. } = &v[0].kind else { panic!("a path") }; + assert_eq!(path.subpaths.len(), 2, "both squares fill"); + assert_eq!(stroke(&v[1]).unwrap().0, [0, 0, 255]); + let NodeKind::Path { path, .. } = &v[1].kind else { panic!("a path") }; + // The first square's three visible edges are one open line, and the second square is one + // closed outline. + assert_eq!(path.subpaths.len(), 2, "one outline for each square"); + assert_eq!(path.subpaths.iter().filter(|s| s.closed).count(), 1, "{:?}", path.subpaths); +} + +#[test] +fn a_figure_fills_its_lines_as_one_shape() { + let bytes = cgm( + &[], + &[extent()], + &[ + el(5, 22, &be(&[1])), + el(0, 8, &[]), + el(4, 1, &be(&[0, 0, 100, 0])), + el(4, 15, &be(&[100, 50, 0, -1, 0, 1, 50])), + el(4, 1, &be(&[100, 100, 0, 100])), + el(0, 9, &[]), + ], + ); + let p = import_cgm(&bytes).unwrap(); + let v = paths(&p.document); + assert_eq!(v.len(), 1, "{v:?}"); + assert!(fill_rgb(&v[0]).is_some() && v[0].appearance.stroke().is_none()); + let NodeKind::Path { path, .. } = &v[0].kind else { panic!("a path") }; + assert_eq!(path.subpaths.len(), 1); + assert!(near(v[0].geometric_bounds().unwrap(), Rect::from_points(pt(0.0, 0.0), pt(150.0, 100.0)), 0.05)); +} + +#[test] +fn text_comes_in_as_point_type_at_its_character_height() { + let bytes = cgm( + &[el(1, 13, &[s("Times-Roman"), s("Helvetica-BoldOblique")].concat())], + &[extent()], + &[ + el(5, 10, &be(&[2])), + el(5, 15, &be(&[70])), + // Not final: the rest of the string follows in APPEND TEXT. + el(4, 4, &[be(&[100, 200, 0]), s("Hel")].concat()), + el(4, 6, &[be(&[1]), s("lo")].concat()), + // Restricted text: its box is not applied, and a warning says so. + el(4, 5, &[be(&[300, 70, 100, 50, 1]), s("Box")].concat()), + ], + ); + let p = import_cgm(&bytes).unwrap(); + assert_eq!(p.warnings, ["restricted text was set at its character height without fitting it to its box"]); + let texts: Vec<_> = all(&p.document).into_iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).collect(); + assert_eq!(texts.len(), 2); + let NodeKind::Text(t) = &texts[0].kind else { panic!("text") }; + assert_eq!(t.plain_text(), "Hello"); + let st = &t.runs[0].style; + assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Helvetica", "Bold Italic")); + // The character height (70 units, 40.32 pt) is the cap height: 0.7 of the size. + assert!((st.size - 57.6).abs() < 1e-3, "{}", st.size); + assert!((t.xf.translation().to_point() - pt(100.0, 200.0)).hypot() < 1e-3, "{:?}", t.xf); +} + +#[test] +fn what_the_reader_left_out_or_set_differently_is_warned_about() { + let bytes = cgm( + &[], + &[extent()], + &[ + // Character spacing 0.5, then a rectangle with one corner and a circle without its radius. + el(5, 13, &[0, 0, 0x80, 0]), + el(4, 4, &[be(&[0, 0, 1]), s("spaced")].concat()), + el(4, 11, &be(&[0, 0])), + el(4, 12, &be(&[10, 10])), + el(4, 11, &be(&[0, 0, 10, 10])), + ], + ); + let p = import_cgm(&bytes).unwrap(); + assert!(p.warnings.iter().any(|w| w == "character spacing was not applied"), "{:?}", p.warnings); + assert!(p.warnings.iter().any(|w| w == "2 drawing elements cut short or describing no shape were left out"), "{:?}", p.warnings); + assert_eq!(paths(&p.document).len(), 1); +} + +#[test] +fn cell_arrays_become_images_packed_or_run_length() { + // 2 × 2 cells over (0, 0) to (200, 100), first row along the bottom: red, green, then blue, + // white. + let corners = be(&[0, 0, 200, 100, 200, 0]); + let packed = [corners.clone(), be(&[2, 2, 8, 1]), vec![255, 0, 0, 0, 255, 0], vec![0, 0, 255, 255, 255, 255]].concat(); + // Runs: a count (16 bits) and a color. + let run = |color: [u8; 3]| [be(&[1]), color.to_vec()].concat(); + let runs = [corners.clone(), be(&[2, 2, 8, 0]), run([255, 0, 0]), run([0, 255, 0]), run([0, 0, 255]), run([255, 255, 255])].concat(); + // 4-bit indexed cells: each row of two cells takes one byte and is padded to a word. + let indexed = [corners, be(&[2, 2, 4, 1]), vec![0x23, 0, 0x41, 0]].concat(); + for data in [packed, runs] { + let p = import_cgm(&cgm(&[], &[extent(), direct()], &[el(4, 9, &data)])).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + let imgs = images(&p.document); + assert_eq!(imgs.len(), 1); + let (n, px) = &imgs[0]; + assert_eq!(px.dimensions(), (2, 2)); + assert_eq!(px.get_pixel(0, 0).0, [255, 0, 0, 255]); + assert_eq!(px.get_pixel(1, 0).0, [0, 255, 0, 255]); + assert_eq!(px.get_pixel(0, 1).0, [0, 0, 255, 255]); + // The first row is at the bottom of the picture: drawn upward from P. + let b = n.geometric_bounds().unwrap(); + assert!(near(b, Rect::from_points(pt(0.0, 0.0), pt(200.0, 100.0)), 1e-3), "{b:?}"); + } + // Indexed cells through the default color table. + let p = import_cgm(&cgm(&[], &[extent()], &[el(4, 9, &indexed)])).unwrap(); + let px = &images(&p.document)[0].1; + let row = |y| [px.get_pixel(0, y).0, px.get_pixel(1, y).0]; + assert_eq!(row(0), [[255, 0, 0, 255], [0, 255, 0, 255]]); + assert_eq!(row(1), [[0, 0, 255, 255], [0, 0, 0, 255]]); +} + +#[test] +fn markers_are_drawn_at_their_points() { + let bytes = cgm(&[], &[extent()], &[el(5, 6, &be(&[4])), el(4, 3, &be(&[100, 100, 900, 400]))]); + let v = paths(&import_cgm(&bytes).unwrap().document); + assert_eq!(v.len(), 2); + // A nominal marker is 1/100 of the longer side across: 5.76 pt. + let b = v[1].geometric_bounds().unwrap(); + assert!((b.center() - pt(900.0, 400.0)).hypot() < 1e-3 && (b.width() - 5.76).abs() < 1e-2, "{b:?}"); +} + +#[test] +fn the_clip_rectangle_clips_what_follows() { + let bytes = cgm( + &[], + &[extent()], + &[el(5, 22, &be(&[1])), el(4, 11, &be(&[0, 0, 100, 100])), el(3, 5, &be(&[0, 0, 500, 250])), el(4, 11, &be(&[0, 0, 1000, 500]))], + ); + let p = import_cgm(&bytes).unwrap(); + let layer = p.document.layers[0].children().unwrap(); + assert!(matches!(layer[0].kind, NodeKind::Path { .. }), "the picture's own extent clips nothing"); + let NodeKind::Group { children, clip: true } = &layer[1].kind else { panic!("a clipping group: {:?}", layer[1].kind) }; + assert!(near(children[0].geometric_bounds().unwrap(), Rect::from_points(pt(0.0, 0.0), pt(500.0, 250.0)), 1e-3)); + // With the clip indicator off, nothing is clipped. + let off = [el(3, 5, &be(&[0, 0, 500, 250])), el(3, 6, &be(&[0])), el(5, 22, &be(&[1])), el(4, 11, &be(&[0, 0, 1000, 500]))]; + let off = cgm(&[], &[extent()], &off); + let p = import_cgm(&off).unwrap(); + assert!(matches!(p.document.layers[0].children().unwrap()[0].kind, NodeKind::Path { .. })); +} + +#[test] +fn precisions_real_coordinates_partitions_and_default_replacements() { + // Real VDC (fixed point 16.16), a line width set in the metafile's defaults, and a polyline + // in two partitions. + let fixed = |v: f64| ((v * 65536.0) as i32).to_be_bytes().to_vec(); + let mdr = el(1, 12, &[el(2, 3, &be(&[0])), el(5, 3, &fixed(100.0))].concat()); + let real_extent = el(2, 6, &[fixed(0.0), fixed(0.0), fixed(1000.0), fixed(500.0)].concat()); + let points: Vec<u8> = [0.0, 0.0, 500.0, 0.0, 500.0, 250.0, 1000.0, 500.0].iter().flat_map(|v| fixed(*v)).collect(); + let mut body = vec![]; + body.extend(((4u16 << 12) | (1 << 5) | 31).to_be_bytes()); + body.extend((0x8000u16 | 16).to_be_bytes()); + body.extend(&points[..16]); + body.extend(16u16.to_be_bytes()); + body.extend(&points[16..]); + let bytes = cgm(&[el(1, 3, &be(&[1])), mdr], &[real_extent], &[body]); + let p = import_cgm(&bytes).unwrap(); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + let v = paths(&p.document); + assert_eq!(v.len(), 1); + assert!(near(v[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 576.0, 288.0), 1e-3)); + assert!((stroke(&v[0]).unwrap().1 - 57.6).abs() < 1e-3, "{:?}", stroke(&v[0])); +} + +#[test] +fn files_that_are_not_binary_cgm_are_refused() { + assert_eq!(import_cgm(b"").unwrap_err(), "not a CGM file"); + assert_eq!(import_cgm(&[0; 64]).unwrap_err(), "not a CGM file"); + assert!(!is_cgm(&[0; 64])); + let clear = import_cgm(b"BEGMF 'drawing';\nmfversion 1;\n").unwrap_err(); + assert!(clear.contains("only binary CGM files"), "{clear}"); + // A metafile without a picture. + let mut b = el(0, 1, &s("empty")); + b.extend(el(1, 1, &be(&[1]))); + b.extend(el(0, 2, &[])); + assert!(is_cgm(&b)); + assert_eq!(import_cgm(&b).unwrap_err(), "the CGM file holds no picture"); +} + +#[test] +fn a_picture_cut_short_keeps_what_came_before() { + let full = cgm(&[], &[extent()], &[el(5, 22, &be(&[1])), el(4, 11, &be(&[0, 0, 100, 100])), el(4, 11, &be(&[200, 0, 300, 100]))]); + // Cut inside the second rectangle. + let cut = &full[..full.len() - 10]; + let p = import_cgm(cut).unwrap(); + assert_eq!(paths(&p.document).len(), 1); + assert!(p.warnings.iter().any(|w| w.contains("cut short")), "{:?}", p.warnings); +} + +#[test] +fn only_the_first_picture_is_read() { + let mut b = cgm(&[], &[extent()], &[el(5, 22, &be(&[1])), el(4, 11, &be(&[0, 0, 100, 100]))]); + // Drop END METAFILE and add a second picture. + b.truncate(b.len() - 2); + b.extend(el(0, 3, &s("p2"))); + b.extend(el(0, 4, &[])); + b.extend(el(4, 11, &be(&[0, 0, 500, 500]))); + b.extend(el(0, 5, &[])); + b.extend(el(0, 2, &[])); + let p = import_cgm(&b).unwrap(); + assert_eq!(paths(&p.document).len(), 1); + assert!(p.warnings.iter().any(|w| w.contains("only the first")), "{:?}", p.warnings); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 31f0da4316..52acb9b572 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -61,7 +61,7 @@ Ordinary File > Save offers Save As when its own location refuses writes with a | | Illustrator | VectorCraft | Notes | |---|---:|---:|---| -| Formats opened or placed | ~30 | 37 | missing: FreeHand | +| Formats opened or placed | ~30 | 38 | missing: FreeHand | | Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, gradients, patterns, images, type, symbols, artboards, transparency, opacity masks, clipping, text wrap options) or as legacy version 7 (layers and groups, one artboard per file) | | Formats exported | ~16 | 20 | missing: DWG; extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | @@ -385,6 +385,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | PCX | open, place | yes (1 bit in the header palette's first two colors, black and white without them; 1 bit in two to four planes and 4 bits with up to 16 colors; 2 bits in the CGA colors the header's CGA palette settings pick; 8 bits with the 256-color palette, gray without one; 24-bit color in three planes) | no | the header's HDpi and VDpi size the image; a file of another depth or plane count, cut short or past the pixel allowance is refused with a message; tests in `crates/engine/src/cmd/fileio/tests_pcxread.rs` and `crates/engine/tests/import_fuzz.rs` | | JPEG 2000 | open, place | yes (JP2 and raw codestream images; multiple codestreams and JPX composition or layers are refused) | no | `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c`, `.jpc`; resolution uses the valid `resd` (display) value on each axis, or else the valid `resc` (capture) value, or 72 ppi; bounded decoding; `tests_jp2read.rs` | | PICT | open, place (legacy) | yes (versions 1 and 2: shapes, lines, regions, text, bitmaps, pixel maps and QuickTime JPEG images; placed as one group clipped to the picture's frame) | no | `.pct`, `.pic` and `.pict`; a version 2 picture also opens by its content; a two-color pattern fills with its average color; inverted shapes, transfer modes other than a copy and QuickTime images in other formats come back as warnings; a picture cut short keeps what came before it; tests in `crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs` and `crates/engine/tests/import_fuzz.rs` | +| CGM `.cgm` | open, place | yes (the binary encoding, ISO/IEC 8632-3: the first picture's polylines, polygons, polygon sets, rectangles, circles, ellipses, arcs, polybeziers, figures, markers, text and cell arrays, with line, edge and fill attributes, the color table and the clip rectangle; placed as one group clipped to the picture's frame) | no | also opens by its content; clear text and character encoded files are refused with a message; hatch, pattern and interpolated fills fill with their fill color; B-splines, hyperbolic and parabolic arcs, symbols, tiles and segment copies are skipped with a warning; a picture cut short keeps what came before it; tests in `crates/metafile/src/tests/cgm.rs`, `crates/engine/src/cmd/fileio/tests_cgm.rs` and `crates/engine/tests/import_fuzz.rs` | | Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` | | FreeHand `.fh*` | open (legacy) | no | no | | | `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, clipping containers, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; hidden and locked layers, groups and objects; the winding flag as the nonzero fill rule; uniform transparency of version 13 on as opacity and blend mode; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses, other transparency and merge modes without a blend mode are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies; version 3 envelopes are not applied, so the objects and groups under one keep their outlines and matrices, with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; after an open with a warning, an export or Save As to the drawing's own path needs `acknowledgeLoss: true`; record layouts and their sources in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`); synthetic test files only; tests in `craft-cdr` `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` | diff --git a/docs/mcp.md b/docs/mcp.md index 2fd8648262..50681987da 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -866,7 +866,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). The app refuses `attributes.openUrl`, `file.export.svg.browser`, `file.saveForWeb.browser` and `file.showPackage` for every control and MCP request, since each opens another app, so the headless error for them does not suggest `--connect`. | | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. An app that does not send the image back writes a window capture without `path` to a file in a new folder inside the system's temporary folder (on Unix only the user can open it); the server reads the file and then removes the folder, also when the capture or the read fails. | -| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`), layered raster `.pcraft` documents (as one image at the canvas size; a warning says when only the smaller preview could be read). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin.<id>"` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | +| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), binary CGM (`.cgm`, and a binary CGM of any extension; its first picture), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`), layered raster `.pcraft` documents (as one image at the canvas size; a warning says when only the smaller preview could be read). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin.<id>"` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | | `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `<name>_<artboard>.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error; versions 1 to 3 get each live star as a plain path of its outline, without its point count and ratio), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: <reason>` without a fallback panel for automation; see [Save location errors](#save-location-errors). In the desktop app, a save that runs in the background shows in the progress window after 0.4 s with a moving bar. `file.cancelSave` stops every such save before it replaces its file → `{cancelled: n}`: the file stays as it was, and the document keeps its file and format and stays modified. A save whose file was already being replaced finishes and is reported as saved. `file.saveInBackground` closes the window while the saves go on → `{hidden: n}`. | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` for type on a path (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning). An invalid effect is rejected before editing. `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | @@ -12672,7 +12672,7 @@ images. DWG drawings open and place (see DXF import) but can't be written: `document.formats` lists `dwg` as readable and not writable, and exporting to it answers with the hint to export DXF. PICT files open and place (see PICT -import) but can't be written. +import) but can't be written, and so do CGM files (see CGM import). ```json {"name":"run_command","arguments":{"command":"document.exportDxf","params":{"path":"/tmp/plan.dxf","version":"2013","unit":"mm","scale":10,"preserve":"editability"}}} @@ -13301,6 +13301,43 @@ written". {"name":"run_command","arguments":{"command":"file.place","params":{"path":"/tmp/logo.pct","at":[300,200]}}} ``` +## CGM import + +`document.open` and `file.place` read Computer Graphics Metafiles in the binary encoding of ISO/IEC 8632-3 (`.cgm`), +the encoding [WebCGM 2.1](https://www.w3.org/TR/webcgm21/) profiles, into one artboard and one layer. A CGM also opens by +its content under any name. Only the first picture is read; a file that holds more adds a warning. + +- The artboard is the picture's VDC extent, with the extent's first corner at its bottom left. A picture with a metric + scale keeps its size in millimeters; any other picture is scaled so that its longer side is 576 pt. +- Polylines, disjoint polylines, polybeziers and open arcs are stroked with the line width, color, type, caps and joins. + Line types 2 to 5 are dashes and dots at multiples of the line's width, and a type that LINE AND EDGE TYPE DEFINITION + defines takes its dashes from there. +- Polygons, polygon sets, rectangles, circles, ellipses and closed arcs are filled by the interior style with the odd-even + rule, and outlined with the edge attributes while edges are visible. A polygon set leaves out its hidden edges. A hollow + interior is outlined in the fill color. Lines and arcs between BEGIN FIGURE and END FIGURE fill as one shape. +- Markers become small paths at their points. Text, restricted text and appended text become point type in the font the + font list names, along the character orientation, with the character height as the cap height (0.7 of the type size). +- Cell arrays (packed or run-length encoded, indexed or direct color) become images placed by their three corners. +- The clip rectangle clips what follows it while the clip indicator is on. + +VectorCraft's own values where the file leaves them to the reader: a nominal line or edge width is 1/1000 of the +picture's longer side, a nominal marker 1/100 of it, and colors 0 to 7 of the default color table are white, black, red, +green, blue, yellow, cyan and magenta. + +`file.place` places the picture as one group clipped to its frame. What isn't read comes back in `warnings`, once each: +hatch, pattern and interpolated fills (filled with their fill color), text that runs left, up or down (set to run right), +restricted text (set at its character height without fitting it to its box), character spacing (not applied), text past +16,384 characters in one string (cut), colors in a CIE color model (read as RGB), drawing elements whose parameters are +cut short or describe no shape (left out, with their count), and B-splines, hyperbolic and parabolic arcs, symbols, tiles +and segment copies (skipped). A picture cut short or past the reader's limits keeps what came before it with a warning. A file that isn't binary CGM is refused with +"not a CGM file", a clear text or character encoded CGM with "only binary CGM files can be read: this one uses the clear +text or character encoding", and a metafile without a picture with "the CGM file holds no picture". CGM can't be written: +`document.export` to it is refused with "CGM files can be opened but not written". + +```json +{"name":"run_command","arguments":{"command":"file.place","params":{"path":"/tmp/part.cgm","at":[300,200]}}} +``` + ## HP-GL import `document.open` and `file.place` read HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`) into one layer, with the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 99255fa880..1041576062 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2545,6 +2545,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - HEIC and HEIF images open and place from `.heic` and `.heif`, as the [supported file formats](https://helpx.adobe.com/illustrator/kb/supported-file-formats-illustrator.html) list High Efficiency Image under both Open and Place (and [Fix HEIF file import errors on Windows](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/fix-heif-file-import-errors-on-windows.html) covers both ways of bringing HEIF files in): HEVC-coded single pictures and grids of tiles, 8 to 10 bits, with an alpha image, decoded by heic-rs in the engine's default `heif` feature. The container's rotation, mirror and crop are applied. Without an `nclx` box, the HEVC stream's video signal type gives the samples' matrix and range. An RGB ICC profile, or Display P3 with the sRGB curve named by an `nclx` box or, without a color box, by the stream, is converted to sRGB; the EXIF resolution tags size the image, or 72 ppi. Image sequences, other codings and grids of cropped tiles are refused with a message, and so is every HEIF file in a build without the feature. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_heifread.rs`). - HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`, or a name no other format reads when the file starts with plotter instructions) open and place as paths on one layer, the artboard round the art: each line drawn with the pen down is a stroked path in its pen's color and width, line types become dash patterns, circles, arcs, wedges and Bézier curves are curves, filled and edged rectangles, wedges and polygons (polygon mode) are filled or stroked paths, and encoded polylines, scaling points, user units and rotation are read. Labels, symbol mode's symbols, raster images and hatching aren't drawn and are listed in the warnings (`crates/cad/src/hpgl/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - PICT pictures (`.pct`, `.pic`, and `.pict` as VectorCraft's own name) open and place, as [the help page](https://helpx.adobe.com/archive/illustrator/illustrator-cs5-5-troubleshooting.pdf) lists Macintosh PICT under both opening and placing: versions 1 and 2, with or without the file's 512 bytes of application data, read by the opcodes of Apple's [Opcodes in Pictures](https://dev.os9.ca/techpubs/mac/QuickDraw/QuickDraw-461.html). Lines, rectangles, rounded rectangles, ovals, arcs, polygons and regions become paths in their pen and pattern colors, text becomes point type in the font the picture names, bitmaps, pixel maps and QuickTime JPEG images become images, and the clip region clips what follows it; File › Place places the picture as one group clipped to its frame. Inverted shapes, other transfer modes and other QuickTime formats come back as warnings, and a picture cut short keeps what came before it (`crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs`). + - Computer Graphics Metafiles (`.cgm`) open and place, as [the supported file formats page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/supported-file-formats-in-illustrator.html) lists them under both opening and placing: the binary encoding of ISO/IEC 8632-3, as [WebCGM 2.1](https://www.w3.org/TR/webcgm21/) profiles it. The first picture's lines, shapes, arcs, figures, markers, text and cell arrays come in at the picture's metric scale (or 576 pt on its longer side), with their line, edge and fill attributes and the clip rectangle; File › Place places the picture as one group clipped to its frame. Hatch and pattern fills fill with their fill color, other primitives are skipped with a warning, and a picture cut short keeps what came before it (`crates/metafile/src/tests/cgm.rs`, `crates/engine/src/cmd/fileio/tests_cgm.rs`). - EMF and WMF type takes its size from the font's height, where a negative height is the em and a positive height is the character cell, and a font's average character width becomes Horizontal Scale against the face's own average width (OS/2 `xAvgCharWidth`) when the face gives one, as [LOGFONT](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-logfontw) and [MS-EMF 2.2.13](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-emf/1cd7cb7a-1a7c-48d2-b4a4-c218f9d12100) describe the two fields. VectorCraft's own rules are that the cell is the face's `usWinAscent` plus `usWinDescent` at a variable font's instance (its ascent plus descent without an OS/2 table), that a negative width is read as its absolute value, and that the width is ignored when the height is 0 (`a_font_width_becomes_horizontal_scale`, `a_positive_font_height_is_the_character_cell`, `a_font_the_system_lacks_is_measured_in_the_face_that_draws_it`, `wmf_font_width_becomes_horizontal_scale`). - EMF and WMF files are read by the shared `craft-metafile` reader and open, place and paste as editable paths, clipping groups, images and point type: an EMF drawn with EMF+ records (on their own, or beside plain records) is read from them instead of opening empty, and hatched and pattern brushes fill with their average color (`crates/metafile/src/tests/import.rs`). - EMF, WMF and EMF+ text keeps the character advances the file gives (ExtTextOut's `lpDx`, DrawDriverString positions) as tracking, with pair kerning off; on a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object where the advance puts it, with an underline or strikethrough filled across the space between and on to the end of the last character's advance; type on more than one line is placed a line at a time, each line aligned by its own advances and split as a single line is (`text_is_spaced_by_its_advances`, `multiline_text_with_advances_aligns_each_line`, `wmf_text_is_spaced_by_its_advances`, `emf_plus_driver_strings_keep_their_positions`, `split_type_keeps_its_underline_and_right_to_left_order`). From 5b1f78fc0742a75b9c0e605c237ee5b07a46e83a Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 16:44:37 -0800 Subject: [PATCH 54/88] DWG: DXF Options stays in Keyboard Shortcuts; MCP export names dwg - crates/ui-egui/src/menus/ui_commands.rs: ui.dxfOptionsDialog's params doc starts with `path?` again. Keyboard Shortcuts lists a UI command with no default key only when its params doc starts with `{}` or `{path?` (ui_listed_on_its_own), so the doc that started with `format?` dropped DXF Options Dialog from Edit > Keyboard Shortcuts, and commands_no_menu_holds_are_grouped_by_their_menu_or_panel failed on its unused File group row. crates/mcp/src/ui_catalog.rs is regenerated with `cargo xtask ui-commands`. - crates/mcp/src/tools/definitions.rs: the export tool's description names dwg, which its format enum now lists, and says DWG takes outlineText and range as DXF does; docs/mcp.md says the same. export_tool_lists_engine_formats_and_options expects dwg in the enum. --- crates/mcp/src/tests/fileio.rs | 3 ++- crates/mcp/src/tools/definitions.rs | 6 +++--- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 2 +- 5 files changed, 8 insertions(+), 7 deletions(-) diff --git a/crates/mcp/src/tests/fileio.rs b/crates/mcp/src/tests/fileio.rs index f8c3689f99..dd116908ef 100644 --- a/crates/mcp/src/tests/fileio.rs +++ b/crates/mcp/src/tests/fileio.rs @@ -81,7 +81,8 @@ fn export_tool_lists_engine_formats_and_options() { "hpgl", "tga", "psd", - "cmx" + "cmx", + "dwg" ]) ); for k in ["artboard", "range", "options"] { diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index cc187ea408..a5cb93f998 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -400,16 +400,16 @@ pub fn tool_definitions() -> Vec<Value> { tool( "export", "Export", - "Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, emf, wmf, hpgl pen moves for plotters and cutters, cmx exchange files of fills and strokes), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.", + "Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, dwg (the DXF drawing as a DWG file, versions 2000 to 2018), emf, wmf, hpgl pen moves for plotters and cutters, cmx exchange files of fills and strokes), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF and DWG take it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.", obj( json!({ "format": {"type": "string", "enum": FORMATS.iter().filter(|f| f.write).map(|f| f.id).collect::<Vec<_>>(), "description": "Default: from the path's extension"}, "path": string("Destination file (omit to get dataBase64)"), "scale": num("Raster pixels per point (without scale or options.ppi, uses the document's raster effects resolution; options.ppi wins)"), "artboard": {"type": "integer", "minimum": 0, "description": "0-based artboard (default: the first; PDF and .ai default: all)"}, - "range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, EMF, WMF and HP-GL: one, or one file each with options.useArtboards: true; CMX: one, or one page each in one file with options.useArtboards: true)"), + "range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, DWG, EMF, WMF and HP-GL: one, or one file each with options.useArtboards: true; CMX: one, or one page each in one file with options.useArtboards: true)"), "selection": {"type": "boolean", "description": "Export only the selection, cropped to it"}, - "outlineText": {"type": "boolean", "description": "SVG/SVGZ: true writes text as outlines (viewable without the fonts). DXF takes it too (type outlined anyway unless preserve: editability). PDF uses options.advanced.outlineText instead (default false: live text)"}, + "outlineText": {"type": "boolean", "description": "SVG/SVGZ: true writes text as outlines (viewable without the fonts). DXF and DWG take it too (type outlined anyway unless preserve: editability). PDF uses options.advanced.outlineText instead (default false: live text)"}, "options": {"type": "object", "description": "More format options, passed through (see run_command document.formats), e.g. {\"quality\": 80} for jpg or {\"advanced\": {\"outlineText\": true}} for PDF text as outlines (default false: live text)"}, }), &[], diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index e75927208c..a6028362c1 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1756,7 +1756,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.dxfOptionsDialog", "DXF Options Dialog", "", - "{format?: dxf (default)|dwg, path?, useArtboards?, range?, …document.exportDxf options} open DXF Options, or DWG Options for format: dwg (dialog `dxfOptions`: fields = these options over the ones used last, a dxfPreset's options under them; the dxfPreset field shows cnc while every field it sets matches, else custom; DWG offers the versions from 2000, and a version used last that DWG isn't written as starts on 2018); OK checks them, remembers them and writes path (else asks). Export As… → DXF or DWG opens it too", + "{path?, format?: dxf (default)|dwg, useArtboards?, range?, …document.exportDxf options} open DXF Options, or DWG Options for format: dwg (dialog `dxfOptions`: fields = these options over the ones used last, a dxfPreset's options under them; the dxfPreset field shows cnc while every field it sets matches, else custom; DWG offers the versions from 2000, and a version used last that DWG isn't written as starts on 2018); OK checks them, remembers them and writes path (else asks). Export As… → DXF or DWG opens it too", ), ( "links.editOriginal", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 25a2e1e74e..a3438f836f 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1757,7 +1757,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.dxfOptionsDialog", "DXF Options Dialog", "", - "{format?: dxf (default)|dwg, path?, useArtboards?, range?, …document.exportDxf options} open DXF Options, or DWG Options for format: dwg (dialog `dxfOptions`: fields = these options over the ones used last, a dxfPreset's options under them; the dxfPreset field shows cnc while every field it sets matches, else custom; DWG offers the versions from 2000, and a version used last that DWG isn't written as starts on 2018); OK checks them, remembers them and writes path (else asks). Export As… → DXF or DWG opens it too", + "{path?, format?: dxf (default)|dwg, useArtboards?, range?, …document.exportDxf options} open DXF Options, or DWG Options for format: dwg (dialog `dxfOptions`: fields = these options over the ones used last, a dxfPreset's options under them; the dxfPreset field shows cnc while every field it sets matches, else custom; DWG offers the versions from 2000, and a version used last that DWG isn't written as starts on 2018); OK checks them, remembers them and writes path (else asks). Export As… → DXF or DWG opens it too", ), ( "links.editOriginal", diff --git a/docs/mcp.md b/docs/mcp.md index 399dc4d1eb..7cb6ac3eed 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -910,7 +910,7 @@ first frame's direction, frames taken out of a thread keep theirs, and a file wh with the first frame's direction in all of them. When every frame already has the direction, the command records no undo step. -For SVG/SVGZ, `export`'s top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). +For SVG/SVGZ, `export`'s top-level `outlineText: true` writes text as paths; DXF and DWG take it too (their type is outlined anyway unless `preserve: editability`). PDF instead uses `options: {"advanced": {"outlineText": true}}`; its default is false (live text). With `mods.shift`, a marquee dragged with the Selection tool toggles the objects it reaches (the selected ones leave From ab636b13951748c2e4135c0e97cb3f90c6cd44f5 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 17:20:38 -0800 Subject: [PATCH 55/88] Image Trace: tracing again moves the tracing's attributes instead of copying them Tracing a tracing again copied its attributes twice: once when the edit read the tracing out of the document, and again for the new tracing. An object can hold 64 tags of up to 64 KiB each, so each extra copy could cost megabytes. The new tracing now takes the attributes from the edit's own copy of the old one. `vectorcraft_doc::attribute_copies()` counts copies of an object's attributes on the current thread, and a test checks that tracing again copies them once. --- crates/doc/src/lib.rs | 2 +- crates/doc/src/node.rs | 4 ++- crates/doc/src/node/attributes.rs | 30 ++++++++++++++++++- crates/engine/src/cmd/buildcmds/trace.rs | 7 +++-- crates/engine/src/tests/script_dom_tracing.rs | 21 +++++++++++++ 5 files changed, 59 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 059a3d4bdc..5b6c67c1dc 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -119,7 +119,7 @@ pub use node::Knockout; pub use node::Scaling; pub use node::changed_nodes; pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask}; -pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; +pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS, attribute_copies}; pub use orient::OrientedBox; pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType}; pub use perspective::PerspectiveAttachment; diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 3a4b2abd03..2fdb579ee1 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -25,7 +25,9 @@ mod opacity; mod ops; mod wire; -pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; +pub use attributes::{ + ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS, attribute_copies, +}; #[cfg(test)] pub(crate) use changed::COUNTERPART_LOOKUPS; pub use changed::changed_nodes; diff --git a/crates/doc/src/node/attributes.rs b/crates/doc/src/node/attributes.rs index 67d3d02308..62edeb3795 100644 --- a/crates/doc/src/node/attributes.rs +++ b/crates/doc/src/node/attributes.rs @@ -3,7 +3,7 @@ use super::live_shape::LiveShape; use super::{Deserialize, Node, Serialize}; /// Window → Attributes: an object's settings that don't change how it prints. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ObjectAttributes { /// Show Center / Don't Show Center (`None`: the object kind's default, [`Node::shows_center`]). @@ -45,6 +45,34 @@ pub struct ObjectAttributes { pub tags: Vec<ObjectTag>, } +impl Clone for ObjectAttributes { + fn clone(&self) -> Self { + ATTRIBUTE_COPIES.set(ATTRIBUTE_COPIES.get().saturating_add(1)); + Self { + show_center: self.show_center, + image_map: self.image_map, + url: self.url.clone(), + note: self.note.clone(), + data: self.data.clone(), + events: self.events.clone(), + classes: self.classes.clone(), + foreign: self.foreign.clone(), + tags: self.tags.clone(), + } + } +} + +thread_local! { + /// [`attribute_copies`] of this thread. + static ATTRIBUTE_COPIES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; +} + +/// How many times an object's [`ObjectAttributes`] have been copied on this thread. Tags can hold +/// up to [`MAX_TAGS`] values of [`MAX_TAG_TEXT`] bytes each, so each copy can cost megabytes. +pub fn attribute_copies() -> u64 { + ATTRIBUTE_COPIES.get() +} + /// The most tags one object has. pub const MAX_TAGS: usize = 64; diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 08a962f919..f8ac3f152b 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -1118,7 +1118,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val return Err(EngineError::Cancelled); } let id = s.edit(label, |d, sel| { - let src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?; + let mut src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?; let mut image = if is_trace_group(&src) { src.children() .and_then(|c| c.first()) @@ -1228,7 +1228,10 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val // Tracing again keeps the tracing's note, tags and URL, including when expanding. // Without expansion, it also keeps the tracing's other object settings. if is_trace_group(&src) { - g.extras_mut().attrs = src.extras().attrs.clone(); + // The attributes move from `src`, this edit's own copy of the tracing, without another copy. + if src.extras().attrs.is_some() { + g.extras_mut().attrs = src.extras_mut().attrs.take(); + } if !expand { g.visible = src.visible; g.locked = src.locked; diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index ce886715a0..ef1f719920 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -1560,6 +1560,27 @@ fn retrace_keeps_the_tracing_note_and_tags() { let _ = std::fs::remove_dir_all(base); } +/// Tracing again moves the tracing's attributes to the new tracing: it copies them once, when it +/// reads the tracing out of the document, and not again for the new object. +#[test] +fn retrace_copies_the_tracing_attributes_once() { + let base = folder("retrace-attribute-copies"); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(); p.note = 'keep me'; var t = p.tags.add(); t.name = 'job'; t.value = '42';", + ); + let id = traces(&s)[0]; + let before = vectorcraft_doc::attribute_copies(); + let r = s.execute("imageTrace.make", &json!({"id": id.0, "params": {"threshold": 100}})).unwrap(); + assert_eq!(vectorcraft_doc::attribute_copies() - before, 1, "copies of the attributes"); + let id = NodeId(r["id"].as_u64().unwrap()); + let note = s.active().unwrap().doc.node(id).and_then(|n| n.extras().attrs.as_deref().map(|a| a.note.clone())); + assert_eq!(note.as_deref(), Some("keep me")); + let _ = std::fs::remove_dir_all(base); +} + /// `pathItems.removeAll()` and `textFrames.removeAll()` refuse to leave an image at the bottom of an /// ordinary group named as a tracing, before the document changes. #[test] From a5ce3e09e9a885d436888d719637b907345be530 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 17:30:51 -0800 Subject: [PATCH 56/88] Tests: agent requests wait for the reply instead of a 10 s poll budget agent_request ran up to 2,000 passes with a 5 ms receive timeout each, so a slow loopback exchange on a busy runner could fail the test. It now runs passes until the client thread hands its reply back; the client's own call timeout turns a request the app never answers into an error reply. --- crates/ui-egui/src/agents/tests.rs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/agents/tests.rs b/crates/ui-egui/src/agents/tests.rs index 4825fc6570..d83c634855 100644 --- a/crates/ui-egui/src/agents/tests.rs +++ b/crates/ui-egui/src/agents/tests.rs @@ -54,8 +54,10 @@ fn app_with_agents(base: &Path, switch: AgentSwitch) -> (VectorcraftApp, Arc<Mut } /// One request from an agent's client through the link's server, answered by the app's frames: the client -/// thread hands its reply back over a channel, and the app runs a pass while it waits. +/// thread hands its reply back over a channel, and the app runs passes until that reply arrives. The +/// client's own call timeout ends a call the app never answers with an error, so the reply always comes. fn agent_request(app: &mut VectorcraftApp, client: &mut Option<ControlClient>, method: &str, params: Value) -> Result<Value, String> { + use std::sync::mpsc::TryRecvError; let ctx = app.ui_ctx.clone().unwrap_or_default(); let mut c = client.take().expect("a connected client"); let sent = method.to_owned(); @@ -64,15 +66,18 @@ fn agent_request(app: &mut VectorcraftApp, client: &mut Option<ControlClient>, m let r = c.call(&sent, params); let _ = done.send((c, r)); }); - for _ in 0..2000 { + loop { app.run_control(&ctx); app.poll_input(&ctx); - if let Ok((c, r)) = reply.recv_timeout(std::time::Duration::from_millis(5)) { - *client = Some(c); - return r; + match reply.try_recv() { + Ok((c, r)) => { + *client = Some(c); + return r; + } + Err(TryRecvError::Empty) => std::thread::yield_now(), + Err(TryRecvError::Disconnected) => panic!("the client thread for {method:?} stopped without a reply"), } } - panic!("the app did not answer {method:?}") } // With the launcher's switch naming VectorCraft, the window serves agents on loopback and publishes From c99020bf0b5b2018d03baee5b2c1f233400d7ef8 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 17:32:34 -0800 Subject: [PATCH 57/88] Screen print marks: artboard deletes, position moves and replays keep marks with their owner Deleting an artboard now clears the owner tag of its marks group, on the marks layer or moved off it, so a reopened file that gives a new artboard the old id does not hand it the old marks. artboard.setProps with moveArt and a new x or y takes the artboard's own marks group wherever it lies and leaves another artboard's group lying on it, as artboard.move does; an artboard scaled in the same call leaves a moving artboard's marks alone, and marks lying on another locked artboard stay unless lockedAndHidden. A run on the active artboard records it in the journal as activeArtboard, which recorded actions leave out. --- crates/engine/src/cmd/addons.rs | 2 +- .../src/cmd/addons/color/screen_marks.rs | 42 ++++++- .../cmd/addons/color/screen_marks/tests.rs | 119 ++++++++++++++++++ crates/engine/src/cmd/layer.rs | 26 +++- crates/engine/src/cmd/panelcmds.rs | 19 ++- crates/engine/src/command_sets.rs | 3 +- docs/mcp.md | 12 +- docs/target-app-parity.md | 2 +- 8 files changed, 206 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 94eff63759..8fcbd68e8a 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -18,7 +18,7 @@ mod units; pub(crate) use color::screen_marks::{ LAYER_NAME as SCREEN_MARKS_LAYER, adopt_layer as adopt_screen_marks_layer, copied_owners as screen_marks_copied, layer_id as screen_marks_layer, - managed_owners as screen_marks_owners, owned_by as screen_marks_of, retag as retag_screen_marks, + managed_owners as screen_marks_owners, owned_by as screen_marks_of, release as release_screen_marks, retag as retag_screen_marks, }; pub(crate) use image::{DecodedImages, refresh_color_masks}; pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines}; diff --git a/crates/engine/src/cmd/addons/color/screen_marks.rs b/crates/engine/src/cmd/addons/color/screen_marks.rs index 5f66210fe4..f5f58b2571 100644 --- a/crates/engine/src/cmd/addons/color/screen_marks.rs +++ b/crates/engine/src/cmd/addons/color/screen_marks.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> { "Create Screen Print Marks", ["Object", "Plug-ins", "Color Effects"], None, - "{positions?: [topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight…] (each at most once; default: [top, bottom, left, right]; [] draws no targets), size?: target width in pt 4..1000 (36), weight?: stroke weight in pt 0.1..20 (1), inset?: pt from the artboard's edge to the target's outer edge -1000..1000 (18; below 0 the targets sit outside the artboard), ink?: \"[Registration]\" (default) or a spot swatch's name (the targets and the file line), inks?: false (a line naming the document's spot inks, each name in its own ink; tints and [Registration] left out), info?: false (a line with the file name, or the title of a document never saved, and the date and time in UTC), time?: Unix seconds (default: now; null, or no clock as on the web: no date), textSize?: pt 4..72 (9), textPlace?: \"top\"|\"bottom\" (default), textAlign?: \"left\" (default)|\"right\" (the lines start past a target ticked in that corner, and move in past the top or bottom target they would cross; they stay where they are when moving would cross another target or leave the artboard), artboard?: index (default: the active artboard), allArtboards?: false; null is refused except for time} draw registration targets (a circle half the target's width with a cross through it, stroked) inside each artboard, and the lines asked for, as one group per artboard on the layer \"Screen Print Marks\", which is made locked at the bottom of the stack when there is none; running it again replaces that artboard's group. Another artboard's group lying on a copied artboard goes with its own artboard. One undo step, none when the marks come out the same; the selection is kept → {changed, layer, ids: [group id…], inks: [spot ink name…]}", + "{positions?: [topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight…] (each at most once; default: [top, bottom, left, right]; [] draws no targets), size?: target width in pt 4..1000 (36), weight?: stroke weight in pt 0.1..20 (1), inset?: pt from the artboard's edge to the target's outer edge -1000..1000 (18; below 0 the targets sit outside the artboard), ink?: \"[Registration]\" (default) or a spot swatch's name (the targets and the file line), inks?: false (a line naming the document's spot inks, each name in its own ink; tints and [Registration] left out), info?: false (a line with the file name, or the title of a document never saved, and the date and time in UTC), time?: Unix seconds (default: now; null, or no clock as on the web: no date), textSize?: pt 4..72 (9), textPlace?: \"top\"|\"bottom\" (default), textAlign?: \"left\" (default)|\"right\" (the lines start past a target ticked in that corner, and move in past the top or bottom target they would cross; they stay where they are when moving would cross another target or leave the artboard), artboard?: index (default: the active artboard), activeArtboard?: index (the active artboard the journal records for a replay; used when artboard is left out; omitted from recorded actions), allArtboards?: false; null is refused except for time} draw registration targets (a circle half the target's width with a cross through it, stroked) inside each artboard, and the lines asked for, as one group per artboard on the layer \"Screen Print Marks\", which is made locked at the bottom of the stack when there is none; running it again replaces that artboard's group. Another artboard's group lying on a copied artboard goes with its own artboard. One undo step, none when the marks come out the same; the selection is kept → {changed, layer, ids: [group id…], inks: [spot ink name…]}", has_doc, screen_marks )] @@ -307,6 +307,25 @@ pub(crate) fn retag(n: &mut Node, from: u32, to: u32) -> bool { true } +/// Make the marks groups of the deleted artboards with ids `gone` ordinary art: a file opened +/// again can give a new artboard one of those ids, and its marks are drawn afresh. +pub(crate) fn release(d: &mut Document, gone: &std::collections::HashSet<u32>) { + // Groups moved off the marks layer keep their tag and count too. + let mut groups: Vec<NodeId> = vec![]; + for l in &d.layers { + l.walk(&mut |n: &Node| { + if owner(n).is_some_and(|o| gone.contains(&o)) { + groups.push(n.id); + } + }); + } + for id in groups { + if let Some(n) = d.node_mut(id) { + n.edit_attrs(|a| a.data.retain(|(k, _)| k != KEY)); + } + } +} + /// Make top-level layer `layer`, which a paste made for a marks group it copied with an artboard, /// the marks layer, when the document has none. pub(crate) fn adopt_layer(d: &mut Document, layer: NodeId) { @@ -352,6 +371,22 @@ fn screen_marks(s: &mut Session, p: &Value) -> Result<Value> { if all && artboard.is_some() { return Err(bad(C, "give `artboard` or `allArtboards`, not both")); } + // The active artboard, noted in the journal (`activeArtboard`) so a replay marks the same one; + // recorded actions leave it out and use the active artboard when played. + let recorded = index_opt(p, "activeArtboard", C)?; + let artboard = match artboard { + None if !all => { + let i = match recorded { + Some(i) => Some(i), + None => active_artboard(s.doc()?), + }; + if let Some(i) = i { + s.note_journal("activeArtboard", json!(i)); + } + i + } + given => given, + }; let st = s.doc()?; let doc = &st.doc; if doc.artboards.is_empty() { @@ -360,10 +395,7 @@ fn screen_marks(s: &mut Session, p: &Value) -> Result<Value> { let boards: Vec<(Rect, u32)> = if all { doc.artboards.iter().map(|a| (a.rect, a.id)).collect() } else { - let i = match artboard { - Some(i) => i, - None => active_artboard(st).unwrap_or(0), - }; + let i = artboard.unwrap_or(0); let a = doc.artboards.get(i).ok_or_else(|| bad(C, format!("there is no artboard {i}")))?; vec![(a.rect, a.id)] }; diff --git a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs index 457b0ec11d..41e0d770a7 100644 --- a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs +++ b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs @@ -812,3 +812,122 @@ fn bad_params_are_refused_and_leave_the_document_unchanged() { assert_eq!(r["inks"], json!([])); assert!(lines(&node(&s, r["ids"][0].as_u64().unwrap())).is_empty()); } + +#[test] +fn marks_of_a_deleted_artboard_belong_to_no_artboard_that_later_takes_its_id() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"artboard": 1, "positions": ["right"]})); + let gone = s.doc().unwrap().doc.artboards[1].id; + s.execute("artboard.delete", &json!({"indices": [1]})).unwrap(); + assert!(s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).is_some(), "the marks stay as art"); + // A reopened file does not remember the deleted id, so a new artboard can take it. + assert!(!super::managed_owners(&s.doc().unwrap().doc).values().any(|o| *o == gone), "no marks group names the deleted artboard"); +} + +#[test] +fn marks_moved_off_the_marks_layer_forget_their_deleted_artboard() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"artboard": 1, "positions": ["right"]})); + s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap(); + let other = s.doc().unwrap().doc.layers[1].id.0; + s.execute("layer.move", &json!({"ids": [r["ids"][0]], "target": other})).unwrap(); + s.execute("artboard.delete", &json!({"indices": [1]})).unwrap(); + assert_eq!(super::owner(&node(&s, r["ids"][0].as_u64().unwrap())), None); +} + +#[test] +fn moving_an_artboard_leaves_its_marks_lying_on_another_locked_artboard() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200})); + let own = node(&s, r["ids"][0].as_u64().unwrap()); + s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": true, "lockedAndHidden": false})).unwrap(); + assert!(node(&s, own.id.0) == own, "Move Artboard leaves them on the locked artboard"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 0, "y": 500, "moveArt": true, "lockedAndHidden": false})).unwrap(); + assert!(node(&s, own.id.0) == own, "a new position leaves them on the locked artboard"); +} + +#[test] +fn an_artboard_scaled_in_the_same_call_leaves_a_moving_artboards_marks_to_it() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200})); + let start = bounds(&node(&s, r["ids"][0].as_u64().unwrap())); + let edits = json!([{"index": 1, "width": 1200}, {"index": 0, "y": 500}]); + s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": true})).unwrap(); + let moved = bounds(&node(&s, r["ids"][0].as_u64().unwrap())); + assert_eq!((moved.x0, moved.y0, moved.width()), (start.x0, start.y0 + 500.0, start.width()), "the marks move with their own artboard, unscaled"); +} + +#[test] +fn marks_on_an_artboard_unlocked_in_the_same_call_stay_when_their_own_artboard_moves() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200})); + let own = node(&s, r["ids"][0].as_u64().unwrap()); + s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + let edits = json!([{"index": 0, "y": 500}, {"index": 1, "locked": false, "y": 500}]); + s.execute("artboard.setProps", &json!({"artboards": edits, "moveArt": true, "lockedAndHidden": false})).unwrap(); + assert!(node(&s, own.id.0) == own, "the marks lay on a locked artboard when the call began"); + s.execute("edit.undo", &json!({})).unwrap(); + let edits = json!([{"index": 0, "y": 500}, {"index": 1, "locked": false, "width": 1200}]); + s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": false})).unwrap(); + assert!(node(&s, own.id.0) == own, "the artboard scaled in the same call leaves them too"); +} + +#[test] +fn a_marks_group_of_a_missing_artboard_goes_with_the_first_listed_artboard() { + let mut s = session(); + for _ in 0..2 { + s.execute("artboard.new", &json!({"x": 0, "y": 0, "width": 600, "height": 400})).unwrap(); + } + let r = run(&mut s, json!({"artboard": 2, "positions": ["top"]})); + // A file saved before deleting an artboard cleared its marks' tag. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.remove(2); + let start = bounds(&node(&s, r["ids"][0].as_u64().unwrap())); + let edits = json!([{"index": 0, "width": 1200}, {"index": 1, "y": 500}]); + s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": true})).unwrap(); + let now = bounds(&node(&s, r["ids"][0].as_u64().unwrap())); + assert!(close(now.width(), start.width() * 2.0), "it scales with the first artboard listed"); +} + +#[test] +fn moving_an_artboard_by_its_position_takes_its_own_marks_and_leaves_others() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let own = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200}))["ids"][0].as_u64().unwrap(); + let foreign = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200}))["ids"][0].as_u64().unwrap(); + let (own, foreign) = (node(&s, own), node(&s, foreign)); + s.execute("artboard.setProps", &json!({"index": 0, "y": 500, "moveArt": true, "lockedAndHidden": true})).unwrap(); + let start = bounds(&own); + let moved = bounds(&node(&s, own.id.0)); + assert_eq!((moved.x0, moved.y0), (start.x0, start.y0 + 500.0), "the marks lying above the artboard move with it"); + assert!(node(&s, foreign.id.0) == foreign, "another artboard's marks lying on it stay"); +} + +#[test] +fn marks_drawn_on_the_active_artboard_record_it_for_a_replay() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let second = s.doc().unwrap().doc.artboards[1].id; + s.doc_mut().unwrap().active_artboard = Some(second); + let start = s.journal.len(); + run(&mut s, json!({"positions": ["right"]})); + let (cmd, recorded) = s.journal.last().unwrap().clone(); + assert_eq!(cmd, COMMAND); + assert_eq!(recorded["activeArtboard"], json!(1), "the journal names the artboard the marks went on"); + // A replay on another active artboard marks the recorded one. + let first = s.doc().unwrap().doc.artboards[0].id; + s.doc_mut().unwrap().active_artboard = Some(first); + let replayed = run(&mut s, recorded); + assert_eq!(replayed["changed"], json!(false), "the second artboard's marks are drawn again the same"); + // A recorded action leaves it out and marks the artboard active when it plays. + let action = s.journal_for_action(start); + assert!(action.iter().all(|(_, p)| p.get("activeArtboard").is_none())); +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 3a52534ac8..6dc4f79f9f 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -165,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> { "Artboard Options…", ["Window", "Artboards"], None, - "{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on. Supported artboard exports and printing include it by default. This includes raster exports with `selectedOnly: true` when the output area is an artboard. Set `includeArtboardFill: false` on the export or print command to omit it. Exports cropped to selection bounds, artwork bounds, or an explicit raster region leave it out, as do formats that do not support artboard fills) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes", + "{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on. Supported artboard exports and printing include it by default. This includes raster exports with `selectedOnly: true` when the output area is an artboard. Set `includeArtboardFill: false` on the export or print command to omit it. Exports cropped to selection bounds, artwork bounds, or an explicit raster region leave it out, as do formats that do not support artboard fills) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard, and the artboard's own screen print marks group wherever it lies, while another artboard's group lying on it stays with its own), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes", has_doc, artboard_set ), @@ -1250,6 +1250,7 @@ pub(crate) fn remove_artboards(d: &mut Document, sel: &mut vectorcraft_doc::Sele for &id in &gone { d.retire_artboard_id(id); } + super::addons::release_screen_marks(d, &gone); d.retain_guides(sel, |g| !g.artboard.is_some_and(|a| gone.contains(&a))); count_artboard_pass(); Ok(()) @@ -1393,7 +1394,6 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> { let delta = now.origin() - was.origin(); let moving = !resized && bool_or(p, "moveArt", false) && delta != vectorcraft_geom::Vec2::ZERO; let transform = fit.or_else(|| moving.then(|| Affine::translate(delta))); - let art = if transform.is_some() { d.art_moving_with(index, all).into_iter().filter(|id| taken.insert(*id)).collect() } else { vec![] }; edits.push(ArtboardEdit { index, now, @@ -1409,9 +1409,29 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> { resized, fit, transform, - art, + art: vec![], }); } + // The artboards that move take their own screen print marks groups wherever they lie, and not + // another artboard's lying on them, as Move Artboard does. An artboard that scales in the same + // call leaves a moving artboard's marks lying on it to their own artboard. + // One pass for all of them, in the order listed. + let movers: Vec<usize> = edits.iter().filter(|e| e.transform.is_some() && e.fit.is_none()).map(|e| e.index).collect(); + let mut found = super::panelcmds::artboards_art(s, &movers, true, all, true)?.into_iter(); + let moved: Vec<Option<Vec<NodeId>>> = + edits.iter().map(|e| (e.transform.is_some() && e.fit.is_none()).then(|| found.next().map(|(_, a)| a).unwrap_or_default())).collect(); + // Every group that belongs to a moving artboard, taken by it or left where it is; a group whose + // artboard was deleted is ordinary art. + let boards: HashSet<u32> = movers.iter().filter_map(|i| d.artboards.get(*i).map(|a| a.id)).collect(); + let reserved: HashSet<NodeId> = super::addons::screen_marks_owners(d).into_iter().filter(|(_, o)| boards.contains(o)).map(|(id, _)| id).collect(); + for (e, own) in edits.iter_mut().zip(moved) { + let art = match own { + Some(art) => art, + None if e.fit.is_some() => d.art_moving_with(e.index, all).into_iter().filter(|id| !reserved.contains(id)).collect(), + None => vec![], + }; + e.art = art.into_iter().filter(|id| taken.insert(*id)).collect(); + } // Nothing to change: no undo step. if !edits.iter().any(|e| d.artboards.get(e.index).is_none_or(|a| e.changes(a))) { return if scale_art { Ok(json!({ "scaled": [] })) } else { ok() }; diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index ad6f4c3798..0dff2ba3ba 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -310,7 +310,12 @@ pub(crate) fn artboard_art(s: &Session, i: usize, art: bool, all: bool, moving: /// own artboard's entry: another artboard's group lying on one of them goes with its own artboard /// when that one is among `arts`, and is left out when it is not. Only the groups on the marks /// layer count; a group whose artboard was deleted stays where it is. -pub(crate) fn marks_with_owners(d: &vectorcraft_doc::Document, arts: Vec<(usize, Vec<NodeId>)>) -> Vec<(usize, Vec<NodeId>)> { +/// `held(i, id)` says group `id` stays put for artboard `i`. +pub(crate) fn marks_with_owners( + d: &vectorcraft_doc::Document, + arts: Vec<(usize, Vec<NodeId>)>, + held: impl Fn(usize, NodeId) -> bool, +) -> Vec<(usize, Vec<NodeId>)> { let owners = super::addons::screen_marks_owners(d); if owners.is_empty() { return arts; @@ -335,7 +340,9 @@ pub(crate) fn marks_with_owners(d: &vectorcraft_doc::Document, arts: Vec<(usize, }) .collect(); for (o, id) in moved { - if let Some((_, art)) = arts.iter_mut().find(|(i, _)| board(*i) == Some(o)) { + if let Some((i, art)) = arts.iter_mut().find(|(i, _)| board(*i) == Some(o)) + && !held(*i, id) + { art.push(id); } } @@ -353,16 +360,20 @@ pub(crate) fn artboards_art(s: &Session, indices: &[usize], art: bool, all: bool arts.push((i, art)); } let d = &s.doc()?.doc; + // A move or a cut leaves a group lying on an artboard locked other than its own, as it leaves + // other art there, unless locked and hidden art goes too. + let held = |i: usize, id: NodeId| moving && !all && d.node(id).is_some_and(|n| d.locked_artboards_except(i).holds(n)); if art { for (id, o) in super::addons::screen_marks_copied(d, all) { - if let Some((_, own)) = arts.iter_mut().find(|(i, _)| d.artboards.get(*i).is_some_and(|a| a.id == o)) + if let Some((i, own)) = arts.iter_mut().find(|(i, _)| d.artboards.get(*i).is_some_and(|a| a.id == o)) + && !held(*i, id) && seen.insert(id) { own.push(id); } } } - Ok(marks_with_owners(d, arts)) + Ok(marks_with_owners(d, arts, held)) } /// How far a copy of `rect` moves to sit right of the last artboard (Duplicate Artboards, Paste). diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 753c315a9a..84ddf9eaec 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -37,7 +37,7 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p /// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that /// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out /// ([`Session::journal_for_action`]). -const REPLAY_ONLY: [(&str, &str); 38] = [ +const REPLAY_ONLY: [(&str, &str); 39] = [ ("edit.copy", "artboard"), ("edit.cut", "artboard"), ("file.new", "created"), @@ -68,6 +68,7 @@ const REPLAY_ONLY: [(&str, &str); 38] = [ ("artboard.distributeSpacing", "selectedArtboards"), ("artboard.distributeSpacing", "activeArtboard"), ("addon.document.floodFillArtboards", "activeArtboard"), + ("addon.color.screenMarks", "activeArtboard"), ("edit.copy", "selectedArtboards"), ("edit.copy", "art"), ("edit.cut", "selectedArtboards"), diff --git a/docs/mcp.md b/docs/mcp.md index b6ea03f919..2b7bb9e82a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11745,7 +11745,9 @@ artboard size fields while the tool is in use. `artboard.setProps {artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…], scaleArt?, moveArt?, …}` sets several artboards in one undo step, each with its own fields; the other params apply to all of them. The art that moves or scales with each artboard is the art inside it before any of them changes, and an object inside several of them goes -with the first one listed that moves or scales its art. An empty list and a list that names an artboard twice are +with the first one listed that moves or scales its art. An artboard whose new `x` or `y` at the same size moves its art (`moveArt`) takes its own +screen print marks group wherever it lies, and leaves another artboard's group lying on it to that artboard +([Create Screen Print Marks](#create-screen-print-marks)). An empty list and a list that names an artboard twice are refused. With several artboards selected with the Artboard tool, the desktop app gives a new size to each of them in one such @@ -18525,12 +18527,14 @@ The marks of each artboard are one group, on the top-level marks layer the comma the layer's data and not by its name. The command makes that layer, named "Screen Print Marks", at the bottom of the stack, locked, when the document has none. Another layer with that name is not used, and the marks layer keeps its role when renamed. A marks layer moved, unlocked or hidden stays as it is. -`artboard` is an artboard's index (default: the active artboard) and `allArtboards: true` marks every artboard; +`artboard` is an artboard's index (default: the active artboard; the journal records it as `activeArtboard` for a replay, and recorded actions leave it +out) and `allArtboards: true` marks every artboard; giving both is an error. Running the command again replaces that artboard's group and leaves the other artboards' groups alone. A group copied with an artboard duplicated, Alt-dragged or pasted in the same document belongs to the copy. Another artboard's group lying on an artboard that is duplicated, Alt-dragged, copied or cut goes with its own artboard: -it is copied with that artboard when that one is copied too, and otherwise stays where it is. A group whose artboard was -deleted is copied like other art. With art enabled, moves and cuts also take marks by their recorded owner, even when +it is copied with that artboard when that one is copied too, and otherwise stays where it is. Deleting an artboard makes its group ordinary art on the marks layer, so a new artboard never takes it over; +it is copied like other art. With art enabled, moves (`artboard.move`, and `artboard.setProps` with `moveArt` and a +new `x` or `y` at the same size) and cuts also take marks by their recorded owner (marks lying on another locked artboard stay, as other art does), even when the marks lie outside every artboard, subject to `lockedAndHidden`. When the marks layer was deleted, or the document pasted into has none, pasting an artboard with its marks makes a new marks layer named "Screen Print Marks" at the top level, and the command uses that layer. Marks outside the artboard (a negative `inset`) appear in an export or a print clipped to the artboard only as far as its diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 94e2de6426..8ce8627a9e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3318,7 +3318,7 @@ A VectorCraft addition (it replaces a script some users ran), so no area score m ## Create Screen Print Marks (2026-11-29) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Color Effects › Create Screen Print Marks… (`addon.color.screenMarks`) opens a dialog (the eight target positions, size, stroke weight, inset, ink, the spot ink and file lines with their type size, place and alignment, all artboards, with a preview) and draws registration targets (a circle half the target's width with a cross through it) inside the artboard in [Registration] or a spot ink, with an optional line naming the document's spot inks, each in its own ink, and an optional line with the file name and the date and time in UTC. The marks are document art: one group per artboard on a locked "Screen Print Marks" layer made at the bottom of the stack, so they print, separate and export with the rest of the art, where Create Trim Marks draws trim marks only and the PDF export's printer's marks exist only in the exported file. The lines move in past a top or bottom target they would cross. They stay where they are when moving would cross another target or leave the artboard. Marks copied with a duplicated artboard belong to the copy, and another artboard's marks lying on a copied artboard stay with their own artboard. A paste that makes the deleted marks layer again makes it the marks layer. Running it again replaces that artboard's marks; one undo step, none when the marks come out the same. Remaining: saved presets of the dialog's settings. Tests: `cmd::addons::color::screen_marks::tests` (engine), `addons::color::screen_marks::tests` (ui-egui). +A VectorCraft addition, so no area score moves. Object › Plug-ins › Color Effects › Create Screen Print Marks… (`addon.color.screenMarks`) opens a dialog (the eight target positions, size, stroke weight, inset, ink, the spot ink and file lines with their type size, place and alignment, all artboards, with a preview) and draws registration targets (a circle half the target's width with a cross through it) inside the artboard in [Registration] or a spot ink, with an optional line naming the document's spot inks, each in its own ink, and an optional line with the file name and the date and time in UTC. The marks are document art: one group per artboard on a locked "Screen Print Marks" layer made at the bottom of the stack, so they print, separate and export with the rest of the art, where Create Trim Marks draws trim marks only and the PDF export's printer's marks exist only in the exported file. The lines move in past a top or bottom target they would cross. They stay where they are when moving would cross another target or leave the artboard. Marks copied with a duplicated artboard belong to the copy, and another artboard's marks lying on a copied artboard stay with their own artboard. Moving an artboard with its art, by Move Artboard or a new position, takes its own marks, and deleting it makes its marks ordinary art. A paste that makes the deleted marks layer again makes it the marks layer. Running it again replaces that artboard's marks; one undo step, none when the marks come out the same. Remaining: saved presets of the dialog's settings. Tests: `cmd::addons::color::screen_marks::tests` (engine), `addons::color::screen_marks::tests` (ui-egui). With art enabled, artboard moves and cuts take eligible screen print marks by their recorded owner, including marks outside every artboard. Tests: `overlapping_artboard_copies_keep_one_marks_group_per_owner`, `off_board_marks_follow_artboard_copies_and_cuts_by_owner`, `moving_an_artboard_uses_marks_ownership_instead_of_containment` in `cmd::addons::color::screen_marks::tests`. From ae0b4664a00fa2718c8e5d5d41703b4ef64b7822 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 17:35:30 -0800 Subject: [PATCH 58/88] Scripts: multi-file exports catch case aliases and keep backslashes in Unix names Two destinations that differ only in letter case name one file on Windows and macOS, and a multi-file write now refuses them when either file is new. Files that already exist are still compared by their real paths, so two files in a case-sensitive folder stay distinct. On Linux and macOS a backslash is part of a file name, so the files written beside an export (per-artboard files, linked images, image maps) now go in the destination's folder instead of taking the name's text before the backslash as a folder. --- crates/engine/src/cmd/fileio/encode.rs | 23 ++++++++++++- crates/engine/src/cmd/fileio/export_names.rs | 36 ++++++++++++++++++-- 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 96e5d2210f..6ac9189b32 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -135,6 +135,27 @@ pub(super) fn add_note(notes: &mut Vec<Note>, note: Note) { } } +/// Whether `\` separates folders in a path: on Windows and on the web, where paths may come from +/// Windows. On other platforms `\` is a character of a file name. +const BACKSLASH_SEPARATES: bool = cfg!(any(windows, target_arch = "wasm32")); + +/// The length of `path`'s folder part, its last separator included. +fn dir_len(path: &str, backslash: bool) -> usize { + let at = if backslash { path.rfind(['/', '\\']) } else { path.rfind('/') }; + at.map_or(0, |i| i + 1) +} + +#[cfg(test)] +mod dir_tests { + #[test] + fn a_backslash_is_part_of_a_file_name_where_it_does_not_separate_folders() { + assert_eq!(super::dir_len("out/a\\b.svg", false), 4, "the file a\\b.svg is in out/"); + assert_eq!(super::dir_len("a\\b.svg", false), 0); + assert_eq!(super::dir_len("out\\a\\b.svg", true), 6); + assert_eq!(super::dir_len("b.svg", true), 0); + } +} + impl Encoded { pub(super) fn one(bytes: Vec<u8>) -> Self { Self { files: vec![(None, bytes)], ..Self::default() } @@ -180,7 +201,7 @@ impl Encoded { /// under their own names, then the image maps as `{image stem}.html` or `.map`. pub fn named<'a>(&'a self, doc: &Document, path: &str) -> Vec<(String, Cow<'a, [u8]>)> { // Siblings keep the path's own separators (this runs on every platform and on the web). - let dir = &path[..path.rfind(['/', '\\']).map_or(0, |i| i + 1)]; + let dir = &path[..dir_len(path, BACKSLASH_SEPARATES)]; let sibling = |name: &str| format!("{dir}{name}"); let mut out: Vec<(String, Cow<[u8]>)> = match self.files.as_slice() { [(_, bytes)] => vec![(path.to_string(), Cow::Borrowed(bytes.as_slice()))], diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index f75da1f6a1..73d93ef549 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -117,20 +117,40 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do /// is compared as written, and its write then reports its own error. #[cfg(not(target_arch = "wasm32"))] pub(super) fn distinct_write_targets<'a>(paths: impl IntoIterator<Item = &'a str>) -> Result<()> { - let mut targets = std::collections::HashSet::new(); + // Files that exist are compared by their real paths. A file a write would create is also + // compared with every other destination by `target_key`. + let mut exact = std::collections::HashSet::new(); + let mut folded: std::collections::HashMap<std::path::PathBuf, bool> = std::collections::HashMap::new(); for path in paths { let real = crate::file_access::resolve(path) .ok() .or_else(|| dangling_target(path)) .or_else(|| std::path::absolute(path).ok()) .unwrap_or_else(|| std::path::PathBuf::from(path)); - if !targets.insert(real) { + let exists = std::fs::symlink_metadata(&real).is_ok(); + let same_new_file = match folded.insert(target_key(real.clone(), FOLD_CASE), exists) { + Some(other_exists) => !(exists && other_exists), + None => false, + }; + if !exact.insert(real) || same_new_file { return Err(EngineError::Other("output destinations resolve to the same file".into())); } } Ok(()) } +/// Whether file names ignore letter case: Windows and macOS file systems do by default, so `A.png` +/// and `a.png` name one file there. Files that already exist are compared by their real paths, so a +/// case-sensitive folder's `A.png` and `a.png` stay two files. +#[cfg(not(target_arch = "wasm32"))] +const FOLD_CASE: bool = cfg!(any(windows, target_os = "macos")); + +/// `real` as compared with the other destinations: in lowercase when `fold_case`. +#[cfg(not(target_arch = "wasm32"))] +fn target_key(real: std::path::PathBuf, fold_case: bool) -> std::path::PathBuf { + if fold_case { std::path::PathBuf::from(real.to_string_lossy().to_lowercase()) } else { real } +} + /// The file a write to `path` creates when `path` is a link (or a chain of at most 40 links) that /// leads to a file that does not exist yet. #[cfg(not(target_arch = "wasm32"))] @@ -163,6 +183,18 @@ fn dangling_target(path: &str) -> Option<std::path::PathBuf> { .or_else(|| std::path::absolute(&at).ok()) } +#[cfg(all(test, not(target_arch = "wasm32")))] +mod case_tests { + use std::path::PathBuf; + + #[test] + fn names_that_differ_only_in_case_are_the_same_file_where_case_is_ignored() { + let key = |p: &str, fold| super::target_key(PathBuf::from(p), fold); + assert_eq!(key("/out/Out.png", true), key("/out/out.png", true), "one file where case is ignored"); + assert_ne!(key("/out/Out.png", false), key("/out/out.png", false), "two files where case counts"); + } +} + /// `a` with the fields of `b`. pub(crate) fn merge(mut a: Value, b: Value) -> Value { if let (Some(a), Value::Object(b)) = (a.as_object_mut(), b) { From a3840176ac0cfc3f9f4ab20d3a5e7b5aa368d1f1 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 18:03:35 -0800 Subject: [PATCH 59/88] Screen print marks: replay-only list counts main's new entry The merge of main added an entry to REPLAY_ONLY beside this branch's activeArtboard row, so the array length is now 40. --- crates/engine/src/command_sets.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 479abfc35a..6c99816e5b 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -39,7 +39,7 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p /// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that /// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out /// ([`Session::journal_for_action`]). -const REPLAY_ONLY: [(&str, &str); 39] = [ +const REPLAY_ONLY: [(&str, &str); 40] = [ ("edit.copy", "artboard"), ("edit.cut", "artboard"), ("file.new", "created"), From f74855acee7c1188f7da3302a75a6331ab3413f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 18:07:50 -0800 Subject: [PATCH 60/88] Swatches: vectorcraft-doc turns swatch-scans on for its own tests The gate's shard check failed on every shard: vectorcraft-doc's tests run in the Rest shard, where no crate turned the swatch-scans feature on, so they built with other features than under `cargo test --workspace`, where vectorcraft-ui-egui's dev-dependency turns it on. vectorcraft-doc now lists itself as a dev-dependency with swatch-scans on, as vectorcraft-pdf and vectorcraft-eps do for their counters, so its tests build with the same features in their shard and with the whole workspace. --- Cargo.lock | 1 + crates/doc/Cargo.toml | 3 +++ 2 files changed, 4 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index ab8d5d83c3..9b38a0a150 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8789,6 +8789,7 @@ dependencies = [ "thiserror 2.0.21", "tiff", "vectorcraft-color", + "vectorcraft-doc", "vectorcraft-geom 0.25.1", "zune-jpeg", ] diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index d018a5f946..ebd2671ae2 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -41,3 +41,6 @@ flate2 = { workspace = true } zune-jpeg = { workspace = true } jpeg-encoder = { workspace = true } proptest = { workspace = true } +# The counter vectorcraft-ui-egui's tests turn on, also when this crate is tested without +# vectorcraft-ui-egui (`cargo xtask ci shard`). +vectorcraft-doc = { path = ".", features = ["swatch-scans"] } From e874618f543219c456a6f86e7acaa5816817169f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 19:18:08 -0800 Subject: [PATCH 61/88] Print: Print as Bitmap sizes its images with craft-print's raster grid Print as Bitmap now takes each printed region's pixel grid from craft_print::raster::raster_grid (storytold/craft-libs#5442) instead of computing it in the engine. The limits are the same: at most 64 megapixels, and one pixel inside the side the renderer draws. The resolution is read through Document::raster_ppi, so a raster effects resolution that is not a number prints at 72 ppi. Before, such a document printed an empty page. The craft-libs pin moves to bc02712d, craft-libs main 4c330f6b plus #5442. --- Cargo.lock | 183 ++++++++++++----------- Cargo.toml | 84 ++++++----- apps/vectorcraft-web/Cargo.toml | 2 +- crates/engine/Cargo.toml | 2 + crates/engine/src/cmd/printadvanced.rs | 23 +-- crates/engine/src/tests/printadvanced.rs | 25 ++++ xtask/src/pdf_deps.rs | 2 +- 7 files changed, 172 insertions(+), 149 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b878d75456..4906096e4b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1256,7 +1256,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-automation", "craft-behavior", @@ -1298,7 +1298,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "crc32fast", "flate2", @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1331,7 +1331,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "rustix 1.1.6", ] @@ -1339,7 +1339,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1364,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1383,7 +1383,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-docpath", @@ -1401,7 +1401,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "crc32fast", "flate2", @@ -1410,7 +1410,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "egui", ] @@ -1418,7 +1418,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "md-5", "rayon", @@ -1427,12 +1427,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-cms", @@ -1452,7 +1452,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-ai-agents", "craft-atomic", @@ -1468,7 +1468,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1478,7 +1478,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "rayon", ] @@ -1486,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1512,7 +1512,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "blake3", "craft-ecproj-format", @@ -1528,7 +1528,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "serde", ] @@ -1536,7 +1536,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1555,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-dwg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "acadrust", "craft-dxf", @@ -1565,7 +1565,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-codepage", "encoding_rs", @@ -1577,7 +1577,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "serde", "serde_json", @@ -1587,12 +1587,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-atomic", "dirs", @@ -1602,7 +1602,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1617,7 +1617,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1636,7 +1636,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1645,7 +1645,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "cap-primitives", "craft-atomic", @@ -1668,12 +1668,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "gif", ] @@ -1681,7 +1681,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "flate2", ] @@ -1689,7 +1689,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1702,7 +1702,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1732,7 +1732,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-dds", "craft-jpeg", @@ -1759,7 +1759,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1777,7 +1777,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "thiserror 2.0.21", ] @@ -1785,7 +1785,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1796,7 +1796,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-host", "craft-i18n", @@ -1811,7 +1811,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-i18n", @@ -1825,7 +1825,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-host", @@ -1843,7 +1843,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1855,7 +1855,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "encoding_rs", "image", @@ -1866,7 +1866,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "chrono", "craft-codepage", @@ -1876,7 +1876,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "uds_windows", "winsafe", @@ -1885,7 +1885,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-keymap", @@ -1901,7 +1901,7 @@ dependencies = [ [[package]] name = "craft-pbr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-texture", "thiserror 2.0.21", @@ -1910,7 +1910,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "flate2", "serde", @@ -1921,7 +1921,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1933,7 +1933,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "async-channel", "async-io", @@ -1966,7 +1966,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1975,7 +1975,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-host", @@ -1999,7 +1999,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -2010,7 +2010,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-eps", "flate2", @@ -2024,7 +2024,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "encoding_rs", "flate2", @@ -2035,7 +2035,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "dispatch2", "egui", @@ -2048,7 +2048,7 @@ dependencies = [ [[package]] name = "craft-raster3d" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "rayon", "thiserror 2.0.21", @@ -2057,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -2076,7 +2076,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-atomic", "craft-host", @@ -2093,7 +2093,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "fax", "hayro-ccitt", @@ -2104,7 +2104,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2125,7 +2125,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-keymap", @@ -2137,7 +2137,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2162,7 +2162,7 @@ dependencies = [ [[package]] name = "craft-texture" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "thiserror 2.0.21", ] @@ -2170,7 +2170,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2185,7 +2185,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-atomic", "craft-behavior", @@ -2200,7 +2200,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "serde", "thiserror 2.0.21", @@ -2210,7 +2210,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "serde", "thiserror 2.0.21", @@ -2219,7 +2219,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-keymap", @@ -2234,12 +2234,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2253,7 +2253,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -2270,7 +2270,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "accesskit", "craft-behavior", @@ -2308,7 +2308,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2319,7 +2319,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-host", @@ -2337,7 +2337,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-host", @@ -2358,7 +2358,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-host", @@ -2379,7 +2379,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-behavior", "craft-host", @@ -2398,7 +2398,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "base64 0.22.1", "chrono", @@ -2430,7 +2430,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "flate2", "serde", @@ -2441,7 +2441,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2451,7 +2451,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "js-sys", "serde_json", @@ -2462,7 +2462,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "winsafe", ] @@ -2470,7 +2470,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "craft-appkit", "craft-atomic", @@ -2502,7 +2502,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3862,7 +3862,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3871,7 +3871,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3889,7 +3889,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3907,12 +3907,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "flate2", "hayro-ccitt", @@ -4895,7 +4895,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "base64 0.22.1", "bumpalo", @@ -5052,7 +5052,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=bc02712d20e78db2cff7bc85139418889a8547c5#bc02712d20e78db2cff7bc85139418889a8547c5" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -8834,6 +8834,7 @@ dependencies = [ "craft-font-store", "craft-image-codecs", "craft-jxl", + "craft-print", "craft-proof", "craft-stream-codecs", "craft-xml", diff --git a/Cargo.toml b/Cargo.toml index a48e3c1330..b5044bfb02 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,57 +10,59 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +# Print as Bitmap's pixel grid (`craft_print::raster`). +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } # 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } # DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified). -craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } # The metallic-roughness BRDF and environment light the 3D effects' Roughness and Metallic shade with. -craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } # The CPU rasterizer that draws a 3D effect's Render Settings › Rendered image: depth-buffered triangles, shadow maps. -craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -200,13 +202,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5" } # skrifa 0.44 (epaint, glifo, usvg) with the automatic hinter's long blue-zone exit (craft-libs vendor/skrifa). # It stays at this rev until craft-libs#5222 merges. skrifa = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 4db9a1dac2..8a50676f3d 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "bc02712d20e78db2cff7bc85139418889a8547c5", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 2487dcd01d..fe18d2eae6 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -23,6 +23,8 @@ craft-codepage = { workspace = true } # Which paths stored in documents may be opened. craft-docpath = { workspace = true } craft-proof = { workspace = true } +# Print as Bitmap's pixel grid. +craft-print = { workspace = true } vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } vectorcraft-doc = { workspace = true } diff --git a/crates/engine/src/cmd/printadvanced.rs b/crates/engine/src/cmd/printadvanced.rs index 1051342262..9b3ff72eea 100644 --- a/crates/engine/src/cmd/printadvanced.rs +++ b/crates/engine/src/cmd/printadvanced.rs @@ -5,6 +5,7 @@ use std::sync::Arc; +use craft_print::raster::{RasterLimits, raster_grid}; use vectorcraft_doc::marks::outset; use vectorcraft_doc::{Document, ImageBlob, ImageObject, LayerColor, Node, NodeKind}; use vectorcraft_geom::{Affine, Rect}; @@ -77,21 +78,13 @@ fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: b let mut images = vec![]; for (_, r) in regions { let area = outset(r, bleed); - // At most MAX_PIXELS, and no side longer than the renderer draws (rounded up to whole - // pixels below). - let side = area.width().max(area.height()).max(1.0); - let longest = f64::from(vectorcraft_render::MAX_RASTER_SIDE) - 2.0; - let scale = (doc.raster_effects_ppi / 72.0).min((MAX_PIXELS / (area.width() * area.height()).max(1.0)).sqrt()).min(longest / side); - if !(scale.is_finite() && scale > 0.0) { - continue; - } - // Whole pixels. - let region = Rect::new( - area.x0, - area.y0, - area.x0 + (area.width() * scale).ceil().max(1.0) / scale, - area.y0 + (area.height() * scale).ceil().max(1.0) / scale, - ); + // At most MAX_PIXELS, and one pixel inside the side the renderer draws, which may round + // the grid's side up once more. + let limits = RasterLimits { max_pixels: MAX_PIXELS, max_side: vectorcraft_render::MAX_RASTER_SIDE - 1 }; + let grid = raster_grid(area.width(), area.height(), doc.raster_ppi(), limits).map_err(|e| bad(cmd, e))?; + let scale = grid.scale; + let (width, height) = grid.size(); + let region = Rect::new(area.x0, area.y0, area.x0 + width, area.y0 + height); let img = renderer.render_region_with(&art, region, scale, &opts); if img.pixels.as_chunks::<4>().0.iter().all(|px| px[3] == 0) { continue; diff --git a/crates/engine/src/tests/printadvanced.rs b/crates/engine/src/tests/printadvanced.rs index e183e7dfb2..4c118f5738 100644 --- a/crates/engine/src/tests/printadvanced.rs +++ b/crates/engine/src/tests/printadvanced.rs @@ -152,6 +152,31 @@ fn print_as_bitmap_prints_all_of_a_long_artboard() { assert!(b.x0 <= 0.0 && b.x1 >= 9000.0, "the image covers the artboard: {b:?}"); } +/// A raster effects resolution that isn't a number prints at the resolution the document reads it +/// as (72 ppi), not as an empty page. +#[test] +fn print_as_bitmap_of_a_resolution_that_is_not_a_number_prints_at_72_ppi() { + let (s, _) = session(); + let saved = s.prefs.flattener_presets.clone(); + let set = settings(json!({"advanced": {"printAsBitmap": true}})); + let widths = |ppi: f64| { + let mut d = doc(&s).clone(); + d.raster_effects_ppi = ppi; + let bitmap = crate::cmd::printadvanced::prepare("file.print", &d, &set, &saved, false).unwrap().unwrap(); + let mut widths = vec![]; + bitmap.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + widths.push(im.width); + } + }); + widths + }; + let at_72 = widths(72.0); + assert_eq!(at_72.len(), 1, "{at_72:?}"); + assert_eq!(widths(f64::NAN), at_72); + assert!(widths(144.0)[0] > at_72[0], "the resolution decides the image's size"); +} + /// Appearance of Black › Printing / Exporting (#394): Print as Bitmap draws pure CMYK black as RGB /// black when `rich_black` is on. #[test] diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 04cf313ca0..1ae63464cc 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8"; +const REV: &str = "bc02712d20e78db2cff7bc85139418889a8547c5"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From 0cd2bab6f9b27b5c0be0706806bcfed5c517e5f6 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 20:14:43 -0800 Subject: [PATCH 62/88] CI: build the tests once and run every shard from a nextest archive Each of the five test shards compiled its own tests: 8 to 18 minutes with a cache hit and 25 to 43 minutes with a miss, on every shard of every run. The gate's build job now builds every shard's tests once (`cargo xtask ci archive`) and writes one nextest archive per shard with that shard's test binaries (`Shard::filterset`). The test legs download their own archive and run it without building or restoring the dependency cache. The build job runs the doctests after the upload (`cargo xtask ci doctests`), and on main it saves the rolling dependency cache in place of the `cache warm` legs. The ci steps that are not tests (fmt, clippy, no-bundled-fonts and the other checks) move from shard 6 to the gate's lint leg (`cargo xtask ci checks`), which runs beside the build with a cache entry of its own. The gate now has five test shards; `ci warm` and the warm split are removed. The nightly signing policy lists the new job names (build, lint and test 1/5 to 5/5), and the cold cache clear waits for the build job's save. Co-authored-by: Elvis33LE <markusseiler@gmx.net> --- .github/nightly-signing-policy.json | 14 +- .github/workflows/ci.yml | 54 ++-- docs/nightly-release-preparation.md | 7 +- scripts/ci-clear-rolling-cache-tests.py | 8 +- scripts/ci-clear-rolling-cache.py | 22 +- xtask/src/cache_units.rs | 2 +- xtask/src/main.rs | 353 ++++++++++++------------ xtask/src/shards.rs | 300 ++++++++++---------- 8 files changed, 382 insertions(+), 378 deletions(-) diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 55d2a1983c..ccd7767934 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -33,37 +33,37 @@ "applicability": "required" }, { - "name": "gate / cache warm (ubuntu-24.04)", + "name": "gate / build (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, { - "name": "gate / test 1/6 (ubuntu-24.04)", + "name": "gate / lint (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, { - "name": "gate / test 2/6 (ubuntu-24.04)", + "name": "gate / test 1/5 (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, { - "name": "gate / test 3/6 (ubuntu-24.04)", + "name": "gate / test 2/5 (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, { - "name": "gate / test 4/6 (ubuntu-24.04)", + "name": "gate / test 3/5 (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, { - "name": "gate / test 5/6 (ubuntu-24.04)", + "name": "gate / test 4/5 (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, { - "name": "gate / test 6/6 (ubuntu-24.04)", + "name": "gate / test 5/5 (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 53a9be4e4a..22d31b9133 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,9 +31,9 @@ jobs: with: # Same craft-fonts commit as release.yml. craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c - # A cold `cache warm` leg (the nightly run, or any run after a toolchain or lockfile change) - # took 90 minutes to reach its last three steps on 2026-11-27 and was canceled there; with - # those steps and the save it needs about two hours. + # A cold build of every shard's tests (the nightly run, or any run after a toolchain or + # lockfile change) took 90 minutes to reach its last three steps on 2026-11-27 and was + # canceled there; with those steps and the save it needs about two hours. timeout-minutes: 150 # The gate's test binaries carry no debug info and no symbols (CARGO_PROFILE_TEST_DEBUG=0, # CARGO_PROFILE_TEST_STRIP=symbols), as photocraft's do: linking ~100 test binaries with line @@ -43,19 +43,24 @@ jobs: dev-strip: true # The workspace crates also build without line tables. A panic still names its file and line. dev-debug: "0" - # Six legs instead of one: shards 1 and 2 each build vectorcraft-ui-egui's tests and run - # half of them, shards 3 to 5 each build and run the tests of their own crates, and shard 6 - # runs the other `cargo xtask ci` steps (xtask/src/shards.rs). `gate (<os>)` passes only - # when all six did. On pushes to main, a `cache warm` leg builds what every shard builds and - # saves the dependency cache. - test-shards: 6 + # The `build (<os>)` job builds the tests once and writes one nextest archive per shard with + # that shard's test binaries (`cargo xtask ci archive`), then runs the doctests. Five test + # legs download their own archive and run it without building: shards 1 and 2 each run half + # of vectorcraft-ui-egui's tests, and shards 3 to 5 the tests of their own crates + # (xtask/src/shards.rs). The `lint (<os>)` leg runs the other `cargo xtask ci` steps beside + # them, with a dependency cache of its own. `gate (<os>)` passes when the build and every + # test leg that ran passed; `lint (<os>)` is a check of its own. + test-shards: 5 shard-command: cargo xtask ci shard - warm-command: cargo xtask ci warm + archive-command: cargo xtask ci archive + shard-archives: true + after-archive-command: cargo xtask ci doctests + lint-command: cargo xtask ci checks # A pull request runs only the test shards whose crates its changes reach: the crates that # own a changed file or declare a read of it (`[package.metadata.craft] reads`), and every - # crate that depends on them. Shard 6 runs on every event. The `select legs` log lists the - # shards left out and why; pushes to main, the nightly run and the `full-ci` label run all - # six. `shard-members` names each shard's crates, as xtask/src/shards.rs › GROUPS does. + # crate that depends on them. The `select legs` log lists the shards left out and why; pushes + # to main, the nightly run and the `full-ci` label run all five. `shard-members` names each + # shard's crates, as xtask/src/shards.rs › GROUPS does. select-tests: true shard-members: | vectorcraft-ui-egui @@ -63,13 +68,9 @@ jobs: vectorcraft-engine vectorcraft vectorcraft-web vectorcraft-cli vectorcraft-mcp xtask (rest) - (always) - # The warm build runs as one `cache warm <k>/6` leg per shard, in parallel (each builds what - # its shard builds), and `cache warm` puts their files into the one entry it saves. - warm-split: true # The dependency cache also keeps the compiled workspace crates and test executables, so a - # pull request's shards rebuild only the crates its changes reach. Each main run's `cache - # warm` leg saves a rolling entry of its own, every leg restores the newest one, and + # pull request's build rebuilds only the crates its changes reach. Each main run's `build` + # job saves a rolling entry of its own, every build restores the newest one, and # cache-prune.yml deletes the one it replaced after each attempt. The nightly run restores # nothing and builds everything from source. cache-workspace-crates: true @@ -82,15 +83,12 @@ jobs: # The nightly cold run never restores the rolling crates entry, so the old entry is only overlap # while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the # 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes - # the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py). - # When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run - # failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a - # free runner, and with `warm-split` after every `cache warm <k>/6` leg. The script suspends its - # start deadline while any split leg is queued or running, then allows 180 minutes from the last - # split completion for the saving leg to start. Without split legs, it allows 180 minutes from - # the script's start. A failed split leg fails this job too. The script then waits up to 160 - # minutes from the saving leg's start. GitHub's 360-minute job limit can end this job before the - # script's deadlines expire when split builds or runner waits take too long. + # the old entries when the `build` job starts saving (scripts/ci-clear-rolling-cache.py). When + # the job fails or is canceled, before its save or during it, this job fails too, so "Re-run + # failed jobs" runs it again beside the re-run build. The build starts after `gate / select legs` + # and a free runner. The script allows 180 minutes from its start for the build to start, then + # waits up to 160 minutes from the build's start. GitHub's 360-minute job limit can end this job + # before the script's deadlines expire when runner waits take too long. cold-cache-clear: name: cold cache clear if: github.event_name == 'schedule' diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md index c2b4917fad..29ca838f1d 100644 --- a/docs/nightly-release-preparation.md +++ b/docs/nightly-release-preparation.md @@ -81,9 +81,10 @@ Read on 2026-11-24; re-read anything that may have moved before `nightly-signer` | `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `380135806`), 9 jobs | Workflow list API; jobs that succeeded on recent main push runs | | `candidate_policy.sonar` | `storytold` / `storytold_vectorcraft`, app `12526` | `sonar-project.properties`; the SonarCloud check on main commits | -The signer reads the policy from `nightly-signer`, so a candidate whose CI ran six test shards -(`test 1/6` to `test 6/6`) is admitted only after `nightly-signer` advances to a main commit with -this policy. Candidates whose CI ran five shards should be signed before that advance. +The signer reads the policy from `nightly-signer`, so a candidate whose CI built the tests once +(`build`, `lint` and `test 1/5` to `test 5/5`) is admitted only after `nightly-signer` advances to +a main commit with this policy. Candidates whose CI ran six shards (`cache warm` and `test 1/6` to +`test 6/6`) should be signed before that advance. ## Ownership and interface diff --git a/scripts/ci-clear-rolling-cache-tests.py b/scripts/ci-clear-rolling-cache-tests.py index 5684762f4e..7887b3bd7f 100644 --- a/scripts/ci-clear-rolling-cache-tests.py +++ b/scripts/ci-clear-rolling-cache-tests.py @@ -18,7 +18,7 @@ _spec = importlib.util.spec_from_file_location("clear", Path(__file__).with_name clear = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(clear) -WARM = "gate / cache warm (ubuntu-24.04)" +WARM = "gate / build (ubuntu-24.04)" ME = [{"name": "cold cache clear", "status": "in_progress"}] @@ -166,8 +166,10 @@ class Workflow(unittest.TestCase): class Jobs(unittest.TestCase): def test_only_the_warm_leg_counts(self): - jobs = [{"name": "gate / test 1/5 (ubuntu-24.04)"}, {"name": "gate / build (${{ matrix.os }})"}, {"name": WARM}] - self.assertEqual(clear.warm_job(jobs), jobs[2]) + jobs = [{"name": "gate / test 1/5 (ubuntu-24.04)"}, {"name": "gate / build (${{ matrix.os }})"}, + {"name": "gate / cache warm (ubuntu-24.04)"}, {"name": WARM}] + self.assertEqual(clear.warm_job(jobs), jobs[3]) + self.assertIsNone(clear.warm_job(jobs[:3])) def test_a_rerun_of_failed_jobs_skips_a_leg_that_succeeded(self): grace = clear.RERUN_GRACE_SECONDS diff --git a/scripts/ci-clear-rolling-cache.py b/scripts/ci-clear-rolling-cache.py index 6a9f3cdc88..e3f013afab 100644 --- a/scripts/ci-clear-rolling-cache.py +++ b/scripts/ci-clear-rolling-cache.py @@ -6,7 +6,7 @@ The cold run (ci.yml, `cold-build`) never restores the rolling entry, so the old one only adds to the cache while the new one is saved: two entries of about 4.6 GB each, beside the others, go over the repository's 10 GB limit and GitHub evicts the corpus, SonarCloud and Windows ARM64 entries. The -gate's `cache warm` leg saves in its `Post Setup` step; this deletes the old entries when that step +gate's `build` leg saves in its `Post Setup` step; this deletes the old entries when that step starts, then waits for the step to finish. Pull requests and pushes that start in the minutes between restore nothing from the deleted entry and build cold once. Deleting is the only write; the entry the cold run saves does not exist yet when this runs. Only entries created before this run @@ -35,7 +35,9 @@ import sys import time REF = 'refs/heads/main' -WARM_JOB = re.compile(r'^gate / cache warm \(') +# The leg that saves the rolling entry: the gate's `build` job (ci.yml's `archive-command`). While +# the job is skipped, GitHub lists it as `gate / build (${{ matrix.os }})`. +WARM_JOB = re.compile(r'^gate / build \((?!\$\{\{)') SPLIT_WARM_JOB = re.compile(r'^gate / cache warm \d+/\d+ \(') # The jobs the gate's legs need (craft-common-actions .github/workflows/gate.yml): when one of # them fails or is canceled, the legs are skipped and no warm leg is listed. With `warm-split` the @@ -64,8 +66,8 @@ START_SECONDS = 180 * 60 STOPPED = ('failure', 'cancelled', 'timed_out') # Steps with continue-on-error in craft-common-actions .github/workflows/gate.yml. TOLERATED_FAILURES = ('Trim the cache entry to this build',) -NO_SAVE = 'the cache warm leg failed or was canceled and saves no entry; nothing deleted. Re-running the failed jobs runs this job again with the leg' -SAVE_LOST = 'the cache warm leg did not finish its save after the old rolling entries were deleted; the next run starts cold' +NO_SAVE = 'the build leg failed or was canceled and saves no entry; nothing deleted. Re-running the failed jobs runs this job again with the leg' +SAVE_LOST = 'the build leg did not finish its save after the old rolling entries were deleted; the next run starts cold' def save_step(job): @@ -194,7 +196,7 @@ def main(): job = warm_job(jobs.get('jobs', [])) ready = start_wait_began(jobs.get('jobs', []), began) if started_late(job, ready): - print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted') + print(f'::error::the build leg did not start within {START_SECONDS // 60} minutes; nothing deleted') return 1 if job and saving(job): break @@ -206,7 +208,7 @@ def main(): if warm_job(earlier_jobs[earlier]) is not None: break if not_in_attempt(jobs.get('jobs', []), earlier_jobs, (datetime.now(timezone.utc) - began).total_seconds()): - print('the cache warm leg is not part of this attempt (it succeeded in an earlier one); nothing deleted') + print('the build leg is not part of this attempt (it succeeded in an earlier one); nothing deleted') return if legs_stopped(jobs.get('jobs', [])): print('::error::the gate stopped before its cache warm leg started; nothing deleted') @@ -216,14 +218,14 @@ def main(): if job.get('conclusion') in STOPPED or job.get('conclusion') == 'skipped' and legs_stopped(jobs.get('jobs', [])): print(f'::error::{NO_SAVE}') return 1 - print('the cache warm leg finished without a save step; nothing deleted') + print('the build leg finished without a save step; nothing deleted') return now = datetime.now(timezone.utc) if start_overdue(job, now, ready): - print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted') + print(f'::error::the build leg did not start within {START_SECONDS // 60} minutes; nothing deleted') return 1 if gave_up(job, now): - print('::error::the cache warm leg never reached its save; nothing deleted') + print('::error::the build leg never reached its save; nothing deleted') return 1 time.sleep(POLL_SECONDS) if saves_nothing(job): @@ -249,7 +251,7 @@ def main(): if saves_nothing(job): print(f'::error::{SAVE_LOST}') return 1 - print('the cache warm leg saved its entry') + print('the build leg saved its entry') if __name__ == '__main__': diff --git a/xtask/src/cache_units.rs b/xtask/src/cache_units.rs index a3b0a611c0..686a17c2f3 100644 --- a/xtask/src/cache_units.rs +++ b/xtask/src/cache_units.rs @@ -3,7 +3,7 @@ //! In a gate leg that saves the dependency cache, craft-common-actions' `rust-cache` action names a //! file in `CRAFT_CACHE_UNITS`, and its `cache-trim` action deletes every build unit of the target //! directory that the file does not name before the entry is saved. Cargo prints a JSON message for -//! every unit a build compiled or found fresh. The builds of `cargo xtask ci warm` append those +//! every unit a build compiled or found fresh. The builds of `cargo xtask ci archive` append those //! messages to the file, so the saved entry holds this build and no older builds of updated //! dependencies. Without `CRAFT_CACHE_UNITS` the commands run as they always have. diff --git a/xtask/src/main.rs b/xtask/src/main.rs index a09949f548..cefae8c6a6 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -50,11 +50,14 @@ commands: wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates, the web app and its plug-in worker test the workspace tests (cargo nextest when installed, else cargo test), then the doctests ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, grant-sites, cursors (warnings only), test-lint, ui-commands --check, layers, wasm (stops at first failure) - ci shard shard $GATE_SHARD of $GATE_SHARDS of ci (xtask/src/shards.rs): a test shard runs - the tests and doctests of its crates, the last shard the other steps - ci warm build what every shard builds, without running it (fills the gate's cache); with - GATE_SHARD of GATE_SHARDS set, only what that shard builds; with - CRAFT_CACHE_UNITS set, appends Cargo's JSON messages for each build to that file + ci shard shard $GATE_SHARD of $GATE_SHARDS of ci's tests (xtask/src/shards.rs): from the + nextest archive in $NEXTEST_ARCHIVE_FILE when set, otherwise it builds them and + also runs the doctests of its crates + ci archive build every shard's tests once and write shard k's nextest archive to + $NEXTEST_ARCHIVE_DIR/<k>/$NEXTEST_ARCHIVE_NAME for k from 1 to $GATE_SHARDS; with + CRAFT_CACHE_UNITS set, appends Cargo's JSON messages for the build to that file + ci doctests the workspace doctests + ci checks the ci steps other than the tests, the doctests and the i18n report shards list the crates each shard tests; fails when a member is in no shard or in two, or builds with other features in its shard than in the whole workspace corpus [--download | --affinity | --scripts] @@ -95,7 +98,9 @@ fn main() -> ExitCode { Some("wasm") => cmd_wasm(), Some("test") => cmd_test().and_then(|()| cmd_doctests()), Some("ci") if rest.first() == Some(&"shard") => cmd_ci_shard(), - Some("ci") if rest.first() == Some(&"warm") => cmd_ci_warm(), + Some("ci") if rest.first() == Some(&"archive") => cmd_ci_archive(), + Some("ci") if rest.first() == Some(&"doctests") => cmd_doctests(), + Some("ci") if rest.first() == Some(&"checks") => cmd_ci_checks(), Some("ci") => cmd_ci(), Some("shards") => shards::run().map(drop), Some("corpus") => cmd_corpus_args(&rest), @@ -288,46 +293,62 @@ fn cmd_test() -> Result<(), String> { /// which needs nextest. A part runs its counted share, then its pinned tests, each with /// nextest's default thread count. Every run finishes before the first error is returned. fn test_packages(select: &[String], shown: &str, targets: shards::Targets, part: Option<shards::Part>) -> Result<(), String> { - let (listed, targets) = (targets.shown(), targets.args()); - if let Some(part) = part { - if !has_nextest() { - return Err(format!("cargo nextest run {shown}: a shard that runs part of a crate's tests needs cargo-nextest")); - } - let mut c = cargo(); - c.args(["nextest", "list", "--color", "never", "--message-format", "json"]).args(select).args(targets); - let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("cargo nextest list {shown}: failed to spawn: {e}"))?; - if !out.status.success() { - return Err(format!("cargo nextest list {shown}: exited with {}", out.status)); - } - let missing = part.missing_pins(&String::from_utf8_lossy(&out.stdout)).map_err(|e| format!("cargo nextest list {shown}: {e}"))?; - if !missing.is_empty() { - return Err(format!( - "cargo nextest list {shown}: no test has the full name of pinned test(s) {} (update `pinned` in xtask/src/shards.rs)", - missing.join(", ") - )); - } - let command = |args: Vec<String>| { - let mut c = cargo(); - c.args(["nextest", "run"]).args(select).args(targets).args(&args); - let quoted = args.iter().map(|a| if a.contains(' ') { format!("'{a}'") } else { a.clone() }).collect::<Vec<_>>().join(" "); - (c, format!("cargo nextest run {shown} {listed} {quoted}")) - }; - let mut result = Ok(()); - for args in part.runs() { - let (c, what) = command(args); - result = result.and(run(c, &what)); - } - return result; - } - let mut c = cargo(); - if has_nextest() { - c.args(["nextest", "run"]).args(select).args(targets); - run(c, &format!("cargo nextest run {shown} {listed}")) - } else { + let (listed, args) = (targets.shown(), targets.args()); + if part.is_none() && !has_nextest() { eprintln!("note: cargo-nextest is not installed; running cargo test (cargo install cargo-nextest for faster runs)"); - c.arg("test").args(select).args(targets); - run(c, &format!("cargo test {shown} {listed}")) + let mut c = cargo(); + c.arg("test").args(select).args(args); + return run(c, &format!("cargo test {shown} {listed}")); } + let nextest = |sub: &str| { + let mut c = cargo(); + c.args(["nextest", sub]).args(select).args(args); + c + }; + nextest_tests(&nextest, &format!("{shown} {listed}"), part) +} + +/// The tests of the nextest archive `file`, which `cargo xtask ci archive` wrote for one shard; +/// with `part`, that part's share of them, as [`test_packages`] runs it. +fn archive_tests(file: &Path, part: Option<shards::Part>) -> Result<(), String> { + let nextest = |sub: &str| { + let mut c = cargo(); + c.args(["nextest", sub, "--archive-file"]).arg(file).arg("--workspace-remap").arg(root()); + c + }; + nextest_tests(&nextest, &format!("--archive-file {}", file.display()), part) +} + +/// The tests `nextest(sub)` selects for `cargo nextest <sub>`, shown after the subcommand as +/// `shown`; with `part`, only that part's share of them (see [`test_packages`]). +fn nextest_tests(nextest: &dyn Fn(&str) -> Command, shown: &str, part: Option<shards::Part>) -> Result<(), String> { + if !has_nextest() { + return Err(format!("cargo nextest run {shown}: a shard that runs part of a crate's tests, or runs an archive, needs cargo-nextest")); + } + let Some(part) = part else { + return run(nextest("run"), &format!("cargo nextest run {shown}")); + }; + let mut c = nextest("list"); + c.args(["--color", "never", "--message-format", "json"]); + let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("cargo nextest list {shown}: failed to spawn: {e}"))?; + if !out.status.success() { + return Err(format!("cargo nextest list {shown}: exited with {}", out.status)); + } + let missing = part.missing_pins(&String::from_utf8_lossy(&out.stdout)).map_err(|e| format!("cargo nextest list {shown}: {e}"))?; + if !missing.is_empty() { + return Err(format!( + "cargo nextest list {shown}: no test has the full name of pinned test(s) {} (update `pinned` in xtask/src/shards.rs)", + missing.join(", ") + )); + } + let mut result = Ok(()); + for args in part.runs() { + let mut c = nextest("run"); + c.args(&args); + let quoted = args.iter().map(|a| if a.contains(' ') { format!("'{a}'") } else { a.clone() }).collect::<Vec<_>>().join(" "); + result = result.and(run(c, &format!("cargo nextest run {shown} {quoted}"))); + } + result } /// The doctests, which nextest doesn't run. @@ -350,7 +371,8 @@ fn doctest_packages(crates: &[shards::Member]) -> Result<(), String> { /// One `cargo xtask ci` step: its name and what it runs. type Step = (&'static str, Box<dyn Fn() -> Result<(), String>>); -/// The `ci` steps that build and run tests of the whole workspace; `ci shard` runs them per shard. +/// The `ci` steps that build and run tests of the whole workspace; `ci shard` runs them per shard, +/// and `ci checks` runs the other steps. const TEST_STEPS: [&str; 3] = ["test", "doctests", "i18n-report"]; /// `cargo xtask ci`: each step in turn, stopping at the first that fails; the summary names the @@ -359,142 +381,124 @@ fn cmd_ci() -> Result<(), String> { run_steps(&ci_steps()) } -/// `cargo xtask ci shard`: shard `GATE_SHARD` of `GATE_SHARDS` (1-based, as the shared gate -/// workflow sets them). A test shard runs the shard checks, then the tests and doctests of its -/// crates, and the i18n report where it tests vectorcraft-ui-egui; a part of a split runs its -/// share of the tests, and only part 1 the doctests and the report. The checks shard runs every -/// other `ci` step and the shard checks. -fn cmd_ci_shard() -> Result<(), String> { - let number = |key: &str| -> Result<usize, String> { - let value = std::env::var(key).map_err(|_| format!("ci shard: {key} is not set (the gate workflow sets it)"))?; - value.trim().parse().map_err(|_| format!("ci shard: {key} is `{value}`, not a number")) - }; - let (shard, count) = (number("GATE_SHARD")?, number("GATE_SHARDS")?); +/// `GATE_SHARDS`, the shard count the shared gate workflow sets, for `ci <what>`; it must equal +/// the number of shards in xtask/src/shards.rs. +fn gate_shards(what: &str) -> Result<usize, String> { + let count = gate_number(what, "GATE_SHARDS")?; if count != shards::GROUPS.len() { return Err(format!( - "ci shard: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)", + "ci {what}: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)", shards::GROUPS.len() )); } + Ok(count) +} + +/// The number in the environment variable `key`, which the shared gate workflow sets. +fn gate_number(what: &str, key: &str) -> Result<usize, String> { + let value = std::env::var(key).map_err(|_| format!("ci {what}: {key} is not set (the gate workflow sets it)"))?; + value.trim().parse().map_err(|_| format!("ci {what}: {key} is `{value}`, not a number")) +} + +/// `cargo xtask ci shard`: shard `GATE_SHARD` of `GATE_SHARDS` (1-based, as the shared gate +/// workflow sets them). A shard runs the tests of its crates, and the i18n report where it tests +/// vectorcraft-ui-egui; a part of a split runs its share of the tests, and only part 1 the report. +/// +/// With `NEXTEST_ARCHIVE_FILE` set (the gate's shard legs), it runs the tests of that archive, +/// which `ci archive` built for this shard after the shard checks, and leaves the doctests to +/// `ci doctests`. Otherwise it runs the shard checks, builds the tests, and runs the doctests of +/// its crates on part 1 too. +fn cmd_ci_shard() -> Result<(), String> { + let count = gate_shards("shard")?; + let shard = gate_number("shard", "GATE_SHARD")?; if !(1..=count).contains(&shard) { return Err(format!("ci shard: GATE_SHARD is {shard}, not 1 to {count}")); } - let checked = shards::run()?; + let archive = std::env::var_os("NEXTEST_ARCHIVE_FILE").filter(|f| !f.is_empty()).map(PathBuf::from); + let shards::Shard { runs, part } = if archive.is_some() { shards::assigned()? } else { shards::run()? }.swap_remove(shard - 1); + let share = part.map(|p| format!(" (part {} of {})", p.index, p.split.parts())).unwrap_or_default(); + eprintln!("ci shard {shard}/{count}: the tests of {}{share}", shards::describe(&runs)); + let first = part.is_none_or(|p| p.is_first()); + let report = + runs.iter().find(|r| r.targets == shards::Targets::All && r.crates.iter().any(|m| m.name == "vectorcraft-ui-egui")).filter(|_| first); let mut steps: Vec<Step> = Vec::new(); - match &checked[shard - 1] { - shards::Shard::Tests(runs, part) => { - let share = part.map(|p| format!(" (part {} of {})", p.index, p.split.parts())).unwrap_or_default(); - eprintln!("ci shard {shard}/{count}: the tests of {}{share}", shards::describe(runs)); - let shown = |crates: &[shards::Member]| crates.iter().map(|m| format!("-p {}", m.name)).collect::<Vec<_>>().join(" "); - let part = *part; - let tests: Vec<(Vec<String>, String, shards::Targets)> = - runs.iter().map(|r| (shards::select(&r.crates), shown(&r.crates), r.targets)).collect(); - // Each run finishes before the first error is returned. - steps.push(( - "test", - Box::new(move || { - let mut result = Ok(()); - for (s, w, t) in &tests { - result = result.and(test_packages(s, w, *t, part)); - } - result - }), - )); - // The doctests and the i18n report run once, on a split's first part. - let first = part.is_none_or(|p| p.is_first()); - if first { - let c = shards::unit_crates(runs); - steps.push(("doctests", Box::new(move || doctest_packages(&c)))); - } - let all = runs.iter().find(|r| r.targets == shards::Targets::All && r.crates.iter().any(|m| m.name == "vectorcraft-ui-egui")); - if let Some(r) = all.filter(|_| first) { - let (select, shown) = (shards::select(&r.crates), shown(&r.crates)); - steps.push(("i18n-report", Box::new(move || i18n_report_packages(&select, &shown)))); - } - } - shards::Shard::Checks => { - eprintln!("ci shard {shard}/{count}: the ci steps other than the tests"); - steps.extend(ci_steps().into_iter().filter(|(name, _)| !TEST_STEPS.contains(name))); + if let Some(file) = archive { + let tests = file.clone(); + steps.push(("test", Box::new(move || archive_tests(&tests, part)))); + if report.is_some() { + steps.push(("i18n-report", Box::new(move || i18n_report_archive(&file)))); } + return run_steps(&steps); + } + let shown = |crates: &[shards::Member]| crates.iter().map(|m| format!("-p {}", m.name)).collect::<Vec<_>>().join(" "); + let report = report.map(|r| (shards::select(&r.crates), shown(&r.crates))); + let tests: Vec<(Vec<String>, String, shards::Targets)> = runs.iter().map(|r| (shards::select(&r.crates), shown(&r.crates), r.targets)).collect(); + // Each run finishes before the first error is returned. + steps.push(( + "test", + Box::new(move || { + let mut result = Ok(()); + for (s, w, t) in &tests { + result = result.and(test_packages(s, w, *t, part)); + } + result + }), + )); + // The doctests and the i18n report run once, on a split's first part. + if first { + let c = shards::unit_crates(&runs); + steps.push(("doctests", Box::new(move || doctest_packages(&c)))); + } + if let Some((select, shown)) = report { + steps.push(("i18n-report", Box::new(move || i18n_report_packages(&select, &shown)))); } run_steps(&steps) } -/// `cargo xtask ci warm`: for each run of each test shard, builds the test targets it runs without -/// running them, then builds what the checks shard builds, so one dependency-cache entry holds the -/// dependencies of every shard with the features that shard builds them with (cargo resolves -/// features over the packages each command selects). The test builds select the same crates and -/// targets as the test shards' runs, so the cache also holds the test executables the shards run. -/// -/// With `GATE_SHARD` and `GATE_SHARDS` set (the gate's split warm legs), it builds only what that -/// shard builds: a test shard's tests, or the checks shard's builds. A split's later parts build -/// nothing in either case, since part 1 builds the same tests. -/// -/// In a leg that saves the cache, every build records its units in `CRAFT_CACHE_UNITS` -/// (xtask/src/cache_units.rs), xtask's own build included. -fn cmd_ci_warm() -> Result<(), String> { - let var = |key: &str| match std::env::var(key) { - Ok(value) => Ok(Some(value)), - Err(std::env::VarError::NotPresent) => Ok(None), - Err(std::env::VarError::NotUnicode(_)) => Err(format!("ci warm: {key} is not valid Unicode")), +/// `cargo xtask ci archive`: the shared gate's `build` job (`archive-command` with +/// `shard-archives`). After the shard checks it builds every shard's tests in one workspace build, +/// which records its units in a leg that saves the cache, then writes the test binaries of shard +/// k (1-based, [`shards::Shard::filterset`]) to the nextest archive +/// `$NEXTEST_ARCHIVE_DIR/<k>/$NEXTEST_ARCHIVE_NAME` for every k up to `GATE_SHARDS`. A split's +/// later parts run the same binaries as part 1, so their archive is a copy of part 1's. +fn cmd_ci_archive() -> Result<(), String> { + let var = |key: &str| { + std::env::var(key).ok().filter(|v| !v.is_empty()).ok_or_else(|| format!("ci archive: {key} is not set (the gate workflow sets it)")) }; - let (shard, count) = (var("GATE_SHARD")?, var("GATE_SHARDS")?); - let only = shards::warm_only(shard.as_deref(), count.as_deref())?; + let (dir, name) = (PathBuf::from(var("NEXTEST_ARCHIVE_DIR")?), var("NEXTEST_ARCHIVE_NAME")?); + gate_shards("archive")?; + if !has_nextest() { + return Err("ci archive: cargo-nextest is not installed".into()); + } cache_units::record_xtask()?; let checked = shards::run()?; - let (tests, checks) = shards::warm_plan(&checked, only); - let mut steps: Vec<Step> = Vec::new(); - for i in tests { - if let shards::Shard::Tests(runs, _) = checked[i].clone() { - for r in runs { - steps.push(( - "build tests", - Box::new(move || { - let (c, what) = warm_tests(&r); - cache_units::run(c, &what) - }), - )); - } - } - } - if checks { - push_warm_checks(&mut steps); - } - run_steps(&steps) -} - -/// The builds of the checks shard that [`cmd_ci_warm`] runs. -fn push_warm_checks(steps: &mut Vec<Step>) { - steps.push(( - "clippy", - Box::new(|| { - let mut c = cargo(); - c.args(["clippy", "--workspace", "--all-targets", "--keep-going"]); - cache_units::run(c, "cargo clippy --workspace --all-targets --keep-going") - }), - )); - steps.push(( - "no-bundled-fonts", - Box::new(|| { - let mut c = cargo(); - c.args(["test", "-p", "vectorcraft-text", "--no-default-features", "--test", "without_bundled_fonts", "--no-run"]); - cache_units::run(c, "cargo test -p vectorcraft-text --no-default-features --test without_bundled_fonts --no-run")?; - let mut c = cargo(); - c.args(["clippy", "-p", "vectorcraft-ui-egui", "--no-default-features", "--all-targets"]); - cache_units::run(c, "cargo clippy -p vectorcraft-ui-egui --no-default-features --all-targets")?; - let mut c = cargo(); - c.args(["test", "-p", "vectorcraft-ui-egui", "--no-default-features", "--test", "install_fonts", "--no-run"]); - cache_units::run(c, "cargo test -p vectorcraft-ui-egui --no-default-features --test install_fonts --no-run") - }), - )); - steps.push(("wasm", Box::new(cmd_wasm))); -} - -/// The command `ci warm` builds the tests of one run of a test shard with, and its description. -fn warm_tests(r: &shards::Run) -> (Command, String) { let mut c = cargo(); - c.arg("test").args(shards::select(&r.crates)).args(r.targets.args()).arg("--no-run"); - (c, format!("cargo test {} --no-run ({})", r.targets.shown(), shards::names(&r.crates))) + c.args(["test", "--workspace", "--lib", "--bins", "--tests", "--no-run"]); + cache_units::run(c, "cargo test --workspace --lib --bins --tests --no-run")?; + for (i, shard) in checked.iter().enumerate() { + let file = dir.join((i + 1).to_string()).join(&name); + let parent = file.parent().unwrap_or(&dir); + std::fs::create_dir_all(parent).map_err(|e| format!("ci archive: {}: {e}", parent.display()))?; + if let Some(p) = shard.part.filter(|p| !p.is_first()) { + let first = dir.join((i + 2 - p.index).to_string()).join(&name); + std::fs::hard_link(&first, &file) + .or_else(|_| std::fs::copy(&first, &file).map(drop)) + .map_err(|e| format!("ci archive: copy {} to {}: {e}", first.display(), file.display()))?; + eprintln!("ci archive: shard {} runs part {} of shard {}'s archive", i + 1, p.index, i + 2 - p.index); + continue; + } + let filter = shard.filterset(); + let mut c = cargo(); + c.args(["nextest", "archive", "--workspace", "--lib", "--bins", "--tests", "-E", &filter, "--archive-file"]).arg(&file); + run(c, &format!("cargo nextest archive --workspace --lib --bins --tests -E '{filter}' --archive-file {}", file.display()))?; + } + Ok(()) +} + +/// `cargo xtask ci checks`: every `ci` step other than [`TEST_STEPS`], for the shared gate's +/// `lint` leg. +fn cmd_ci_checks() -> Result<(), String> { + run_steps(&ci_steps().into_iter().filter(|(name, _)| !TEST_STEPS.contains(name)).collect::<Vec<_>>()) } /// Runs `steps` in turn, stopping at the first that fails; the summary names the steps that passed @@ -641,20 +645,11 @@ fn i18n_report_packages(select: &[String], shown: &str) -> Result<(), String> { run(c, &format!("cargo test {shown} --lib --bins --tests -- i18n::tests::untranslated_report --exact --nocapture")) } -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn warm_builds_the_test_targets_the_shards_run() { - let a = shards::Member { name: "a".into(), id: "path+file:///w/a#0.1.0".into(), version: "0.1.0".into(), doctests: true }; - let args = |r: &shards::Run| warm_tests(r).0.get_args().map(|a| a.to_string_lossy().into_owned()).collect::<Vec<String>>(); - let all = shards::Run::all(vec![a.clone()]); - assert_eq!(args(&all), ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--tests", "--no-run"]); - assert_eq!(warm_tests(&all).1, "cargo test --lib --bins --tests --no-run (a)"); - let units = shards::Run { targets: shards::Targets::Units, crates: vec![a.clone()] }; - assert_eq!(args(&units), ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--no-run"]); - let integration = shards::Run { targets: shards::Targets::Integration, crates: vec![a] }; - assert_eq!(args(&integration), ["test", "-p", "path+file:///w/a#0.1.0", "--test", "*", "--no-run"]); - } +/// [`cmd_ci_i18n_report`] from the nextest archive `file` of a `ci shard` that tests +/// vectorcraft-ui-egui. +fn i18n_report_archive(file: &Path) -> Result<(), String> { + let mut c = cargo(); + c.args(["nextest", "run", "--archive-file"]).arg(file).arg("--workspace-remap").arg(root()); + c.args(["--no-capture", "-E", "test(=i18n::tests::untranslated_report)"]); + run(c, &format!("cargo nextest run --archive-file {} --no-capture -E 'test(=i18n::tests::untranslated_report)'", file.display())) } diff --git a/xtask/src/shards.rs b/xtask/src/shards.rs index 9bc4469ae4..372d8fbe7d 100644 --- a/xtask/src/shards.rs +++ b/xtask/src/shards.rs @@ -2,10 +2,13 @@ //! gate workflow): which workspace crates each shard tests, and the checks that keep the split //! complete. //! -//! Each test shard builds and runs the tests of its own crates and what they depend on. The last -//! shard runs the `cargo xtask ci` steps that are not tests. [`GROUPS`] names the crates of the -//! first shards; every other workspace member goes to the [`Group::Rest`] shard, so a new crate is -//! tested without a change here. [`check`] fails when a named crate is not a workspace member or +//! In CI the gate's `build` job builds every shard's tests once and writes one nextest archive per +//! shard (`cargo xtask ci archive`, [`Shard::filterset`]), and each shard runs its tests from its +//! archive. Without an archive a shard builds and runs the tests of its own crates and what they +//! depend on. The `cargo xtask ci` steps that are not tests run in the gate's `lint` leg +//! (`cargo xtask ci checks`). [`GROUPS`] names the crates of the first shards; every other +//! workspace member goes to the [`Group::Rest`] shard, so a new crate is tested without a change +//! here. [`check`] fails when a named crate is not a workspace member or //! is named twice, when a group is empty, and when a crate's features in its shard differ from //! its features in `cargo test --workspace`. Cargo resolves features over the packages a command //! selects, so a feature that only another crate's dev-dependencies turn on is off in a shard @@ -37,8 +40,6 @@ pub enum Group { Targets(&'static [(Targets, &'static [&'static str])]), /// The tests of every workspace member no other group names. Rest, - /// The `cargo xtask ci` steps that are not tests. - Checks, } /// The test targets a shard builds and runs for a crate. @@ -71,6 +72,16 @@ impl Targets { Targets::Integration => "--test '*'", } } + + /// The nextest filterset of the test binaries [`Targets::args`] selects among a build of + /// `--lib --bins --tests`: `None` for all of them. + pub fn filterset(self) -> Option<&'static str> { + match self { + Targets::All => None, + Targets::Units => Some("kind(lib) | kind(proc-macro) | kind(bin)"), + Targets::Integration => Some("kind(test)"), + } + } } /// Crates whose tests run on several shards, one [`Group::Part`] each. @@ -120,7 +131,6 @@ pub const GROUPS: &[Group] = &[ (Targets::Integration, &["vectorcraft-engine"]), ]), Group::Rest, - Group::Checks, ]; /// A workspace member, as `cargo metadata` gives it. @@ -139,9 +149,27 @@ pub struct Member { /// What one shard runs, with its crates resolved; a shard of a [`Split`] carries its part. #[derive(Debug, Clone, PartialEq, Eq)] -pub enum Shard { - Tests(Vec<Run>, Option<Part>), - Checks, +pub struct Shard { + pub runs: Vec<Run>, + pub part: Option<Part>, +} + +impl Shard { + /// The nextest filterset of the test binaries this shard runs, among a workspace build of + /// `--lib --bins --tests`: each run's crates (`package(=…)`), with its targets' kinds. + pub fn filterset(&self) -> String { + self.runs + .iter() + .map(|r| { + let packages = r.crates.iter().map(|m| format!("package(={})", m.name)).collect::<Vec<_>>().join(" | "); + match r.targets.filterset() { + None => format!("({packages})"), + Some(kinds) => format!("(({packages}) & ({kinds}))"), + } + }) + .collect::<Vec<_>>() + .join(" | ") + } } /// One test run of a shard: the given targets of these crates. @@ -286,7 +314,7 @@ pub fn assign(groups: &[Group], members: &[Member]) -> Result<Vec<Shard>, String } vec![(Targets::All, split.crates)] } - Group::Rest | Group::Checks => continue, + Group::Rest => continue, }; if lists.iter().all(|(_, names)| names.is_empty()) { return Err(format!("shard {} names no crates ({WHERE})", i + 1)); @@ -326,25 +354,24 @@ pub fn assign(groups: &[Group], members: &[Member]) -> Result<Vec<Shard>, String .iter() .enumerate() .map(|(i, g)| match g { - Group::Targets(lists) => Ok(Shard::Tests( - lists + Group::Targets(lists) => Ok(Shard { + runs: lists .iter() .filter(|(_, names)| !names.is_empty()) .map(|(targets, names)| Run { targets: *targets, crates: pick(&|m| names.contains(&m.name.as_str())) }) .collect(), - None, - )), + part: None, + }), Group::Part(split, index) => { - Ok(Shard::Tests(vec![Run::all(pick(&|m| split.crates.contains(&m.name.as_str())))], Some(Part { split, index: *index }))) + Ok(Shard { runs: vec![Run::all(pick(&|m| split.crates.contains(&m.name.as_str())))], part: Some(Part { split, index: *index }) }) } Group::Rest => { let rest = pick(&|m| !named.contains_key(m.name.as_str())); if rest.is_empty() { return Err(format!("shard {} takes the remaining crates, and there are none ({WHERE})", i + 1)); } - Ok(Shard::Tests(vec![Run::all(rest)], None)) + Ok(Shard { runs: vec![Run::all(rest)], part: None }) } - Group::Checks => Ok(Shard::Checks), }) .collect() } @@ -424,6 +451,13 @@ pub fn describe(runs: &[Run]) -> String { .join(", ") } +/// The shards of this workspace after the checks in [`assign`] alone. A shard that runs its tests +/// from an archive uses it: the archive's build already ran [`check`], and `cargo tree` would +/// first download every dependency. +pub fn assigned() -> Result<Vec<Shard>, String> { + assign(GROUPS, &members(&crate::metadata()?)?) +} + /// The shards of this workspace, after the checks in [`assign`] and [`feature_differences`]. pub fn check() -> Result<Vec<Shard>, String> { // The shared gate runs only the shards that test a crate a pull request reaches, by these @@ -435,11 +469,9 @@ pub fn check() -> Result<Vec<Shard>, String> { let mut differences = Vec::new(); for (i, shard) in shards.iter().enumerate() { // Each run is its own cargo command, so cargo resolves features over that run's crates. - if let Shard::Tests(runs, _) = shard { - for r in runs { - let alone = tree_features(&tree(&select(&r.crates))?, &members); - differences.extend(feature_differences(i + 1, &r.crates, &workspace, &alone)); - } + for r in &shard.runs { + let alone = tree_features(&tree(&select(&r.crates))?, &members); + differences.extend(feature_differences(i + 1, &r.crates, &workspace, &alone)); } } if !differences.is_empty() { @@ -475,7 +507,6 @@ fn workflow_members(workflow: &str) -> Result<(), String> { lists.iter().filter(|(t, _)| *t != Targets::Integration).flat_map(|(_, c)| c.iter().copied()).collect::<Vec<_>>().join(" ") } Group::Rest => "(rest)".to_owned(), - Group::Checks => "(always)".to_owned(), }) .collect(); let found = shard_members(workflow); @@ -491,117 +522,105 @@ fn workflow_members(workflow: &str) -> Result<(), String> { pub fn run() -> Result<Vec<Shard>, String> { let shards = check()?; for (i, shard) in shards.iter().enumerate() { - match shard { - Shard::Tests(runs, part) => { - let share = part.map(|p| format!(", part {} of {}", p.index, p.split.parts())).unwrap_or_default(); - println!("shard {}/{}: tests of {}{share}", i + 1, shards.len(), describe(runs)) - } - Shard::Checks => println!("shard {}/{}: the other ci steps", i + 1, shards.len()), - } + let share = shard.part.map(|p| format!(", part {} of {}", p.index, p.split.parts())).unwrap_or_default(); + println!("shard {}/{}: tests of {}{share}", i + 1, shards.len(), describe(&shard.runs)) } println!("OK: every workspace member is tested on one shard, with the features `cargo test --workspace` gives it."); Ok(shards) } -/// The shard `cargo xtask ci warm` builds alone, as an index into [`GROUPS`], from the gate's -/// `GATE_SHARD` and `GATE_SHARDS`: `None` (every shard) when neither is set. Setting only one, -/// a value that is not a number, a count other than the number of shards, or a shard out of range -/// is an error. -pub fn warm_only(shard: Option<&str>, count: Option<&str>) -> Result<Option<usize>, String> { - let (shard, count) = match (shard, count) { - (None, None) => return Ok(None), - (Some(shard), Some(count)) => (shard, count), - _ => return Err("ci warm: GATE_SHARD and GATE_SHARDS are set together or not at all".into()), - }; - let number = - |key: &str, value: &str| -> Result<usize, String> { value.trim().parse().map_err(|_| format!("ci warm: {key} is `{value}`, not a number")) }; - let (shard, count) = (number("GATE_SHARD", shard)?, number("GATE_SHARDS", count)?); - if count != GROUPS.len() { - return Err(format!( - "ci warm: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)", - GROUPS.len() - )); - } - if !(1..=count).contains(&shard) { - return Err(format!("ci warm: GATE_SHARD is {shard}, not 1 to {count}")); - } - Ok(Some(shard - 1)) -} - -/// What `cargo xtask ci warm` builds of `shards`: the indices of the test shards whose tests it -/// builds, and whether it runs the checks shard's builds. With `only` (from [`warm_only`]) it -/// builds that shard alone, and without it every shard. A split's later parts build nothing: they -/// build the same tests as part 1, whose leg puts them in the cache. -pub fn warm_plan(shards: &[Shard], only: Option<usize>) -> (Vec<usize>, bool) { - let mut tests = Vec::new(); - let mut checks = false; - for (i, shard) in shards.iter().enumerate() { - if only.is_some_and(|k| k != i) { - continue; - } - match shard { - Shard::Checks => checks = true, - Shard::Tests(_, part) if part.is_some_and(|p| !p.is_first()) => {} - Shard::Tests(..) => tests.push(i), - } - } - (tests, checks) -} - #[cfg(test)] mod tests { use super::*; - #[test] - fn warm_builds_every_shard_unless_the_gate_names_one() { - let n = GROUPS.len().to_string(); - assert_eq!(warm_only(None, None), Ok(None)); - assert_eq!(warm_only(Some("1"), Some(&n)), Ok(Some(0))); - assert_eq!(warm_only(Some(&n), Some(&n)), Ok(Some(GROUPS.len() - 1))); - for (shard, count) in [(Some("1"), None), (None, Some(n.as_str())), (Some("0"), Some(n.as_str())), (Some("x"), Some(n.as_str()))] { - assert!(warm_only(shard, count).is_err(), "{shard:?} of {count:?}"); + /// Whether the filterset `expr` (`package(=…)` and `kind(…)` terms joined by `|` and `&`, with + /// parentheses) matches a test binary of `package` whose kind is `kind`, as nextest reads + /// those terms: `&` binds tighter than `|`. + fn matches(expr: &str, package: &str, kind: &str) -> bool { + fn any(s: &mut &str, package: &str, kind: &str) -> bool { + let mut found = all(s, package, kind); + while let Some(rest) = s.trim_start().strip_prefix('|') { + *s = rest; + found |= all(s, package, kind); + } + found } - let past = (GROUPS.len() + 1).to_string(); - assert!(warm_only(Some(&past), Some(&n)).is_err()); - assert!(warm_only(Some("1"), Some(&past)).is_err()); + fn all(s: &mut &str, package: &str, kind: &str) -> bool { + let mut found = term(s, package, kind); + while let Some(rest) = s.trim_start().strip_prefix('&') { + *s = rest; + found &= term(s, package, kind); + } + found + } + fn term(s: &mut &str, package: &str, kind: &str) -> bool { + *s = s.trim_start(); + if let Some(rest) = s.strip_prefix('(') { + *s = rest; + let found = any(s, package, kind); + *s = s.trim_start().strip_prefix(')').unwrap_or_else(|| panic!("no `)` before `{s}`")); + return found; + } + let (call, rest) = s.split_once(')').unwrap_or_else(|| panic!("no `)` in `{s}`")); + *s = rest; + match call.split_once('(') { + Some(("package", name)) => name.strip_prefix('=') == Some(package), + Some(("kind", k)) => k == kind, + _ => panic!("unknown term `{call})`"), + } + } + let mut s = expr; + let found = any(&mut s, package, kind); + assert!(s.trim().is_empty(), "`{s}` left over in `{expr}`"); + found } #[test] - fn warm_builds_each_shard_of_the_plan() { - let ws = [m("a"), m("b")]; - let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap(); - assert_eq!(warm_plan(&shards, None), (vec![0, 2], true)); - assert_eq!(warm_plan(&shards, Some(0)), (vec![0], false)); - assert_eq!(warm_plan(&shards, Some(1)), (vec![], false)); - assert_eq!(warm_plan(&shards, Some(2)), (vec![2], false)); - assert_eq!(warm_plan(&shards, Some(3)), (vec![], true)); - // The real plan: every leg the gate names builds its own shard (a split's later part - // builds nothing), and the legs together, like a full warm, build every crate's tests - // once and the checks. - let real = assign(GROUPS, &members(&crate::metadata().unwrap()).unwrap()).unwrap(); - let mut owned: Vec<&str> = real.iter().flat_map(owners).map(|(name, _)| name).collect(); - owned.sort_unstable(); - let (mut legs, mut leg_checks) = (Vec::new(), 0); - for i in 0..GROUPS.len() { - let n = GROUPS.len().to_string(); - let only = warm_only(Some(&(i + 1).to_string()), Some(&n)).unwrap(); - let (tests, checks) = warm_plan(&real, only); - let want = match &real[i] { - Shard::Checks => (vec![], true), - Shard::Tests(_, Some(p)) if !p.is_first() => (vec![], false), - Shard::Tests(..) => (vec![i], false), - }; - assert_eq!((tests.clone(), checks), want, "shard {}", i + 1); - legs.extend(tests); - leg_checks += usize::from(checks); + fn a_shard_s_archive_holds_the_test_binaries_of_its_runs() { + let units = Shard { runs: vec![Run { targets: Targets::Units, crates: vec![m("a")] }], part: None }; + let other = Shard { runs: vec![Run::all(vec![m("b"), m("c")]), Run { targets: Targets::Integration, crates: vec![m("a")] }], part: None }; + let (units, other) = (units.filterset(), other.filterset()); + for kind in ["lib", "proc-macro", "bin"] { + assert!(matches(&units, "a", kind) && !matches(&other, "a", kind), "a {kind}"); + } + assert!(!matches(&units, "a", "test") && matches(&other, "a", "test")); + for (package, kind) in [("b", "lib"), ("b", "test"), ("c", "bin")] { + assert!(matches(&other, package, kind) && !matches(&units, package, kind), "{package} {kind}"); + } + assert!(!matches(&other, "d", "lib")); + // In this workspace each test binary is in the archive of one shard, and a split's later + // parts take part 1's archive. + let meta = crate::metadata().unwrap(); + let ws = members(&meta).unwrap(); + let real = assign(GROUPS, &ws).unwrap(); + let mut binaries = 0; + for p in meta["packages"].as_array().unwrap().iter().filter(|p| ws.iter().any(|m| p["id"] == m.id.as_str())) { + let name = p["name"].as_str().unwrap(); + for target in p["targets"].as_array().unwrap().iter().filter(|t| t["test"] != false) { + let kinds: Vec<&str> = target["kind"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + let kind = if kinds.contains(&"proc-macro") { + "proc-macro" + } else if kinds.iter().any(|k| k.ends_with("lib")) { + "lib" + } else if let [k @ ("bin" | "test")] = kinds.as_slice() { + k + } else { + continue; + }; + binaries += 1; + let owners: Vec<usize> = (0..real.len()) + .filter(|&i| real[i].part.is_none_or(|p| p.is_first()) && matches(&real[i].filterset(), name, kind)) + .map(|i| i + 1) + .collect(); + assert_eq!(owners.len(), 1, "{name}'s {kind} test binary is in the archive of shards {owners:?}"); + } + } + assert!(binaries > ws.len(), "{binaries} test binaries for {} members", ws.len()); + for (i, shard) in real.iter().enumerate() { + if let Some(p) = shard.part.filter(|p| !p.is_first()) { + assert_eq!(shard.filterset(), real[i + 1 - p.index].filterset(), "shard {}", i + 1); + } } - let (tests, checks) = warm_plan(&real, None); - assert!(checks); - assert_eq!(leg_checks, 1); - assert_eq!(tests, legs); - let mut built: Vec<&str> = tests.iter().flat_map(|&i| crates(&real[i])).collect(); - built.sort_unstable(); - assert_eq!(built, owned); } fn m(name: &str) -> Member { @@ -626,20 +645,16 @@ mod tests { } fn crates(shard: &Shard) -> Vec<&str> { - match shard { - Shard::Tests(runs, _) => runs.iter().flat_map(|r| r.crates.iter().map(|m| m.name.as_str())).collect(), - Shard::Checks => Vec::new(), - } + shard.runs.iter().flat_map(|r| r.crates.iter().map(|m| m.name.as_str())).collect() } /// Each crate a shard tests from the start, with the targets it runs: a part after the first /// runs a share of the same tests, so it is counted with part 1. fn owners(shard: &Shard) -> Vec<(&str, Targets)> { - match shard { - Shard::Tests(_, Some(p)) if !p.is_first() => Vec::new(), - Shard::Tests(runs, _) => runs.iter().flat_map(|r| r.crates.iter().map(|m| (m.name.as_str(), r.targets))).collect(), - Shard::Checks => Vec::new(), + if shard.part.is_some_and(|p| !p.is_first()) { + return Vec::new(); } + shard.runs.iter().flat_map(|r| r.crates.iter().map(|m| (m.name.as_str(), r.targets))).collect() } /// The tests (binary ids and full names, in the order nextest lists them) that one `cargo nextest run` with @@ -685,9 +700,9 @@ mod tests { #[test] fn a_split_runs_on_its_parts_in_a_row() { let ws = [m("a"), m("b")]; - let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap(); - assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["a"], vec!["a"], vec!["b"], vec![]]); - assert_eq!(shards[1], Shard::Tests(vec![Run::all(vec![m("a")])], Some(Part { split: &SPLIT, index: 2 }))); + let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest], &ws).unwrap(); + assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["a"], vec!["a"], vec!["b"]]); + assert_eq!(shards[1], Shard { runs: vec![Run::all(vec![m("a")])], part: Some(Part { split: &SPLIT, index: 2 }) }); let apart = assign(&[Group::Part(&SPLIT, 1), Group::Rest, Group::Part(&SPLIT, 2)], &ws).unwrap_err(); assert!(apart.contains("not shards 1 to 2 in a row"), "{apart}"); let missing = assign(&[Group::Part(&SPLIT, 2), Group::Rest], &ws).unwrap_err(); @@ -755,9 +770,8 @@ mod tests { #[test] fn the_rest_shard_takes_every_crate_no_group_names() { let ws = [m("a"), m("b"), m("c"), m("d")]; - let shards = assign(&[Group::Targets(&[(Targets::All, &["c"])]), Group::Rest, Group::Checks], &ws).unwrap(); - assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["c"], vec!["a", "b", "d"], vec![]]); - assert_eq!(shards[2], Shard::Checks); + let shards = assign(&[Group::Targets(&[(Targets::All, &["c"])]), Group::Rest], &ws).unwrap(); + assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["c"], vec!["a", "b", "d"]]); } /// Every test target of `a`. @@ -768,18 +782,11 @@ mod tests { #[test] fn a_crate_s_units_and_integration_tests_run_on_two_shards() { let ws = [m("a"), m("b"), m("c")]; - let shards = - assign(&[Group::Targets(&[UNITS]), Group::Targets(&[(Targets::All, &["b"]), INTEGRATION]), Group::Rest, Group::Checks], &ws).unwrap(); - assert_eq!(shards[0], Shard::Tests(vec![Run { targets: Targets::Units, crates: vec![m("a")] }], None)); - assert_eq!(shards[1], Shard::Tests(vec![Run::all(vec![m("b")]), Run { targets: Targets::Integration, crates: vec![m("a")] }], None)); + let shards = assign(&[Group::Targets(&[UNITS]), Group::Targets(&[(Targets::All, &["b"]), INTEGRATION]), Group::Rest], &ws).unwrap(); + assert_eq!(shards[0], Shard { runs: vec![Run { targets: Targets::Units, crates: vec![m("a")] }], part: None }); + assert_eq!(shards[1], Shard { runs: vec![Run::all(vec![m("b")]), Run { targets: Targets::Integration, crates: vec![m("a")] }], part: None }); assert_eq!(crates(&shards[2]), ["c"]); - assert_eq!( - unit_crates(match &shards[1] { - Shard::Tests(r, _) => r, - Shard::Checks => panic!("shard 2 is a test shard"), - }), - [m("b")] - ); + assert_eq!(unit_crates(&shards[1].runs), [m("b")]); let half = assign(&[Group::Targets(&[UNITS]), Group::Rest], &ws).unwrap_err(); assert!(half.contains("no shard runs its integration tests"), "{half}"); let other_half = assign(&[Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err(); @@ -833,7 +840,6 @@ mod tests { "`{name}` runs {targets:?}, not each test target once" ); } - assert_eq!(shards.iter().filter(|s| **s == Shard::Checks).count(), 1); } #[test] From cf866c82d56c43264da6a20fbcea0b3085189e93 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 20:27:26 -0800 Subject: [PATCH 63/88] CI: the build job's cache entry leaves out the integration test executables The build job recorded every unit of `cargo test --workspace --lib --bins --tests --no-run` for the cache trim, so the rolling entry would hold the integration tests' executables. With them the entry measured 10.3 to 10.5 GB, above the repository's 10 GB cache budget, which is why `cargo xtask ci warm` stopped building them. The library and binary tests' build now records the units, and the integration tests build afterwards without a record. The saved entry keeps every dependency and dev-dependency the tests build with. --- xtask/src/main.rs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index cefae8c6a6..6e2d03166c 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -457,10 +457,14 @@ fn cmd_ci_shard() -> Result<(), String> { /// `cargo xtask ci archive`: the shared gate's `build` job (`archive-command` with /// `shard-archives`). After the shard checks it builds every shard's tests in one workspace build, -/// which records its units in a leg that saves the cache, then writes the test binaries of shard -/// k (1-based, [`shards::Shard::filterset`]) to the nextest archive -/// `$NEXTEST_ARCHIVE_DIR/<k>/$NEXTEST_ARCHIVE_NAME` for every k up to `GATE_SHARDS`. A split's -/// later parts run the same binaries as part 1, so their archive is a copy of part 1's. +/// then writes the test binaries of shard k (1-based, [`shards::Shard::filterset`]) to the nextest +/// archive `$NEXTEST_ARCHIVE_DIR/<k>/$NEXTEST_ARCHIVE_NAME` for every k up to `GATE_SHARDS`. A +/// split's later parts run the same binaries as part 1, so their archive is a copy of part 1's. +/// +/// In a leg that saves the cache, the library and binary tests' build records its units in +/// `CRAFT_CACHE_UNITS` (xtask/src/cache_units.rs), xtask's own build included, and the +/// integration tests' build does not, so the saved entry holds every dependency and +/// dev-dependency the tests build with and none of the integration tests' executables. fn cmd_ci_archive() -> Result<(), String> { let var = |key: &str| { std::env::var(key).ok().filter(|v| !v.is_empty()).ok_or_else(|| format!("ci archive: {key} is not set (the gate workflow sets it)")) @@ -473,8 +477,11 @@ fn cmd_ci_archive() -> Result<(), String> { cache_units::record_xtask()?; let checked = shards::run()?; let mut c = cargo(); + c.args(["test", "--workspace", "--lib", "--bins", "--no-run"]); + cache_units::run(c, "cargo test --workspace --lib --bins --no-run")?; + let mut c = cargo(); c.args(["test", "--workspace", "--lib", "--bins", "--tests", "--no-run"]); - cache_units::run(c, "cargo test --workspace --lib --bins --tests --no-run")?; + run(c, "cargo test --workspace --lib --bins --tests --no-run")?; for (i, shard) in checked.iter().enumerate() { let file = dir.join((i + 1).to_string()).join(&name); let parent = file.parent().unwrap_or(&dir); From 787c489cfc888e597a5bfa98c168c1fa07af44ec Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 20:33:00 -0800 Subject: [PATCH 64/88] DXF/DWG import: pattern hatches keep their pattern and gradient hatches their gradient Pattern hatches came in as their boundary outlines, and gradient hatches were filled with their first color. - A pattern hatch now draws its pattern lines (groups 53, 43 to 46 and 49): each family's lines clipped to the boundary (even-odd, as solid hatches fill), cut into dashes and dots that start from each line's base point, and stroked at the hatch's lineweight without its linetype. Dots get round caps. A user-defined double hatch (group 77) with one family gets the perpendicular family too. - A gradient hatch (groups 450 to 470) is filled with a linear or radial gradient at its angle across the boundary, in its two colors or one color shaded or tinted (452, 462); the shift (461) moves the center up and left. The named gradients map to linear and radial ones by VectorCraft's own rule (hatch.rs). Gradient colors "by block" or "by layer" on layer 0 resolve through the insert, and a block holding one becomes a symbol per look. - A pattern hatch without usable pattern lines, with more than 20,000 dashes, or past the drawing's budget of 2,000,000 dashes or 200,000,000 clipping steps still comes in as its boundary, with a warning. Docs: docs/mcp.md (DXF import), docs/file-format-parity.md (DXF row). --- crates/cad/src/import.rs | 7 +- crates/cad/src/import/build.rs | 68 +++- crates/cad/src/import/entity.rs | 71 +++- crates/cad/src/import/hatch.rs | 563 ++++++++++++++++++++++++++++++++ crates/cad/src/import/tests.rs | 171 +++++++++- docs/file-format-parity.md | 2 +- docs/mcp.md | 8 +- 7 files changed, 866 insertions(+), 24 deletions(-) create mode 100644 crates/cad/src/import/hatch.rs diff --git a/crates/cad/src/import.rs b/crates/cad/src/import.rs index 5a5582efe1..2f1fd93467 100644 --- a/crates/cad/src/import.rs +++ b/crates/cad/src/import.rs @@ -5,8 +5,9 @@ //! drawing units; by default the drawing's own unit at 1:1) or fitted to an artboard, centred //! or with the drawing's origin on the artboard's bottom-left corner. Each DXF layer holding art //! becomes a layer (hidden, frozen, locked and non-plotting layers keep that), or all art goes on -//! one. Lines, polylines with arc segments, circles, arcs, ellipses, splines (NURBS), solid -//! hatches and solids become paths; text and multiline text point type; named blocks symbols +//! one. Lines, polylines with arc segments, circles, arcs, ellipses, splines (NURBS), solid and +//! gradient hatches, pattern hatches' lines and solids become paths; text and multiline text +//! point type; named blocks symbols //! (anonymous ones, such as dimensions, groups of their art). Colours (indexed and true colour), //! lineweights, linetypes and transparency come through layers and blocks as CAD apps resolve //! them. What can't come in is listed in the warnings. @@ -15,12 +16,14 @@ //! blocks and layouts. //! - `entity`: entities to items (geometry and properties). //! - `curve`: bulges, arcs, ellipses and NURBS as Bézier paths. +//! - `hatch`: pattern hatches' lines and gradient hatches' fills. //! - `text`: text values to plain text. //! - `build`: items to the document. mod build; mod curve; mod entity; +mod hatch; mod reader; mod text; diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 4e1bed4ae1..9ddd1944db 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -8,12 +8,13 @@ use std::rc::Rc; use std::sync::Arc; use kurbo::BezPath; -use vectorcraft_color::{Color, Paint}; +use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Dash, Document, LAYER_COLORS, LayerColor, LineCap, Node, NodeKind, Symbol, TextObject}; use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect}; use super::ImportOptions; -use super::entity::{Alpha, Col, Converter, Geom, InsertItem, Item, Lw, Props, Span, TextItem}; +use super::entity::{Alpha, Col, Converter, Geom, InsertItem, Item, Lw, Props, Shade, Span, TextItem}; +use super::hatch::{Grad, Second}; use super::reader::{Drawing, LayoutDef}; use crate::{CAP_HEIGHT, MAX_NEST}; @@ -47,6 +48,19 @@ const TOO_MUCH_BLOCK_WORK: &str = "the drawing's blocks take too much work to pl const TOO_MANY_DASHES: &str = "the drawing has more dashed lines than can be kept: the rest are drawn solid"; const TOO_MUCH_TEXT: &str = "the drawing has more than 64 MB of text and block names: the rest are left out"; +/// How a path paints. +#[derive(Clone, Copy)] +enum Look<'g> { + /// Stroked at its width or lineweight, in its linetype. + Line, + /// Filled with its color. + Fill, + /// Filled with a gradient hatch's gradient. + Gradient(&'g Grad), + /// Pattern hatch lines: stroked without the linetype; `dots` take round caps. + Pattern { dots: bool }, +} + /// What a block's art takes from the insert that places it: its colour, lineweight, linetype /// and opacity where the art says "by block", and its layer for art on layer 0. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] @@ -291,7 +305,7 @@ impl<'d, 'a> Build<'d, 'a> { /// An item's bounds in world coordinates (type: an estimate from its height and length). fn item_bounds(&mut self, it: &Item, depth: u32) -> Option<Rect> { match &it.geom { - Geom::Path { bp, .. } => super::curve::bounds(bp), + Geom::Path { bp, .. } | Geom::Shaded { bp, .. } => super::curve::bounds(bp), Geom::Text(t) => { let lines = t.text.lines().count().max(1) as f64; let longest = t.text.lines().map(|l| l.chars().count()).max().unwrap_or(0) as f64; @@ -333,6 +347,10 @@ impl<'d, 'a> Build<'d, 'a> { let on_zero = p.layer == "0"; s |= p.color == Col::ByBlock || p.lineweight == Lw::ByBlock || p.linetype == "BYBLOCK" || p.alpha == Alpha::ByBlock; s |= on_zero && (p.color == Col::ByLayer || p.lineweight == Lw::ByLayer || p.linetype == "BYLAYER"); + if let Geom::Shaded { shade: Shade::Gradient(g), .. } = &it.geom { + let inherited = |c| c == Col::ByBlock || (on_zero && c == Col::ByLayer); + s |= inherited(g.first) || matches!(g.second, Second::Col(c) if inherited(c)); + } if let Geom::Insert(ins) = &it.geom { s |= !ins.attribs.is_empty() || self.is_sensitive(&ins.block, depth + 1); } @@ -391,6 +409,23 @@ impl<'d, 'a> Build<'d, 'a> { } } + /// Gradient `g` as paint, placed by `map`; its colors resolved as the hatch's own would be. + fn gradient(&self, g: &Grad, p: &Props, map: Affine, inh: &Inherit) -> Paint { + let rgb = |c: Col| self.rgb(&Props { color: c, ..p.clone() }, inh); + let first = rgb(g.first); + let second = match g.second { + Second::Col(c) => rgb(c), + Second::Tint(t) => Grad::tinted(first, t), + }; + let stops = g.stops.iter().map(|(at, two)| GradientStop::new(*at, rgb_color(if *two { second } else { first }))).collect(); + let mut geom = g.geom; + geom.transform(map, g.kind); + let mut paint = GradientPaint::new(Gradient::new(g.kind, stops)); + paint.angle = geom.angle_deg(); + paint.geom = Some(geom); + Paint::Gradient(Box::new(paint)) + } + /// What a block placed by an insert with `p` inherits. fn inherit(&self, p: &Props, inh: &Inherit) -> Inherit { Inherit { @@ -479,7 +514,9 @@ impl<'d, 'a> Build<'d, 'a> { return None; } let mut node = match &it.geom { - Geom::Path { bp, fill, width } => self.path(bp, *fill, *width, &it.props, map, inh)?, + Geom::Path { bp, fill, width } => self.path(bp, if *fill { Look::Fill } else { Look::Line }, *width, &it.props, map, inh)?, + Geom::Shaded { bp, shade: Shade::Gradient(g) } => self.path(bp, Look::Gradient(g), 0.0, &it.props, map, inh)?, + Geom::Shaded { bp, shade: Shade::Pattern { dots } } => self.path(bp, Look::Pattern { dots: *dots }, 0.0, &it.props, map, inh)?, Geom::Text(t) => self.text(t, &it.props, map, inh)?, Geom::Insert(ins) => return self.insert(ins, &it.props, map, inh, depth), }; @@ -488,7 +525,10 @@ impl<'d, 'a> Build<'d, 'a> { Some(node) } - fn path(&mut self, bp: &BezPath, fill: bool, width: f64, p: &Props, map: Affine, inh: &Inherit) -> Option<Node> { + /// A path painted as `look` says; `width`: a line's width in drawing units (0: the + /// lineweight). + fn path(&mut self, bp: &BezPath, look: Look<'_>, width: f64, p: &Props, map: Affine, inh: &Inherit) -> Option<Node> { + let fill = matches!(look, Look::Fill | Look::Gradient(_)); let n = bp.elements().len(); if self.elements.saturating_add(n) > MAX_ELEMENTS { self.warn(TOO_MANY_POINTS); @@ -498,7 +538,14 @@ impl<'d, 'a> Build<'d, 'a> { let mut bp = bp.clone(); bp.apply_affine(map); super::curve::bounds(&bp)?; - let paint = Paint::solid(rgb_color(self.rgb(p, inh))); + let paint = match look { + Look::Gradient(g) => self.gradient(g, p, map, inh), + _ => Paint::solid(rgb_color(self.rgb(p, inh))), + }; + let pattern = match look { + Look::Pattern { dots } => Some(dots), + _ => None, + }; let scale = map.determinant().abs().sqrt(); let path = PathData::from_bezpath(&bp); // A compound path's loops each keep a copy of its appearance, beside its own. @@ -515,7 +562,14 @@ impl<'d, 'a> Build<'d, 'a> { f64::from(lw) / 100.0 * PT_PER_MM * self.lw_scale }; let mut ap = Appearance::basic(Paint::None, paint, w); - if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut() + // Pattern lines carry their own dashes; dots of no length show with round caps. + if let Some(dots) = pattern { + if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut() + && dots + { + s.cap = LineCap::Round; + } + } else if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut() && let Some((dash, dots)) = self.dash(&self.linetype(p, inh), p, scale) { match dash.pattern.len().checked_mul(copies).and_then(|v| self.dash_values.checked_add(v)).filter(|n| *n <= MAX_DASH_VALUES) { diff --git a/crates/cad/src/import/entity.rs b/crates/cad/src/import/entity.rs index 9d147b08cf..3538920f1d 100644 --- a/crates/cad/src/import/entity.rs +++ b/crates/cad/src/import/entity.rs @@ -10,6 +10,7 @@ use vectorcraft_geom::{Affine, Point, Vec2}; use craft_dxf::model::{self, EntityRecord, Groups, HatchEdge, HatchPath}; use super::curve::{self, Vertex}; +use super::hatch::{self, Grad, NoPattern}; use super::reader::{aci_paper, point}; /// How far below the baseline the lowest descender reaches, as a fraction of the cap height. @@ -155,10 +156,25 @@ pub(crate) enum Geom { fill: bool, width: f64, }, + /// A hatch filled with a gradient, or a pattern hatch's lines (`bp`, world coordinates). + Shaded { + bp: BezPath, + shade: Shade, + }, Text(TextItem), Insert(InsertItem), } +/// How a [`Geom::Shaded`] path paints. +#[derive(Clone, Debug)] +pub(crate) enum Shade { + /// The area filled with a gradient. + Gradient(Box<Grad>), + /// Pattern lines, stroked at the lineweight without a linetype; `dots`: some pieces have no + /// length and need round caps to show. + Pattern { dots: bool }, +} + /// An entity as art: its geometry and its properties. #[derive(Clone, Debug)] pub(crate) struct Item { @@ -174,10 +190,14 @@ pub(crate) struct Converter { pub warnings: Vec<String>, /// Array insert copies made so far, against [`MAX_TOTAL_CELLS`]. cells: i64, + /// The pattern budget shared by entity sections and blocks. + patterns: hatch::Budget, } -const PATTERN_HATCH: &str = "pattern hatches come in as their boundaries"; -const GRADIENT_HATCH: &str = "gradient hatches are filled with their first colour"; +const PATTERN_HATCH: &str = "pattern hatches without usable pattern lines come in as their boundaries"; +const DENSE_PATTERN: &str = "pattern hatches of more than 20,000 dashes come in as their boundaries"; +const MANY_PATTERNS: &str = "the drawing's pattern hatches have more than 2,000,000 dashes in all: the rest come in as their boundaries"; +const MUCH_PATTERN_WORK: &str = "the drawing's pattern hatches take too much work to clip: the rest come in as their boundaries"; const MESH_VERTICES: &str = "polygon meshes and polyface mesh faces whose vertices are missing are left out"; const BIG_ARRAY: &str = "array inserts are limited to 10,000 copies each"; const MANY_ARRAYS: &str = "array inserts are limited to 2,000,000 copies in all"; @@ -247,7 +267,7 @@ impl Converter { face(&mut bp, &corners); (!bp.elements().is_empty()).then_some(bp).and_then(path) } - model::EntityKind::Hatch(h) => self.hatch(h, ocs), + model::EntityKind::Hatch(h) => self.hatch(h, ocs, Props::read(&m.common).color), model::EntityKind::Text(t) => text(t, &g, false, ocs).map(Geom::Text), model::EntityKind::MText(t) => mtext(t, e.tags).map(Geom::Text), model::EntityKind::Insert(ins) => self.insert(ins, &e.followers, ocs), @@ -378,7 +398,8 @@ impl Converter { out } - fn hatch(&mut self, h: &model::Hatch, ocs: Affine) -> Option<Geom> { + /// A hatch's art; `own`: its color, which a gradient without color records takes. + fn hatch(&mut self, h: &model::Hatch, ocs: Affine, own: Col) -> Option<Geom> { let mut bp = BezPath::new(); for l in &h.loops { let Some(path) = boundary(&l.path) else { break }; @@ -387,14 +408,38 @@ impl Converter { if bp.elements().is_empty() { return None; } - let bp = transformed(bp, ocs); - if h.gradient.is_some() { - self.warn(GRADIENT_HATCH); - } else if !h.solid { - self.warn(PATTERN_HATCH); - return Some(Geom::Path { bp, fill: false, width: 0.0 }); + if let Some(g) = &h.gradient { + let shade = hatch::gradient(g, &bp, ocs, own).map(|g| Shade::Gradient(Box::new(g))); + let bp = transformed(bp, ocs); + return Some(match shade { + Some(shade) => Geom::Shaded { bp, shade }, + None => Geom::Path { bp, fill: true, width: 0.0 }, + }); + } + if h.solid { + return Some(Geom::Path { bp: transformed(bp, ocs), fill: true, width: 0.0 }); + } + // The pattern lines are in the hatch's plane, as its boundary is. + let doubled; + let lines = if h.pattern_type == 0 && h.double && h.pattern_lines.len() == 1 { + doubled = hatch::doubled(&h.pattern_lines); + &doubled + } else { + &h.pattern_lines + }; + match hatch::pattern(lines, &bp, &mut self.patterns) { + Ok((lines, _)) if lines.elements().is_empty() => None, + Ok((lines, dots)) => Some(Geom::Shaded { bp: transformed(lines, ocs), shade: Shade::Pattern { dots } }), + Err(why) => { + self.warn(match why { + NoPattern::Undefined => PATTERN_HATCH, + NoPattern::TooDense => DENSE_PATTERN, + NoPattern::DrawingPieces => MANY_PATTERNS, + NoPattern::DrawingWork => MUCH_PATTERN_WORK, + }); + Some(Geom::Path { bp: transformed(bp, ocs), fill: false, width: 0.0 }) + } } - Some(Geom::Path { bp, fill: true, width: 0.0 }) } } @@ -406,6 +451,10 @@ fn in_range(g: &Geom) -> bool { Geom::Path { bp, width, .. } => { curve::bounds(bp).is_some_and(|b| near(Point::new(b.x0, b.y0)) && near(Point::new(b.x1, b.y1))) && *width <= MAX_COORD } + Geom::Shaded { bp, shade } => { + let far = matches!(shade, Shade::Gradient(g) if !near(g.geom.start) || !near(g.geom.end) || !g.geom.aspect.is_finite()); + !far && curve::bounds(bp).is_some_and(|b| near(Point::new(b.x0, b.y0)) && near(Point::new(b.x1, b.y1))) + } Geom::Text(t) => origin(&t.xf) && t.height <= MAX_COORD, Geom::Insert(i) => i.cells.iter().all(|m| origin(m) && m.as_coeffs().iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)), } diff --git a/crates/cad/src/import/hatch.rs b/crates/cad/src/import/hatch.rs new file mode 100644 index 0000000000..506f595ba0 --- /dev/null +++ b/crates/cad/src/import/hatch.rs @@ -0,0 +1,563 @@ +//! Hatch fills other than solid: a pattern hatch's line families clipped to its boundary and cut +//! into their dashes, and a gradient hatch's colors and placement. Both work in the hatch's own +//! plane (its object coordinate system), where the boundary and the pattern lines are given. + +use kurbo::{BezPath, PathEl}; +use vectorcraft_color::{GradientGeom, GradientKind}; +use vectorcraft_geom::{Affine, Point, Vec2}; + +use craft_dxf::model::{self, PatternLine}; + +use super::entity::Col; +use super::reader::aci_paper; + +/// The most dashes and dots one pattern hatch draws. +pub(crate) const MAX_PIECES: usize = 20_000; +/// The most boundary edges a pattern hatch is clipped against, once its curves are flattened. +const MAX_EDGES: usize = 200_000; +/// The most work one pattern hatch does: each pattern line drawn costs one step per boundary +/// edge, and each dash, gap or dot looked at one more. +const MAX_WORK: usize = 20_000_000; +/// The most dashes and dots all pattern hatches draw together. +pub(crate) const MAX_TOTAL_PIECES: usize = if cfg!(test) { 1_000 } else { 2_000_000 }; +/// The most clipping and dash steps all pattern hatches take together. +pub(crate) const MAX_TOTAL_WORK: usize = if cfg!(test) { 200_000 } else { 200_000_000 }; +/// How far flattened boundary curves may stray, as a fraction of the boundary's larger side. +const FLATNESS: f64 = 1e-4; +/// Lengths below this fraction of the boundary's larger side count as none. +const TINY: f64 = 1e-9; + +/// Why a pattern hatch is not drawn as its pattern. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum NoPattern { + /// The hatch holds no pattern lines. + Undefined, + /// Drawing it would take more than [`MAX_PIECES`] pieces or [`MAX_WORK`] steps. + TooDense, + /// The drawing reaches its total piece limit. + DrawingPieces, + /// The drawing reaches its total work limit. + DrawingWork, +} + +/// The remaining pattern budget; discarded patterns also use it. +pub(crate) struct Budget { + pieces: usize, + work: usize, + stopped: Option<NoPattern>, +} + +impl Default for Budget { + fn default() -> Self { + Self { pieces: MAX_TOTAL_PIECES, work: MAX_TOTAL_WORK, stopped: None } + } +} + +impl Budget { + fn piece(&mut self, pieces: &mut usize) -> Result<(), NoPattern> { + if *pieces >= MAX_PIECES { + return Err(NoPattern::TooDense); + } + if self.pieces == 0 { + self.stopped = Some(NoPattern::DrawingPieces); + return Err(NoPattern::DrawingPieces); + } + *pieces += 1; + self.pieces -= 1; + Ok(()) + } + + fn work(&mut self, work: &mut usize, steps: usize) -> Result<(), NoPattern> { + if steps > MAX_WORK - *work { + return Err(NoPattern::TooDense); + } + if steps > self.work { + self.stopped = Some(NoPattern::DrawingWork); + return Err(NoPattern::DrawingWork); + } + *work += steps; + self.work -= steps; + Ok(()) + } +} + +/// Adds a perpendicular family when the pattern holds only one family. +pub(crate) fn doubled(lines: &[PatternLine]) -> Vec<PatternLine> { + let mut out = lines.to_vec(); + if let [line] = lines { + out.push(PatternLine { angle: line.angle + 90.0, base: line.base, offset: [-line.offset[1], line.offset[0]], dashes: line.dashes.clone() }); + } + out +} + +/// A pattern hatch's lines inside `boundary` (closed loops; even-odd, as solid hatches fill): +/// each family's lines, cut into dashes and dots that start from the line's own base point. +/// `Ok` holds the pieces (empty when no line crosses the area) and whether any of them is a dot. +pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Budget) -> Result<(BezPath, bool), NoPattern> { + if lines.is_empty() { + return Err(NoPattern::Undefined); + } + let exhausted = if budget.pieces == 0 { + Some(NoPattern::DrawingPieces) + } else if budget.work == 0 { + Some(NoPattern::DrawingWork) + } else { + None + }; + if let Some(why) = budget.stopped.or(exhausted) { + budget.stopped = Some(why); + return Err(why); + } + let mut out = BezPath::new(); + let Some(b) = super::curve::bounds(boundary) else { return Ok((out, false)) }; + let size = b.width().max(b.height()); + if !(size > 0.0 && size.is_finite()) { + return Ok((out, false)); + } + let edges = edges(boundary, size * FLATNESS)?; + if edges.is_empty() { + return Ok((out, false)); + } + let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)]; + let tiny = size * TINY; + let (mut work, mut pieces, mut dots, mut usable) = (0usize, 0usize, false, false); + for l in lines { + let a = l.angle.to_radians(); + let d = Vec2::new(a.cos(), a.sin()); + let n = Vec2::new(-d.y, d.x); + let base = Point::new(l.base[0], l.base[1]); + let offset = Vec2::new(l.offset[0], l.offset[1]); + let step = offset.dot(n); + // A family with numbers out of range is damaged: the others still draw. + if ![a, base.x, base.y, offset.x, offset.y].iter().all(|v| v.is_finite()) || l.dashes.iter().any(|v| !v.is_finite()) { + continue; + } + usable = true; + // Lines no distance apart, or as good as none, fill the area past what can be drawn. + if step.abs() <= tiny { + return Err(NoPattern::TooDense); + } + // The lines crossing the boundary's box: base + k * offset for whole k. + let h = corners.map(|c| (c - base).dot(n) / step); + let lo = h.iter().copied().fold(f64::INFINITY, f64::min).ceil(); + let hi = h.iter().copied().fold(f64::NEG_INFINITY, f64::max).floor(); + if hi < lo { + continue; + } + let count = hi - lo + 1.0; + if count * (edges.len() as f64) + work as f64 > MAX_WORK as f64 { + return Err(NoPattern::TooDense); + } + let period: f64 = l.dashes.iter().map(|v| v.abs()).sum(); + if !l.dashes.is_empty() && period <= tiny { + return Err(NoPattern::TooDense); + } + let mut t = Vec::new(); + for k in (lo as i64)..=(hi as i64) { + budget.work(&mut work, edges.len())?; + let q = base + offset * k as f64; + crossings(&edges, q, d, n, &mut t); + for &[ta, tb] in t.as_chunks::<2>().0 { + if tb - ta <= tiny { + continue; + } + let mut emit = |s0: f64, s1: f64, budget: &mut Budget| -> Result<(), NoPattern> { + budget.piece(&mut pieces)?; + out.move_to(q + d * s0); + out.line_to(q + d * s1); + Ok(()) + }; + if l.dashes.is_empty() { + emit(ta, tb, budget)?; + continue; + } + // The dashes run from the line's base point: the first period that reaches the + // span, element by element. + let mut at = (ta / period).floor() * period; + 'span: loop { + for v in &l.dashes { + if at > tb { + break 'span; + } + budget.work(&mut work, 1)?; + let len = v.abs(); + if *v > 0.0 { + let (s0, s1) = (at.max(ta), (at + len).min(tb)); + if s1 > s0 { + emit(s0, s1, budget)?; + } + } else if *v == 0.0 && at >= ta { + emit(at, at, budget)?; + dots = true; + } + at += len; + } + } + } + } + } + if !usable { + return Err(NoPattern::Undefined); + } + Ok((out, dots)) +} + +/// The boundary's edges as straight segments, each loop closed. +fn edges(boundary: &BezPath, tolerance: f64) -> Result<Vec<(Point, Point)>, NoPattern> { + let mut out = Vec::new(); + let (mut start, mut last) = (None::<Point>, None::<Point>); + let mut over = false; + let mut push = |a: Point, b: Point, out: &mut Vec<(Point, Point)>| { + if out.len() >= MAX_EDGES { + over = true; + } else if a != b { + out.push((a, b)); + } + }; + kurbo::flatten(boundary.iter(), tolerance, |el| match el { + PathEl::MoveTo(p) => { + if let (Some(s), Some(l)) = (start, last) { + push(l, s, &mut out); + } + start = Some(p); + last = Some(p); + } + PathEl::LineTo(p) => { + if let Some(l) = last { + push(l, p, &mut out); + } + last = Some(p); + } + PathEl::ClosePath => { + if let (Some(s), Some(l)) = (start, last) { + push(l, s, &mut out); + } + last = start; + } + _ => {} + }); + if let (Some(s), Some(l)) = (start, last) { + push(l, s, &mut out); + } + if over { Err(NoPattern::TooDense) } else { Ok(out) } +} + +/// Where the line through `q` along `d` (unit; `n` its normal) crosses the edges, as distances +/// from `q` along `d`, sorted into `t`. A vertex on the line counts once, for the edge that leaves +/// the side the previous one came from. +fn crossings(edges: &[(Point, Point)], q: Point, d: Vec2, n: Vec2, t: &mut Vec<f64>) { + t.clear(); + for (p0, p1) in edges { + let (h0, h1) = ((*p0 - q).dot(n), (*p1 - q).dot(n)); + if (h0 > 0.0) != (h1 > 0.0) { + let p = p0.lerp(*p1, h0 / (h0 - h1)); + t.push((p - q).dot(d)); + } + } + t.sort_by(f64::total_cmp); +} + +/// The second color of a gradient: a color of its own, or for a one-color gradient the first +/// one shaded toward black (tint 0) or tinted toward white (tint 1); 0.5 keeps it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Second { + Col(Col), + Tint(f64), +} + +/// A gradient hatch's fill, placed in world coordinates (drawing units, y up). +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Grad { + pub kind: GradientKind, + /// Linear: where the first stop sits and the last; radial: the center, a point on the outer + /// ellipse and its aspect (a circle in the hatch's plane, an ellipse when the plane is seen + /// at a slant). + pub geom: GradientGeom, + pub first: Col, + pub second: Second, + /// Each stop's position and whether it takes the second color (else the first). + pub stops: Vec<(f32, bool)>, +} + +impl Grad { + /// `first` shaded or tinted by `tint` (see [`Second::Tint`]). + pub fn tinted([r, g, b]: [u8; 3], tint: f64) -> [u8; 3] { + let t = if tint.is_finite() { tint.clamp(0.0, 1.0) } else { 0.5 }; + let mix = |c: u8| { + let c = f64::from(c); + let v = if t < 0.5 { c * t * 2.0 } else { c + (255.0 - c) * (t - 0.5) * 2.0 }; + v.round().clamp(0.0, 255.0) as u8 + }; + [mix(r), mix(g), mix(b)] + } +} + +fn col(c: model::Color) -> Col { + match c { + model::Color::Rgb(rgb) => Col::Rgb(rgb), + model::Color::Index(i) => Col::Rgb(aci_paper(i)), + model::Color::ByBlock => Col::ByBlock, + model::Color::ByLayer => Col::ByLayer, + } +} + +/// The fill of gradient `g` over `boundary` (in the hatch's plane; `ocs` takes it to world +/// coordinates), `own` standing in for colors the gradient lacks. The gradient runs at its angle +/// across the boundary's extent in that direction. VectorCraft draws the named gradients this way: +/// `LINEAR` the first color to the second; `CYLINDER` the second color in the middle of the first; +/// `SPHERICAL` a circle from the second color at the center to the first; `HEMISPHERICAL` the same +/// circle centered on the bottom edge; `CURVED` the second color at the bottom to the first at the +/// top; each `INV` name the two colors the other way round; any other name as `LINEAR`. The shift +/// moves the center up and left by up to a quarter of the extent. +pub(crate) fn gradient(g: &model::Gradient, boundary: &BezPath, ocs: Affine, own: Col) -> Option<Grad> { + let angle = if g.angle.is_finite() { g.angle } else { 0.0 }; + let mut frame = boundary.clone(); + frame.apply_affine(Affine::rotate(-angle)); + let r = super::curve::bounds(&frame)?; + let (w, h) = (r.width(), r.height()); + let shift = if g.shift.is_finite() { g.shift.clamp(0.0, 1.0) } else { 0.0 }; + let c = r.center() + Vec2::new(-w, h) * (shift / 4.0); + // How far the shift moves the center along the gradient (left). + let dx = c.x - r.center().x; + let name = g.name.trim().to_uppercase(); + let (inverse, name) = match name.strip_prefix("INV") { + Some(rest) => (true, rest), + None => (false, name.as_str()), + }; + let swap = |stops: &[(f32, bool)]| stops.iter().map(|(o, s)| (*o, *s != inverse)).collect::<Vec<_>>(); + let (kind, start, end, stops) = match name { + "CYLINDER" => { + (GradientKind::Linear, Point::new(r.x0 + dx, c.y), Point::new(r.x1 + dx, c.y), swap(&[(0.0, false), (0.5, true), (1.0, false)])) + } + "SPHERICAL" => (GradientKind::Radial, c, c + Vec2::new(w.max(h) / 2.0, 0.0), swap(&[(0.0, true), (1.0, false)])), + "HEMISPHERICAL" => { + let center = Point::new(c.x, r.y0 + (c.y - r.center().y)); + (GradientKind::Radial, center, center + Vec2::new((w / 2.0).max(h), 0.0), swap(&[(0.0, true), (1.0, false)])) + } + "CURVED" => (GradientKind::Linear, Point::new(c.x, r.y0), Point::new(c.x, r.y1), swap(&[(0.0, true), (1.0, false)])), + _ => (GradientKind::Linear, Point::new(r.x0 + dx, c.y), Point::new(r.x1 + dx, c.y), swap(&[(0.0, false), (1.0, true)])), + }; + let mut geom = GradientGeom { start, end, aspect: 1.0, focal: None }; + geom.transform(ocs * Affine::rotate(angle), kind); + let first = g.colors.first().map_or(own, |c| col(*c)); + let second = if g.single { Second::Tint(g.tint) } else { Second::Col(g.colors.get(1).map_or(first, |c| col(*c))) }; + Some(Grad { kind, geom, first, second, stops }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pattern(lines: &[PatternLine], boundary: &BezPath) -> Result<(BezPath, bool), NoPattern> { + let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None }; + super::pattern(lines, boundary, &mut budget) + } + + #[test] + fn drawing_budgets_charge_discarded_patterns_and_stop_later_hatches() { + let lines = [line(0.0, [0.0, 1.0], &[])]; + let boundary = square(10.0); + let mut budget = Budget { pieces: 3, work: 100, stopped: None }; + assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingPieces)); + assert_eq!(budget.pieces, 0); + assert!(budget.work < 100); + let work = budget.work; + assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingPieces)); + assert_eq!(budget.work, work, "later hatches do no clipping"); + + let mut budget = Budget { pieces: 100, work: 9, stopped: None }; + assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingWork)); + assert_eq!(budget.work, 1, "two lines cost four edges each"); + let pieces = budget.pieces; + assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingWork)); + assert_eq!((budget.work, budget.pieces), (1, pieces)); + + let gaps = [line(0.0, [0.0, 1.0], &[-0.01])]; + let mut budget = Budget { pieces: 100, work: 20, stopped: None }; + assert_eq!(super::pattern(&gaps, &boundary, &mut budget), Err(NoPattern::DrawingWork)); + assert_eq!((budget.work, budget.pieces), (0, 100), "gaps cost work without drawing pieces"); + } + + fn square(side: f64) -> BezPath { + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + bp.line_to((side, 0.0)); + bp.line_to((side, side)); + bp.line_to((0.0, side)); + bp.close_path(); + bp + } + + fn line(angle: f64, offset: [f64; 2], dashes: &[f64]) -> PatternLine { + PatternLine { angle, base: [0.0, 0.0], offset, dashes: dashes.to_vec() } + } + + #[test] + fn doubling_adds_a_perpendicular_family_only_when_one_is_present() { + let mut level = line(0.0, [3.0, 10.0], &[4.0, -2.0]); + level.base = [2.0, 5.0]; + let lines = doubled(&[level.clone()]); + let [first, second] = &lines[..] else { panic!("two families") }; + assert_eq!((first.angle, first.base, first.offset, &first.dashes), (level.angle, level.base, level.offset, &level.dashes)); + assert_eq!(second.angle, level.angle + 90.0); + assert_eq!(second.offset, [-level.offset[1], level.offset[0]]); + assert_eq!((second.base, &second.dashes), (level.base, &level.dashes)); + let kept = doubled(&lines); + assert_eq!(kept.len(), lines.len()); + for (a, b) in kept.iter().zip(&lines) { + assert_eq!((a.angle, a.base, a.offset, &a.dashes), (b.angle, b.base, b.offset, &b.dashes)); + } + } + + /// The pieces as (start, end) pairs. + fn pieces(bp: &BezPath) -> Vec<(Point, Point)> { + let mut out = vec![]; + let mut from = Point::ZERO; + for el in bp.elements() { + match el { + PathEl::MoveTo(p) => from = *p, + PathEl::LineTo(p) => out.push((from, *p)), + _ => {} + } + } + out + } + + #[test] + fn pattern_lines_stop_at_the_boundary_and_skip_holes() { + // Horizontal lines 10 apart, through y 5, 15 … 95, across a 100 square with a 20 square + // hole in the middle. + let mut boundary = square(100.0); + let mut hole = square(20.0); + hole.apply_affine(Affine::translate((40.0, 40.0))); + boundary.extend(hole); + let l = PatternLine { angle: 0.0, base: [0.0, 5.0], offset: [0.0, 10.0], dashes: vec![] }; + let (bp, dots) = pattern(&[l], &boundary).unwrap(); + assert!(!dots); + let p = pieces(&bp); + // Ten lines, the two through the hole (y 45 and 55) each cut in two. + assert_eq!(p.len(), 12, "{p:?}"); + for (a, b) in &p { + assert!((a.y - b.y).abs() < 1e-9 && a.x >= -1e-9 && b.x <= 100.0 + 1e-9); + } + let middle: Vec<_> = p.iter().filter(|(a, _)| (a.y - 45.0).abs() < 1e-9).collect(); + assert_eq!(middle.len(), 2); + assert!(middle.iter().all(|(a, b)| b.x <= 40.0 + 1e-9 || a.x >= 60.0 - 1e-9), "{middle:?}"); + } + + #[test] + fn dashes_start_at_each_lines_base_point() { + // Dash 3, gap 2, a dot, gap 5: period 10 from x = 0, lines staggered by 5 along them. + let l = PatternLine { angle: 0.0, base: [0.0, 0.0], offset: [5.0, 50.0], dashes: vec![3.0, -2.0, 0.0, -5.0] }; + let (bp, dots) = pattern(&[l], &square(100.0)).unwrap(); + assert!(dots); + let p = pieces(&bp); + let row = |y: f64| p.iter().filter(|(a, _)| (a.y - y).abs() < 1e-9).map(|(a, b)| (a.x, b.x)).collect::<Vec<_>>(); + let first = row(50.0); + // The pattern at y 50 starts at x 5, so the period before it puts a dot on the boundary. + assert_eq!(&first[..4], &[(0.0, 0.0), (5.0, 8.0), (10.0, 10.0), (15.0, 18.0)]); + assert!(first.iter().all(|(a, b)| *a >= 0.0 && *b <= 100.0)); + } + + #[test] + fn a_dash_across_the_boundary_is_cut_there() { + let (bp, _) = pattern(&[line(0.0, [0.0, 7.0], &[30.0, -10.0])], &square(35.0)).unwrap(); + let p = pieces(&bp); + assert!(p.iter().any(|(a, b)| (a.x - 0.0).abs() < 1e-9 && (b.x - 30.0).abs() < 1e-9)); + // The second dash, 40 to 70, starts past the boundary at 35. + assert!(p.iter().all(|(_, b)| b.x <= 35.0 + 1e-9), "{p:?}"); + } + + #[test] + fn slanted_lines_fill_a_square_evenly() { + // 45 degree lines 1 apart across the square's diagonal of 14.1: each piece runs from one + // side of the square to another. + let offset = [-(0.5f64.sqrt()), 0.5f64.sqrt()]; + let (bp, _) = pattern(&[line(45.0, offset, &[])], &square(10.0)).unwrap(); + let p = pieces(&bp); + assert!((14..=15).contains(&p.len()), "{} lines", p.len()); + let on_edge = |q: Point| [q.x, q.y].iter().any(|v| v.abs() < 1e-6 || (v - 10.0).abs() < 1e-6); + assert!(p.iter().all(|(a, b)| on_edge(*a) && on_edge(*b))); + } + + #[test] + fn too_dense_patterns_and_missing_ones_are_reported() { + assert_eq!(pattern(&[], &square(10.0)), Err(NoPattern::Undefined)); + // Lines 0.001 apart across a 1,000 square: a million lines. + assert_eq!(pattern(&[line(0.0, [0.0, 0.001], &[])], &square(1000.0)), Err(NoPattern::TooDense)); + // Few lines, but dashes far shorter than the square: more pieces than allowed. + assert_eq!(pattern(&[line(0.0, [0.0, 10.0], &[0.01, -0.01])], &square(1000.0)), Err(NoPattern::TooDense)); + // A tiny nonempty dash period is too dense; only an empty list draws continuous lines. + // It is refused before any line is clipped or dashed. + let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None }; + assert_eq!(super::pattern(&[line(0.0, [0.0, 1.0], &[-1e-12])], &square(10.0), &mut budget), Err(NoPattern::TooDense)); + assert_eq!(budget.work, usize::MAX, "no work done"); + let (bp, _) = pattern(&[line(0.0, [0.0, 1.0], &[])], &square(10.0)).unwrap(); + assert!(!pieces(&bp).is_empty()); + // Lines on top of each other, or as good as, are as dense as can be. + assert_eq!(pattern(&[line(0.0, [5.0, 0.0], &[])], &square(10.0)), Err(NoPattern::TooDense)); + assert_eq!(pattern(&[line(0.0, [0.0, 1e-7], &[])], &square(1000.0)), Err(NoPattern::TooDense)); + // Only damaged families: no pattern to draw. + assert_eq!(pattern(&[line(f64::NAN, [0.0, 1.0], &[])], &square(10.0)), Err(NoPattern::Undefined)); + } + + fn grad(name: &str, angle: f64, shift: f64) -> model::Gradient { + model::Gradient { + name: name.into(), + angle, + shift, + single: false, + tint: 0.0, + colors: vec![model::Color::Index(1), model::Color::Rgb([0, 0, 255])], + } + } + + #[test] + fn gradients_run_across_the_boundary_at_their_angle() { + let box_ = { + let mut b = square(100.0); + b.apply_affine(Affine::scale_non_uniform(2.0, 1.0)); + b + }; + let g = gradient(&grad("LINEAR", 0.0, 0.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap(); + assert_eq!((g.kind, g.geom.start, g.geom.end), (GradientKind::Linear, Point::new(0.0, 50.0), Point::new(200.0, 50.0))); + assert_eq!((g.first, g.second), (Col::Rgb(aci_paper(1)), Second::Col(Col::Rgb([0, 0, 255])))); + assert_eq!(g.stops, [(0.0, false), (1.0, true)]); + // At a quarter turn it runs bottom to top. + let g = gradient(&grad("LINEAR", std::f64::consts::FRAC_PI_2, 0.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap(); + assert!(g.geom.start.distance(Point::new(100.0, 0.0)) < 1e-9 && g.geom.end.distance(Point::new(100.0, 100.0)) < 1e-9, "{g:?}"); + // Shifted, the center moves up and left: a sphere's center and a cylinder's middle. + let g = gradient(&grad("SPHERICAL", 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap(); + assert_eq!((g.kind, g.geom.start), (GradientKind::Radial, Point::new(50.0, 75.0))); + assert_eq!(g.stops, [(0.0, true), (1.0, false)], "the second color in the center"); + let g = gradient(&grad("CYLINDER", 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap(); + assert_eq!(g.geom.start.midpoint(g.geom.end), Point::new(50.0, 75.0)); + // A plane stretched twice as wide stretches the circle into an ellipse with it. + let g = gradient(&grad("SPHERICAL", 0.0, 0.0), &square(10.0), Affine::scale_non_uniform(2.0, 1.0), Col::ByLayer).unwrap(); + assert!((g.geom.aspect - 0.5).abs() < 1e-9 && g.geom.end.distance(Point::new(20.0, 5.0)) < 1e-9, "{:?}", g.geom); + } + + #[test] + fn inverse_gradients_swap_their_colors() { + for (name, inv) in + [("CYLINDER", "INVCYLINDER"), ("SPHERICAL", "INVSPHERICAL"), ("HEMISPHERICAL", "INVHEMISPHERICAL"), ("CURVED", "INVCURVED")] + { + let a = gradient(&grad(name, 0.0, 0.0), &square(10.0), Affine::IDENTITY, Col::ByLayer).unwrap(); + let b = gradient(&grad(inv, 0.0, 0.0), &square(10.0), Affine::IDENTITY, Col::ByLayer).unwrap(); + assert_eq!((a.kind, a.geom), (b.kind, b.geom), "{name}"); + assert!(a.stops.iter().zip(&b.stops).all(|(x, y)| x.0 == y.0 && x.1 != y.1), "{name}: {:?} {:?}", a.stops, b.stops); + } + } + + #[test] + fn one_color_gradients_shade_or_tint_their_color() { + assert_eq!(Grad::tinted([200, 100, 0], 0.0), [0, 0, 0]); + assert_eq!(Grad::tinted([200, 100, 0], 0.5), [200, 100, 0]); + assert_eq!(Grad::tinted([200, 100, 0], 1.0), [255, 255, 255]); + assert_eq!(Grad::tinted([200, 100, 0], 0.25), [100, 50, 0]); + let mut g = grad("LINEAR", 0.0, 0.0); + (g.single, g.tint, g.colors) = (true, 0.75, vec![]); + let g = gradient(&g, &square(10.0), Affine::IDENTITY, Col::ByBlock).unwrap(); + assert_eq!((g.first, g.second), (Col::ByBlock, Second::Tint(0.75)), "no color record: the hatch's own color"); + } +} diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index d53694343a..323923a370 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use kurbo::ParamCurve; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Justify, Node, NodeKind, TextObject, Unit}; +use vectorcraft_doc::{Appearance, Document, Justify, LineCap, Node, NodeKind, TextObject, Unit}; use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes}; use super::*; @@ -505,6 +505,175 @@ fn solid_hatches_fill_and_pattern_hatches_outline() { assert!(square.appearance.fill().is_some_and(|f| !f.paint.is_none())); } +/// [`hatch`]'s square with a round hole, as a pattern hatch of level lines 10 apart through +/// y 5, 15 … 95, in linetype `linetype`, with `dashes` (79 and 49 groups). +fn pattern_hatch(linetype: &'static str, dashes: &[(i32, &'static str)]) -> Vec<(i32, &'static str)> { + let mut e = hatch("0"); + e.insert(1, (6, linetype)); + let seeds = e.iter().position(|p| *p == (98, "0")).unwrap(); + let mut lines = vec![(78, "1"), (53, "0"), (43, "0"), (44, "5"), (45, "0"), (46, "10")]; + lines.extend_from_slice(if dashes.is_empty() { &[(79, "0")] } else { dashes }); + e.splice(seeds..seeds, lines); + e +} + +#[test] +fn pattern_hatches_draw_their_lines_inside_the_boundary() { + // A dashed linetype on the hatch: its pattern lines stay solid, as the pattern defines them. + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + let r = open(&drawing(&[], &tables, &[], &pattern_hatch("DASHED", &[])), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) }; + // Ten lines; the four that cross the hole (y 35 to 65) are cut in two. + assert_eq!(children.len(), 14); + assert_eq!(stroke_rgb(lines), [255, 0, 0, 255]); + assert!(lines.appearance.fill().is_none_or(|f| f.paint.is_none()), "the lines are not filled"); + assert!(lines.appearance.stroke().is_some_and(|s| s.dash.is_none()), "no linetype dashes on pattern lines"); + let h = height(&r.document); + for c in children { + let pts = path_points(c); + let (a, b) = (pts[0], *pts.last().unwrap()); + let y = h - a.y; + assert!((a.y - b.y).abs() < 1e-9 && (y - 5.0).rem_euclid(10.0) < 1e-9, "level lines through y 5, 15 …: {a:?} {b:?}"); + assert!(a.x.min(b.x) >= -1e-9 && a.x.max(b.x) <= 100.0 + 1e-9, "inside the square: {a:?} {b:?}"); + let mid = Point::new((a.x + b.x) / 2.0, y); + assert!(mid.distance(Point::new(50.0, 50.0)) > 20.0, "outside the hole: {a:?} {b:?}"); + } + assert!(lines.appearance.stroke().is_some_and(|s| s.cap != LineCap::Round)); + // A pattern of dots (no length) shows them with round caps. + let r = open(&entities(&pattern_hatch("CONTINUOUS", &[(79, "2"), (49, "0"), (49, "-5")])), &points()); + let [dots] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + assert!(dots.appearance.stroke().is_some_and(|s| s.cap == LineCap::Round), "{:?}", r.warnings); + // Without its pattern lines a pattern hatch still comes in as its boundary, with a note. + let r = open(&entities(&hatch("0")), &points()); + assert!(r.warnings.iter().any(|w| w.contains("without usable pattern lines")), "{:?}", r.warnings); +} + +#[test] +fn user_defined_double_hatches_draw_level_and_vertical_lines() { + for double in ["1", "0"] { + let mut e = pattern_hatch("CONTINUOUS", &[]); + let kind = e.iter().position(|p| *p == (76, "1")).unwrap(); + e[kind] = (76, "0"); + e.insert(kind + 1, (77, double)); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) }; + let (mut level, mut vertical) = (0, 0); + for c in children { + let pts = path_points(c); + let (a, b) = (pts[0], *pts.last().unwrap()); + if (a.y - b.y).abs() < 1e-9 && (a.x - b.x).abs() > 1e-9 { + level += 1; + } else if (a.x - b.x).abs() < 1e-9 && (a.y - b.y).abs() > 1e-9 { + vertical += 1; + } else { + panic!("level or vertical piece: {a:?} {b:?}"); + } + } + assert!(level > 0, "level pieces with double = {double}"); + assert_eq!(vertical > 0, double == "1", "vertical pieces with double = {double}"); + } +} + +#[test] +fn pattern_hatches_share_the_drawings_budget() { + // Keep the fixture's square alone so every fallback is one closed path. + let mut hatch = pattern_hatch("CONTINUOUS", &[]); + let hole = hatch.iter().position(|p| *p == (92, "0")).unwrap(); + let end = hatch.iter().position(|p| p.0 == 75).unwrap(); + hatch.drain(hole..end); + *hatch.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "1"); + let limit = super::hatch::MAX_TOTAL_PIECES; + let count = limit / 10 + 5; + let e = hatch.repeat(count); + let r = open(&entities(&e), &points()); + assert_eq!(r.warnings.len(), 1, "{:?}", r.warnings); + assert!(r.warnings[0].contains("2,000,000 dashes in all"), "{:?}", r.warnings); + let art = r.document.layers[0].children().unwrap(); + assert_eq!(art.len(), count, "each hatch keeps its place"); + let mut pieces = 0; + let mut boundaries = 0; + for n in art { + if let NodeKind::Compound { children, .. } = &n.kind { + assert_eq!(boundaries, 0, "all hatches after exhaustion keep their boundaries"); + pieces += children.len(); + assert!(children.iter().all(|c| c.path_data().is_some_and(|p| p.subpaths.iter().all(|s| !s.closed)))); + } else { + let path = n.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + assert!(path.subpaths[0].closed); + boundaries += 1; + } + } + assert!(pieces > 0 && pieces <= limit, "{pieces} pieces against {limit}"); + assert!(boundaries >= 5, "hatches past the budget keep their boundaries"); +} + +/// [`hatch`]'s square with a round hole, filled with gradient `name` at `angle` (radians) from +/// a true color (red) to color 5 (blue), or from red alone with `tint`. +fn gradient_hatch(name: &'static str, angle: &'static str, tint: Option<&'static str>) -> Vec<(i32, &'static str)> { + let mut e = hatch("1"); + e.extend([(450, "1"), (451, "0"), (452, if tint.is_some() { "1" } else { "0" }), (453, "2"), (460, angle), (461, "0")]); + e.extend([(462, tint.unwrap_or("0")), (463, "0"), (63, "1"), (421, "16711680"), (463, "1"), (63, "5"), (470, name)]); + e +} + +fn gradient_of(n: &Node) -> vectorcraft_color::GradientPaint { + match n.appearance.fill().map(|f| &f.paint) { + Some(Paint::Gradient(g)) => (**g).clone(), + other => panic!("not a gradient: {other:?}"), + } +} + +#[test] +fn gradient_hatches_keep_their_gradient() { + let r = open(&entities(&gradient_hatch("LINEAR", "0", None)), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let g = gradient_of(area); + let colors: Vec<[u8; 4]> = g.gradient.stops.iter().map(|s| s.color.to_rgba8(1.0)).collect(); + assert_eq!(g.gradient.kind, vectorcraft_color::GradientKind::Linear); + assert_eq!(colors, [[255, 0, 0, 255], [0, 0, 255, 255]], "the true color, then color 5"); + // Level, across the square from left to right through its middle. + let (h, geom) = (height(&r.document), g.geom.unwrap()); + assert!(geom.start.distance(Point::new(0.0, h - 50.0)) < 1e-9 && geom.end.distance(Point::new(100.0, h - 50.0)) < 1e-9, "{geom:?}"); + // A quarter turn runs it up the square: from the bottom (larger y in the document) to the top. + let r = open(&entities(&gradient_hatch("LINEAR", "1.5707963267948966", None)), &points()); + let geom = gradient_of(&r.document.layers[0].children().unwrap()[0]).geom.unwrap(); + assert!(geom.start.distance(Point::new(50.0, h)) < 1e-6 && geom.end.distance(Point::new(50.0, h - 100.0)) < 1e-6, "{geom:?}"); + // A one-color sphere tinted to white: white in the center, red at the edge. + let r = open(&entities(&gradient_hatch("SPHERICAL", "0", Some("1"))), &points()); + let g = gradient_of(&r.document.layers[0].children().unwrap()[0]); + let colors: Vec<[u8; 4]> = g.gradient.stops.iter().map(|s| s.color.to_rgba8(1.0)).collect(); + assert_eq!((g.gradient.kind, colors), (vectorcraft_color::GradientKind::Radial, vec![[255; 4], [255, 0, 0, 255]])); + assert!(g.geom.unwrap().start.distance(Point::new(50.0, h - 50.0)) < 1e-9); +} + +#[test] +fn block_gradient_stops_keep_the_inserts_color() { + for (color, layer) in [("0", "Doors"), ("256", "0")] { + for (second, tint) in [(false, None), (true, None), (false, Some("1"))] { + let mut hatch = gradient_hatch("LINEAR", "0", tint); + // The hatch's explicit color and other properties do not need insert inheritance. + hatch.splice(1..1, [(8, layer), (6, "CONTINUOUS"), (370, "25")]); + hatch.retain(|p| p.0 != 421); + let stop = hatch.iter_mut().filter(|p| p.0 == 63).nth(usize::from(second)).unwrap(); + *stop = (63, color); + let inserts = [(0, "INSERT"), (8, "Doors"), (2, "Door"), (62, "3"), (10, "0"), (20, "0")]; + let r = open(&with_door(&hatch, &inserts), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [symbol] = &r.document.symbols[..] else { panic!("one symbol") }; + let g = gradient_of(&symbol.art); + let stop = &g.gradient.stops[usize::from(second)]; + let expected = if color == "0" { [0, 255, 0, 255] } else { [0, 0, 255, 255] }; + assert_eq!(stop.color.to_rgba8(1.0), expected, "color {color}, second {second}, tint {tint:?}"); + } + } +} + #[test] fn hatch_declaring_many_absent_source_handles_parses_quickly() { let base = hatch("1"); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index c20f2ee24c..918f653235 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -371,7 +371,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | DCS 1.0 / 2.0 | place linked | place linked only (one image of the plates; spot plates as spot swatches; the composite's clipping path; each plate on its own ink in Separations Preview and print separations) | no | `crates/eps/src/dcs/tests.rs`, `crates/engine/src/tests/dcs.rs` | | SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as `<title>`, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); a masked group, or a knockout group's masked group, whose content has a shadow, glow, blur or feather starts with a hidden, unpainted rectangle over the mask's region, so readers that draw a masked group only inside the box of its shapes draw those effects too (`crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`); SVG Options › Units writes `width` and `height` in px (bare numbers, the default), pt, mm, cm or in, the `viewBox` staying in points, for software that reads physical size such as LaserGRBL (#4462, `crates/svg/tests/it/roundtrip.rs`) | -| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open | +| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open. DXF and DWG import draw a pattern hatch as its pattern lines (groups 53, 43–46 and 49) clipped to its boundary and cut into their dashes and dots, and fill a gradient hatch (groups 450–470) with a linear or radial gradient in its colors at its angle; the mapping of each named gradient to a linear or radial one is VectorCraft's own (`pattern_hatches_draw_their_lines_inside_the_boundary`, `gradient_hatches_keep_their_gradient`; [HATCH group codes](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-C6C71CED-CE0F-4184-82A5-07AD6241F15B.htm)) | | HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines; Export As opens HP-GL Options) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | | DWG | open, export | yes (open and place: craft-dwg converts the drawing to DXF, in a child process on desktop, and the DXF reader reads it with the DXF import options) | no (export DXF instead) | `crates/cad/src/import/tests_dwg.rs`, `crates/engine/src/cmd/fileio/tests_dwgimport.rs` (drawings written as DXF and converted to DWG by craft-dwg's writer); not in the web build | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776); a picture cut short by a reader limit, images and pattern brushes that are not read, clips that are not applied and raster operations other than a plain copy come back as warnings; tests in `crates/metafile/src/tests/import.rs` | diff --git a/docs/mcp.md b/docs/mcp.md index 4de603f5e1..b84778151a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12867,14 +12867,18 @@ artboard under `at`). `center: false` puts the drawing's origin (fitted art: its artboard's bottom-left corner; `mergeLayers` puts all art on one layer. Each DXF layer holding art becomes a layer (off and frozen layers hidden, locked ones locked, non-plotting ones non-printing). Lines, polylines (arc segments from bulges), circles, arcs, ellipses, splines (NURBS, within a millionth of their size), solids and hatches become paths (solid -hatches filled, pattern hatches as their boundaries), text and multiline text point type, named blocks symbols +hatches filled; gradient hatches filled with a linear or radial gradient at their angle, in their two colors or one +color shaded or tinted; pattern hatches as their pattern's lines clipped to the boundary, each cut into its dashes +and dots and stroked at the lineweight without the linetype; a pattern hatch with no usable pattern lines, with more +than 20,000 dashes, or past the drawing's budget of 2,000,000 dashes or 200,000,000 clipping steps, as its boundary), +text and multiline text point type, named blocks symbols (one per look when their art takes colour "by block"), anonymous blocks such as dimensions groups. 3D faces, polyface meshes and polygon meshes are seen from above, their height dropped: a 3D face or a polyface mesh's face becomes the lines of its visible edges (closed when every edge is visible), and a polygon mesh one path of its M and N lines (smoothed meshes draw their surface's vertices). Indexed colours (7 is black on paper), true colour, lineweights (`scaleLineweights` scales them with the art), linetypes and transparency resolve through layers and blocks. What is left out (viewports, images, meshes and mesh faces whose -vertices are missing, unknown entities) is listed in `warnings`. ASCII and binary DXF files are read. +vertices are missing, pattern hatches drawn as their boundaries, unknown entities) is listed in `warnings`. ASCII and binary DXF files are read. DWG drawings (by content or the `.dwg` extension) open, place and answer `document.dxfInfo` the same way, with the same `dxf` options: craft-dwg converts the drawing to DXF (acadrust 0.6.6, MPL-2.0) and the DXF reader reads that. From 181a471e6caeca96bc40af15d052c6836f615f71 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 21:22:30 -0800 Subject: [PATCH 65/88] Swatches: the panel checks a large selection in one read of the swatches The Swatches panel's body in craft-libs drops selected keys that no longer name a swatch or a group on every repaint while the panel is hovered, and checked each key with a scan of every swatch name. With 2,000 swatches in 20 groups and every swatch and group selected, one run compared about two million names. Every craft-libs rev moves from 4c330f6bd1 to dbc6b20e78, which reads the swatch names once per run and stops when it has found every selected name. Delete events and the footer's Delete answer the first lookup of a swatch or a group name with a scan and later lookups of that kind from a map of the names. Cargo.lock changes only the craft-libs source lines. --- Cargo.lock | 182 ++++++++++++++++---------------- Cargo.toml | 82 +++++++------- apps/vectorcraft-web/Cargo.toml | 2 +- xtask/src/pdf_deps.rs | 2 +- 4 files changed, 134 insertions(+), 134 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b878d75456..e99a0ac16f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1256,7 +1256,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-automation", "craft-behavior", @@ -1298,7 +1298,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "crc32fast", "flate2", @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1331,7 +1331,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "rustix 1.1.6", ] @@ -1339,7 +1339,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1364,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1383,7 +1383,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-docpath", @@ -1401,7 +1401,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "crc32fast", "flate2", @@ -1410,7 +1410,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "egui", ] @@ -1418,7 +1418,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "md-5", "rayon", @@ -1427,12 +1427,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-cms", @@ -1452,7 +1452,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-ai-agents", "craft-atomic", @@ -1468,7 +1468,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1478,7 +1478,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "rayon", ] @@ -1486,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1512,7 +1512,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "blake3", "craft-ecproj-format", @@ -1528,7 +1528,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "serde", ] @@ -1536,7 +1536,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1555,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-dwg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "acadrust", "craft-dxf", @@ -1565,7 +1565,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-codepage", "encoding_rs", @@ -1577,7 +1577,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "serde", "serde_json", @@ -1587,12 +1587,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-atomic", "dirs", @@ -1602,7 +1602,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1617,7 +1617,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1636,7 +1636,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1645,7 +1645,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "cap-primitives", "craft-atomic", @@ -1668,12 +1668,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "gif", ] @@ -1681,7 +1681,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "flate2", ] @@ -1689,7 +1689,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1702,7 +1702,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1732,7 +1732,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-dds", "craft-jpeg", @@ -1759,7 +1759,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1777,7 +1777,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "thiserror 2.0.21", ] @@ -1785,7 +1785,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1796,7 +1796,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-host", "craft-i18n", @@ -1811,7 +1811,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-i18n", @@ -1825,7 +1825,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-host", @@ -1843,7 +1843,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1855,7 +1855,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "encoding_rs", "image", @@ -1866,7 +1866,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "chrono", "craft-codepage", @@ -1876,7 +1876,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "uds_windows", "winsafe", @@ -1885,7 +1885,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-keymap", @@ -1901,7 +1901,7 @@ dependencies = [ [[package]] name = "craft-pbr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-texture", "thiserror 2.0.21", @@ -1910,7 +1910,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "flate2", "serde", @@ -1921,7 +1921,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1933,7 +1933,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "async-channel", "async-io", @@ -1966,7 +1966,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1975,7 +1975,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-host", @@ -1999,7 +1999,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -2010,7 +2010,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-eps", "flate2", @@ -2024,7 +2024,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "encoding_rs", "flate2", @@ -2035,7 +2035,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "dispatch2", "egui", @@ -2048,7 +2048,7 @@ dependencies = [ [[package]] name = "craft-raster3d" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "rayon", "thiserror 2.0.21", @@ -2057,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -2076,7 +2076,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-atomic", "craft-host", @@ -2093,7 +2093,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "fax", "hayro-ccitt", @@ -2104,7 +2104,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2125,7 +2125,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-keymap", @@ -2137,7 +2137,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2162,7 +2162,7 @@ dependencies = [ [[package]] name = "craft-texture" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "thiserror 2.0.21", ] @@ -2170,7 +2170,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2185,7 +2185,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-atomic", "craft-behavior", @@ -2200,7 +2200,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "serde", "thiserror 2.0.21", @@ -2210,7 +2210,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "serde", "thiserror 2.0.21", @@ -2219,7 +2219,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-keymap", @@ -2234,12 +2234,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2253,7 +2253,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -2270,7 +2270,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "accesskit", "craft-behavior", @@ -2308,7 +2308,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2319,7 +2319,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-host", @@ -2337,7 +2337,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-host", @@ -2358,7 +2358,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-host", @@ -2379,7 +2379,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-behavior", "craft-host", @@ -2398,7 +2398,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "base64 0.22.1", "chrono", @@ -2430,7 +2430,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "flate2", "serde", @@ -2441,7 +2441,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2451,7 +2451,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "js-sys", "serde_json", @@ -2462,7 +2462,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "winsafe", ] @@ -2470,7 +2470,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "craft-appkit", "craft-atomic", @@ -2502,7 +2502,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3862,7 +3862,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3871,7 +3871,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3889,7 +3889,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3907,12 +3907,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "flate2", "hayro-ccitt", @@ -4895,7 +4895,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "base64 0.22.1", "bumpalo", @@ -5052,7 +5052,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dbc6b20e78327f702371fcfc7887fc099fbedee8#dbc6b20e78327f702371fcfc7887fc099fbedee8" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index a48e3c1330..494a5ca085 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,57 +10,57 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } # 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } # DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified). -craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } # The metallic-roughness BRDF and environment light the 3D effects' Roughness and Metallic shade with. -craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } # The CPU rasterizer that draws a 3D effect's Render Settings › Rendered image: depth-buffered triangles, shadow maps. -craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -200,13 +200,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8" } # skrifa 0.44 (epaint, glifo, usvg) with the automatic hinter's long blue-zone exit (craft-libs vendor/skrifa). # It stays at this rev until craft-libs#5222 merges. skrifa = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 4db9a1dac2..580355f80e 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "dbc6b20e78327f702371fcfc7887fc099fbedee8", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 04cf313ca0..72a17d1408 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8"; +const REV: &str = "dbc6b20e78327f702371fcfc7887fc099fbedee8"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From a027a84b6ce3d6d9c7adff2020b6ab2990c1df4e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 21:54:40 -0800 Subject: [PATCH 66/88] DWG: a canceled export stops before the next drawing's conversion The DWG export converted every artboard's drawing before the export checked for cancellation, so a canceled multi-artboard export kept the background lane busy until all conversions finished. The export now checks for cancellation before each conversion. --- crates/engine/src/cmd/fileio/dxf.rs | 1 + crates/engine/src/cmd/fileio/tests_dwgimport.rs | 14 ++++++++++++++ 2 files changed, 15 insertions(+) diff --git a/crates/engine/src/cmd/fileio/dxf.rs b/crates/engine/src/cmd/fileio/dxf.rs index 1dceeb9b01..5fdb8ac1d7 100644 --- a/crates/engine/src/cmd/fileio/dxf.rs +++ b/crates/engine/src/cmd/fileio/dxf.rs @@ -277,6 +277,7 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>, dwg for ((board, _, _), out) in drawings.into_iter().zip(outs) { let mut warnings = out.warnings; let bytes = if dwg { + vectorcraft_doc::cancel::check()?; let (bytes, unwritten) = vectorcraft_cad::dwg::from_dxf(&out.bytes, opts.version).map_err(|e| bad(C, e))?; for (kind, n) in unwritten { *left_out.entry(kind).or_insert(0) += n; diff --git a/crates/engine/src/cmd/fileio/tests_dwgimport.rs b/crates/engine/src/cmd/fileio/tests_dwgimport.rs index dfacd51246..cdd317feb1 100644 --- a/crates/engine/src/cmd/fileio/tests_dwgimport.rs +++ b/crates/engine/src/cmd/fileio/tests_dwgimport.rs @@ -136,6 +136,20 @@ fn document_export_writes_a_dwg_that_opens_as_the_drawing_its_dxf_holds() { let _ = std::fs::remove_dir_all(&dir); } +/// A canceled export stops before converting any drawing to DWG. +#[test] +fn a_canceled_dwg_export_converts_no_drawing() { + vectorcraft_cad::dwg::allow_in_process(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + let doc = &s.doc().unwrap().doc; + let token = crate::cancel::CancelToken::new(); + token.cancel(); + let r = crate::cancel::scope(&token, None, || super::dxf::encode(doc, &json!({}), Some(true), true)); + assert!(matches!(r, Err(EngineError::Cancelled)), "{:?}", r.map(|e| e.files.len())); +} + #[test] fn a_dwg_version_before_2000_is_refused_and_nothing_is_written() { vectorcraft_cad::dwg::allow_in_process(); From 3e1fb85fd622a3c7d1f4efa7b112f3adb6b38263 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 22:09:32 -0800 Subject: [PATCH 67/88] DXF/DWG import: hatches follow their island style Every boundary loop of a hatch went into one even-odd area, which is right for the normal island style (group 75 = 0) only. With the outer style (1) the area inside an outermost loop and outside the islands directly in it is hatched, and islands inside islands are not; with the ignore style (2) only the outermost loops are, and islands leave no holes. This applies to solid, gradient and pattern hatches. A loop counts as inside another when its bounds lie within the other's, its area is smaller, and most of up to 16 points taken just inside it lie inside the other loop. Each loop is measured around its own center, so loops far from the origin, or far from each other, keep their precision. A hatch whose nesting test would take more than 10,000,000 steps is filled as if every loop were a boundary, with a warning. --- crates/cad/src/import/entity.rs | 96 +++++++++- crates/cad/src/import/tests.rs | 309 +++++++++++++++++++++++++++++++- docs/file-format-parity.md | 2 +- docs/mcp.md | 4 +- 4 files changed, 404 insertions(+), 7 deletions(-) diff --git a/crates/cad/src/import/entity.rs b/crates/cad/src/import/entity.rs index 3538920f1d..82fb0b0bd8 100644 --- a/crates/cad/src/import/entity.rs +++ b/crates/cad/src/import/entity.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; -use kurbo::{BezPath, PathEl}; +use kurbo::{BezPath, ParamCurve, ParamCurveDeriv, PathEl, PathSeg, Shape}; use vectorcraft_doc::Justify; use vectorcraft_geom::{Affine, Point, Vec2}; @@ -21,6 +21,10 @@ const LINE_SPACING: f64 = 5.0 / 3.0; const MAX_CELLS: i64 = 10_000; /// The most copies all the array inserts of a file make together. const MAX_TOTAL_CELLS: i64 = 2_000_000; +/// The most winding steps for island nesting: loops times boundary elements times samples. +const MAX_ISLAND_WORK: usize = if cfg!(test) { 1_000 } else { 10_000_000 }; +/// The most segment midpoints sampled just inside each loop for island nesting. +const MAX_ISLAND_SAMPLES: usize = 16; /// Art farther than this from the origin (drawing units) is damaged data, left out. const MAX_COORD: f64 = 1e12; /// How far fit and aligned text may be squeezed or stretched to span their two points: at width @@ -198,6 +202,7 @@ const PATTERN_HATCH: &str = "pattern hatches without usable pattern lines come i const DENSE_PATTERN: &str = "pattern hatches of more than 20,000 dashes come in as their boundaries"; const MANY_PATTERNS: &str = "the drawing's pattern hatches have more than 2,000,000 dashes in all: the rest come in as their boundaries"; const MUCH_PATTERN_WORK: &str = "the drawing's pattern hatches take too much work to clip: the rest come in as their boundaries"; +const MUCH_ISLAND_WORK: &str = "hatches with too many boundary points to sort into islands are filled as if every loop were a boundary"; const MESH_VERTICES: &str = "polygon meshes and polyface mesh faces whose vertices are missing are left out"; const BIG_ARRAY: &str = "array inserts are limited to 10,000 copies each"; const MANY_ARRAYS: &str = "array inserts are limited to 2,000,000 copies in all"; @@ -400,10 +405,95 @@ impl Converter { /// A hatch's art; `own`: its color, which a gradient without color records takes. fn hatch(&mut self, h: &model::Hatch, ocs: Affine, own: Col) -> Option<Geom> { - let mut bp = BezPath::new(); + let mut loops = Vec::new(); for l in &h.loops { let Some(path) = boundary(&l.path) else { break }; - bp.extend(path); + loops.push(path); + } + let mut max_depth = match h.style { + 1 => Some(1), + 2 => Some(0), + _ => None, + }; + if max_depth.is_some() { + let elements = loops.iter().fold(0usize, |total, path| total.saturating_add(path.elements().len())); + // Count each loop's samples against every loop, including its own containment checks. + if loops.len().saturating_mul(elements).saturating_mul(MAX_ISLAND_SAMPLES) > MAX_ISLAND_WORK { + self.warn(MUCH_ISLAND_WORK); + max_depth = None; + } + } + let nesting: Vec<_> = if max_depth.is_some() { + loops + .iter() + .map(|path| { + let bounds = path.bounding_box(); + // Center each loop independently so distant loops do not erase small geometry. + let center = bounds.center(); + let local = transformed(path.clone(), Affine::translate(-center.to_vec2())); + let area = local.area(); + // Area divided by perimeter measures thickness independently of the loop's rotation. + let perimeter = local.perimeter(bounds.width().max(bounds.height()) * 1e-3); + let inset = if perimeter > 0.0 { area.abs() / perimeter * 1e-3 * area.signum() } else { 0.0 }; + let step = local.segments().count().div_ceil(MAX_ISLAND_SAMPLES).max(1); + let mut samples: Vec<_> = local + .segments() + .step_by(step) + .filter_map(|segment| { + let tangent = match segment { + PathSeg::Line(line) => line.deriv().eval(0.5), + PathSeg::Quad(quad) => quad.deriv().eval(0.5), + PathSeg::Cubic(cubic) => cubic.deriv().eval(0.5), + } + .to_vec2(); + let tangent = if tangent.hypot() > 0.0 { tangent } else { segment.end() - segment.start() }; + let length = tangent.hypot(); + if length == 0.0 { + return None; + } + // Positive area puts the interior to the left of the tangent in y-up coordinates. + Some(segment.eval(0.5) + Vec2::new(-tangent.y, tangent.x) * (inset / length)) + }) + .take(MAX_ISLAND_SAMPLES) + .filter(|sample| local.winding(*sample) != 0) + .collect(); + if samples.is_empty() + && let Some(PathEl::MoveTo(first)) = local.elements().first() + { + samples.push(*first); + } + (bounds, center, local, area.abs(), samples) + }) + .collect() + } else { + Vec::new() + }; + let mut bp = BezPath::new(); + for (i, path) in loops.iter().enumerate() { + if let Some(limit) = max_depth { + let (bounds, center, _, area, samples) = &nesting[i]; + // Require geometric containment and a majority of samples so a shared + // edge or a single vertex on the boundary does not decide nesting. + let depth = nesting + .iter() + .enumerate() + .filter(|(j, _)| { + let (other_bounds, other_center, other, other_area, _) = &nesting[*j]; + let offset = *center - *other_center; + *j != i + && area < other_area + && bounds.x0 >= other_bounds.x0 + && bounds.y0 >= other_bounds.y0 + && bounds.x1 <= other_bounds.x1 + && bounds.y1 <= other_bounds.y1 + && samples.iter().filter(|p| other.winding(**p + offset) != 0).count() > samples.len() / 2 + }) + .count(); + if depth > limit { + continue; + } + } + bp.extend(path.iter()); } if bp.elements().is_empty() { return None; diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index 323923a370..9b692caa63 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -4,7 +4,7 @@ use std::sync::Arc; -use kurbo::ParamCurve; +use kurbo::{ParamCurve, Shape}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, Document, Justify, LineCap, Node, NodeKind, TextObject, Unit}; use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes}; @@ -517,6 +517,313 @@ fn pattern_hatch(linetype: &'static str, dashes: &[(i32, &'static str)]) -> Vec< e } +#[test] +fn ignore_islands_hatches_fill_and_pattern_through_the_hole() { + let mut e = hatch("1"); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let path = area.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1, "ignore islands leaves only the outer square"); + assert!(path.subpaths[0].closed); + assert!(area.appearance.fill().is_some_and(|f| !f.paint.is_none())); + let box_area = bounds(area).area(); + assert!((path.to_bezpath().area().abs() - box_area).abs() < box_area * 1e-9, "the whole square is filled"); + + let mut e = pattern_hatch("CONTINUOUS", &[]); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) }; + assert_eq!(children.len(), 10, "the ten level lines are not cut by the hole"); + let width = bounds(lines).width(); + assert!(children.iter().all(|c| (bounds(c).width() - width).abs() < width * 1e-9), "each line spans the square"); +} + +#[test] +fn hatch_island_styles_select_nested_boundary_levels() { + let mut e = hatch("1"); + let count = e.iter().position(|p| p.0 == 91).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + e[count] = (91, "3"); + let mut loops = Vec::new(); + // Innermost first so nesting depends on geometry, not boundary order or flags. + for (lo, hi) in [("40", "60"), ("0", "100"), ("20", "80")] { + loops.extend([ + (92, "2"), + (72, "0"), + (73, "1"), + (93, "4"), + (10, lo), + (20, lo), + (10, hi), + (20, lo), + (10, hi), + (20, hi), + (10, lo), + (20, hi), + (97, "0"), + ]); + } + e.splice(count + 1..end, loops); + for (style, expected) in [("0", 3), ("1", 2), ("2", 1), ("3", 3)] { + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, style); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "style {style}: {:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let count = match &area.kind { + NodeKind::Compound { children, rule } => { + assert_eq!(*rule, FillRule::EvenOdd); + children.len() + } + _ => area.path_data().unwrap().subpaths.len(), + }; + assert_eq!(count, expected, "boundary loops for island style {style}"); + assert!(area.appearance.fill().is_some_and(|f| !f.paint.is_none())); + } +} + +#[test] +fn hatch_ignore_islands_drops_small_island_far_from_origin() { + let mut e = hatch("1"); + let start = e.iter().position(|p| p.0 == 92).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + let mut loops = Vec::new(); + for (lo, hi) in [("100000000", "100000001"), ("100000000.2", "100000000.8")] { + loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] { + loops.extend([(10, x), (20, y)]); + } + loops.push((97, "0")); + } + e.splice(start..end, loops); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + // Centered, so the art far from the drawing's origin lands on the canvas. + let r = open(&entities(&e), &ImportOptions { center: true, ..points() }); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let path = area.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1, "the small island far from the origin is removed"); +} + +#[test] +fn hatch_ignore_islands_drops_small_island_with_distant_outer_loop() { + let mut e = hatch("1"); + let start = e.iter().position(|p| p.0 == 92).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + *e.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "3"); + let mut loops = Vec::new(); + for (lo, hi) in [("0", "1"), ("0.2", "0.8"), ("100000000", "100000001")] { + loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] { + loops.extend([(10, x), (20, y)]); + } + loops.push((97, "0")); + } + e.splice(start..end, loops); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + // Fitted to the artboard: the drawing spans more than the canvas holds at 1:1. + let r = open(&entities(&e), &ImportOptions { fit: true, ..points() }); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let NodeKind::Compound { children, .. } = &area.kind else { panic!("both outer boundary loops must remain") }; + assert_eq!(children.len(), 2, "the island is removed and both outer squares remain"); +} + +#[test] +fn hatch_ignore_islands_drops_tiny_island_with_distant_outer_loop() { + let mut e = hatch("1"); + let start = e.iter().position(|p| p.0 == 92).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + *e.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "3"); + let mut loops = Vec::new(); + for (lo, hi) in [("0", "0.000001"), ("0.0000002", "0.0000008"), ("100000000000", "100000000001")] { + loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] { + loops.extend([(10, x), (20, y)]); + } + loops.push((97, "0")); + } + e.splice(start..end, loops); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + // Fitted to the artboard: the drawing spans more than the canvas holds at 1:1. + let r = open(&entities(&e), &ImportOptions { fit: true, ..points() }); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let NodeKind::Compound { children, .. } = &area.kind else { panic!("both outer boundary loops must remain") }; + assert_eq!(children.len(), 2, "the tiny island is removed and both outer squares remain"); +} + +#[test] +fn hatch_ignore_islands_keeps_squares_sharing_an_edge() { + let mut e = hatch("1"); + let start = e.iter().position(|p| p.0 == 92).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + let mut loops = Vec::new(); + // The first vertex lies on the second square's left edge. + for vertices in [[("10", "0"), ("10", "10"), ("0", "10"), ("0", "0")], [("10", "0"), ("20", "0"), ("20", "10"), ("10", "10")]] { + loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in vertices { + loops.extend([(10, x), (20, y)]); + } + loops.push((97, "0")); + } + e.splice(start..end, loops); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let NodeKind::Compound { children, .. } = &area.kind else { panic!("both boundary loops must remain") }; + assert_eq!(children.len(), 2, "adjacent squares are both boundaries"); +} + +#[test] +fn hatch_ignore_islands_drops_square_touching_outer_boundary_at_a_vertex() { + let mut e = hatch("1"); + let start = e.iter().position(|p| p.0 == 92).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + let mut loops = Vec::new(); + // The island's first vertex touches the outer square's right edge, where + // winding is zero. Its other vertices and all segment midpoints are inside. + for vertices in [[("100", "50"), ("75", "75"), ("50", "50"), ("75", "25")], [("0", "0"), ("100", "0"), ("100", "100"), ("0", "100")]] { + loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in vertices { + loops.extend([(10, x), (20, y)]); + } + loops.push((97, "0")); + } + e.splice(start..end, loops); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let path = area.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1, "the touching island is removed"); +} + +#[test] +fn hatch_ignore_islands_drops_square_sharing_two_outer_edges() { + let mut e = hatch("1"); + let start = e.iter().position(|p| p.0 == 92).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + let mut loops = Vec::new(); + for vertices in [[("50", "50"), ("100", "50"), ("100", "100"), ("50", "100")], [("0", "0"), ("100", "0"), ("100", "100"), ("0", "100")]] { + loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in vertices { + loops.extend([(10, x), (20, y)]); + } + loops.push((97, "0")); + } + e.splice(start..end, loops); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let path = area.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1, "the island sharing two outer edges is removed"); +} + +#[test] +fn hatch_ignore_islands_drops_thin_island() { + let mut e = hatch("1"); + let start = e.iter().position(|p| p.0 == 92).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + let mut loops = Vec::new(); + for vertices in [ + [("0", "0"), ("100", "0"), ("100", "0.00001"), ("0", "0.00001")], + [("10", "0.000002"), ("90", "0.000002"), ("90", "0.000008"), ("10", "0.000008")], + ] { + loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in vertices { + loops.extend([(10, x), (20, y)]); + } + loops.push((97, "0")); + } + e.splice(start..end, loops); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let path = area.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1, "the thin island is removed"); +} + +#[test] +fn hatch_ignore_islands_drops_rotated_thin_island() { + let mut e = hatch("1"); + let start = e.iter().position(|p| p.0 == 92).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + let mut loops = Vec::new(); + // These are the previous test's corners turned 45 degrees about the origin. + for vertices in [ + [("0", "0"), ("70.7106781187", "70.7106781187"), ("70.7106710476", "70.7106851897"), ("-0.00000707106781187", "0.00000707106781187")], + [ + ("7.07106639765", "7.07106922608"), + ("63.6396088926", "63.6396117210"), + ("63.6396046499", "63.6396159636"), + ("7.07106215421", "7.07107346952"), + ], + ] { + loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in vertices { + loops.extend([(10, x), (20, y)]); + } + loops.push((97, "0")); + } + e.splice(start..end, loops); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let path = area.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1, "the rotated thin island is removed"); +} + +#[test] +fn hatch_island_work_limit_keeps_all_loops_and_warns_only_for_island_styles() { + let mut e = hatch("1"); + let count = e.iter().position(|p| p.0 == 91).unwrap(); + let hole = e.iter().position(|p| *p == (92, "0")).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + e[count] = (91, "16"); + // Keep the outer square and add 15 inner squares. With at least five path elements + // per square, 16 loops require at least 1,280 steps, over the test-time limit. + // Without the fallback, ignore style removes the inner squares. + let inner = [ + (92, "2"), + (72, "0"), + (73, "1"), + (93, "4"), + (10, "20"), + (20, "20"), + (10, "80"), + (20, "20"), + (10, "80"), + (20, "80"), + (10, "20"), + (20, "80"), + (97, "0"), + ]; + e.splice(hole..end, inner.repeat(15)); + for style in ["2", "0"] { + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, style); + let r = open(&entities(&e), &points()); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let count = match &area.kind { + NodeKind::Compound { children, .. } => children.len(), + _ => area.path_data().unwrap().subpaths.len(), + }; + assert_eq!(count, 16, "every boundary loop is kept for style {style}"); + if style == "2" { + assert_eq!(r.warnings, ["hatches with too many boundary points to sort into islands are filled as if every loop were a boundary"]); + } else { + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + } + } +} + #[test] fn pattern_hatches_draw_their_lines_inside_the_boundary() { // A dashed linetype on the hatch: its pattern lines stay solid, as the pattern defines them. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 918f653235..125bf2ac50 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -371,7 +371,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | DCS 1.0 / 2.0 | place linked | place linked only (one image of the plates; spot plates as spot swatches; the composite's clipping path; each plate on its own ink in Separations Preview and print separations) | no | `crates/eps/src/dcs/tests.rs`, `crates/engine/src/tests/dcs.rs` | | SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as `<title>`, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); a masked group, or a knockout group's masked group, whose content has a shadow, glow, blur or feather starts with a hidden, unpainted rectangle over the mask's region, so readers that draw a masked group only inside the box of its shapes draw those effects too (`crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`); SVG Options › Units writes `width` and `height` in px (bare numbers, the default), pt, mm, cm or in, the `viewBox` staying in points, for software that reads physical size such as LaserGRBL (#4462, `crates/svg/tests/it/roundtrip.rs`) | -| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open. DXF and DWG import draw a pattern hatch as its pattern lines (groups 53, 43–46 and 49) clipped to its boundary and cut into their dashes and dots, and fill a gradient hatch (groups 450–470) with a linear or radial gradient in its colors at its angle; the mapping of each named gradient to a linear or radial one is VectorCraft's own (`pattern_hatches_draw_their_lines_inside_the_boundary`, `gradient_hatches_keep_their_gradient`; [HATCH group codes](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-C6C71CED-CE0F-4184-82A5-07AD6241F15B.htm)) | +| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open. DXF and DWG import draw a pattern hatch as its pattern lines (groups 53, 43–46 and 49) clipped to its boundary and cut into their dashes and dots, and fill a gradient hatch (groups 450–470) with a linear or radial gradient in its colors at its angle; hatches follow their island style (normal, outer, ignore); the mapping of each named gradient to a linear or radial one is VectorCraft's own (`pattern_hatches_draw_their_lines_inside_the_boundary`, `gradient_hatches_keep_their_gradient`; [HATCH group codes](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-C6C71CED-CE0F-4184-82A5-07AD6241F15B.htm)) | | HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines; Export As opens HP-GL Options) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | | DWG | open, export | yes (open and place: craft-dwg converts the drawing to DXF, in a child process on desktop, and the DXF reader reads it with the DXF import options) | no (export DXF instead) | `crates/cad/src/import/tests_dwg.rs`, `crates/engine/src/cmd/fileio/tests_dwgimport.rs` (drawings written as DXF and converted to DWG by craft-dwg's writer); not in the web build | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776); a picture cut short by a reader limit, images and pattern brushes that are not read, clips that are not applied and raster operations other than a plain copy come back as warnings; tests in `crates/metafile/src/tests/import.rs` | diff --git a/docs/mcp.md b/docs/mcp.md index 3479499590..1a602443cf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12881,8 +12881,8 @@ artboard under `at`). `center: false` puts the drawing's origin (fitted art: its artboard's bottom-left corner; `mergeLayers` puts all art on one layer. Each DXF layer holding art becomes a layer (off and frozen layers hidden, locked ones locked, non-plotting ones non-printing). Lines, polylines (arc segments from bulges), circles, arcs, ellipses, splines (NURBS, within a millionth of their size), solids and hatches become paths (solid -hatches filled; gradient hatches filled with a linear or radial gradient at their angle, in their two colors or one -color shaded or tinted; pattern hatches as their pattern's lines clipped to the boundary, each cut into its dashes +hatches filled; hatches follow their island style (normal, outer, ignore); gradient hatches filled with a linear or +radial gradient at their angle, in their two colors or one color shaded or tinted; pattern hatches as their pattern's lines clipped to the boundary, each cut into its dashes and dots and stroked at the lineweight without the linetype; a pattern hatch with no usable pattern lines, with more than 20,000 dashes, or past the drawing's budget of 2,000,000 dashes or 200,000,000 clipping steps, as its boundary), text and multiline text point type, named blocks symbols From 4f0f1231087b8cd4969e961fbf57cf79ec7b2279 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 22:19:39 -0800 Subject: [PATCH 68/88] CI: the build job builds each shard's tests in a command of its own On the pull request run the build job ran one `cargo test --workspace` for every test, and the runner stopped with "received a shutdown signal" (exit 143) after 28 minutes, while it compiled vectorcraft-engine's, vectorcraft-ui-egui's and the app crates' tests side by side. A workspace build also resolves features over every crate, so on the build host the archive step then rebuilt 58 units that the shards' own builds had built with other features. `cargo xtask ci archive` now builds the library and binary tests of each shard's run in a cargo command of its own, then each run's integration tests, as the shards and the cache warm did before. Each archive uses its run's package and target selection, so the archive step finds every test built: on the build host each of the archive commands finished in under a second after the builds. An archive holds one cargo selection, so each shard now makes one run: vectorcraft-engine's integration tests move from shard 4 to shard 3, beside its library tests, and `ci archive` fails on a shard with more than one run. --- xtask/src/main.rs | 120 ++++++++++++++++++++++++++++++++++------ xtask/src/shards.rs | 132 ++------------------------------------------ 2 files changed, 109 insertions(+), 143 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 6e2d03166c..73a47429ba 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -456,14 +456,16 @@ fn cmd_ci_shard() -> Result<(), String> { } /// `cargo xtask ci archive`: the shared gate's `build` job (`archive-command` with -/// `shard-archives`). After the shard checks it builds every shard's tests in one workspace build, -/// then writes the test binaries of shard k (1-based, [`shards::Shard::filterset`]) to the nextest -/// archive `$NEXTEST_ARCHIVE_DIR/<k>/$NEXTEST_ARCHIVE_NAME` for every k up to `GATE_SHARDS`. A -/// split's later parts run the same binaries as part 1, so their archive is a copy of part 1's. +/// `shard-archives`). After the shard checks it builds the tests of each shard's run, one cargo +/// command per run ([`archive_builds`]), then writes the tests of shard k's run (1-based, +/// [`archived_runs`]) to the nextest archive `$NEXTEST_ARCHIVE_DIR/<k>/$NEXTEST_ARCHIVE_NAME` for +/// every k up to `GATE_SHARDS`, with the run's package and target selection, so the archive's own +/// build finds them built. A split's later parts run the same binaries as part 1, so their archive +/// is a copy of part 1's. /// -/// In a leg that saves the cache, the library and binary tests' build records its units in +/// In a leg that saves the cache, the library and binary tests' builds record their units in /// `CRAFT_CACHE_UNITS` (xtask/src/cache_units.rs), xtask's own build included, and the -/// integration tests' build does not, so the saved entry holds every dependency and +/// integration tests' builds do not, so the saved entry holds every dependency and /// dev-dependency the tests build with and none of the integration tests' executables. fn cmd_ci_archive() -> Result<(), String> { let var = |key: &str| { @@ -476,13 +478,12 @@ fn cmd_ci_archive() -> Result<(), String> { } cache_units::record_xtask()?; let checked = shards::run()?; - let mut c = cargo(); - c.args(["test", "--workspace", "--lib", "--bins", "--no-run"]); - cache_units::run(c, "cargo test --workspace --lib --bins --no-run")?; - let mut c = cargo(); - c.args(["test", "--workspace", "--lib", "--bins", "--tests", "--no-run"]); - run(c, "cargo test --workspace --lib --bins --tests --no-run")?; - for (i, shard) in checked.iter().enumerate() { + let archived = archived_runs(&checked)?; + for (units, r) in archive_builds(&checked) { + let (c, what) = test_build(&r, units); + if units { cache_units::run(c, &what)? } else { run(c, &what)? } + } + for (i, (shard, r)) in checked.iter().zip(archived).enumerate() { let file = dir.join((i + 1).to_string()).join(&name); let parent = file.parent().unwrap_or(&dir); std::fs::create_dir_all(parent).map_err(|e| format!("ci archive: {}: {e}", parent.display()))?; @@ -494,14 +495,51 @@ fn cmd_ci_archive() -> Result<(), String> { eprintln!("ci archive: shard {} runs part {} of shard {}'s archive", i + 1, p.index, i + 2 - p.index); continue; } - let filter = shard.filterset(); let mut c = cargo(); - c.args(["nextest", "archive", "--workspace", "--lib", "--bins", "--tests", "-E", &filter, "--archive-file"]).arg(&file); - run(c, &format!("cargo nextest archive --workspace --lib --bins --tests -E '{filter}' --archive-file {}", file.display()))?; + c.args(["nextest", "archive"]).args(shards::select(&r.crates)).args(r.targets.args()).arg("--archive-file").arg(&file); + let what = format!("cargo nextest archive {} ({}) --archive-file {}", r.targets.shown(), shards::names(&r.crates), file.display()); + run(c, &what)?; } Ok(()) } +/// The run of each shard, whose tests `ci archive` writes to the shard's archive with one cargo +/// selection. A shard that makes more than one run is an error. +fn archived_runs(shards: &[shards::Shard]) -> Result<Vec<&shards::Run>, String> { + shards + .iter() + .enumerate() + .map(|(i, s)| match s.runs.as_slice() { + [r] => Ok(r), + runs => Err(format!( + "ci archive: shard {} makes {} runs, and its archive holds the tests of one (xtask/src/shards.rs › GROUPS)", + i + 1, + runs.len() + )), + }) + .collect() +} + +/// The builds `ci archive` runs before it writes the archives, in order: `(true, run)` builds the +/// library and binary tests of a run of the first part of each shard (none for a run of +/// integration tests alone, whose crate has its library tests in a run on another shard), then +/// `(false, run)` builds each such run's integration tests. +fn archive_builds(shards: &[shards::Shard]) -> Vec<(bool, shards::Run)> { + let runs: Vec<&shards::Run> = shards.iter().filter(|s| s.part.is_none_or(|p| p.is_first())).flat_map(|s| &s.runs).collect(); + let units = runs.iter().filter(|r| r.targets != shards::Targets::Integration).map(|r| (true, (*r).clone())); + let integration = runs.iter().filter(|r| r.targets != shards::Targets::Units).map(|r| (false, (*r).clone())); + units.chain(integration).collect() +} + +/// The `cargo test --no-run` command that builds a run's library and binary tests (`units`) or its +/// integration tests, and its description. +fn test_build(r: &shards::Run, units: bool) -> (Command, String) { + let targets = if units { shards::Targets::Units } else { shards::Targets::Integration }; + let mut c = cargo(); + c.arg("test").args(shards::select(&r.crates)).args(targets.args()).arg("--no-run"); + (c, format!("cargo test {} --no-run ({})", targets.shown(), shards::names(&r.crates))) +} + /// `cargo xtask ci checks`: every `ci` step other than [`TEST_STEPS`], for the shared gate's /// `lint` leg. fn cmd_ci_checks() -> Result<(), String> { @@ -660,3 +698,53 @@ fn i18n_report_archive(file: &Path) -> Result<(), String> { c.args(["--no-capture", "-E", "test(=i18n::tests::untranslated_report)"]); run(c, &format!("cargo nextest run --archive-file {} --no-capture -E 'test(=i18n::tests::untranslated_report)'", file.display())) } + +#[cfg(test)] +mod tests { + use super::*; + use shards::{Group, Split, Targets}; + + #[test] + fn the_archive_builds_each_run_once_library_tests_first() { + let m = + |name: &str| shards::Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into(), doctests: true }; + static SPLIT: Split = Split { crates: &["a"], pinned: &[&[], &[]] }; + let groups = [ + Group::Part(&SPLIT, 1), + Group::Part(&SPLIT, 2), + Group::Targets(&[(Targets::Units, &["b"])]), + Group::Targets(&[(Targets::All, &["c"]), (Targets::Integration, &["b"])]), + Group::Rest, + ]; + let shards = shards::assign(&groups, &[m("a"), m("b"), m("c"), m("d")]).unwrap(); + let builds: Vec<(Vec<String>, String)> = archive_builds(&shards) + .iter() + .map(|(units, r)| { + let (c, what) = test_build(r, *units); + (c.get_args().map(|a| a.to_string_lossy().into_owned()).collect(), what) + }) + .collect(); + let shown: Vec<&str> = builds.iter().map(|(_, what)| what.as_str()).collect(); + assert_eq!( + shown, + [ + "cargo test --lib --bins --no-run (a)", + "cargo test --lib --bins --no-run (b)", + "cargo test --lib --bins --no-run (c)", + "cargo test --lib --bins --no-run (d)", + "cargo test --test '*' --no-run (a)", + "cargo test --test '*' --no-run (c)", + "cargo test --test '*' --no-run (b)", + "cargo test --test '*' --no-run (d)", + ] + ); + assert_eq!(builds[1].0, ["test", "-p", "path+file:///w/b#0.1.0", "--lib", "--bins", "--no-run"]); + assert_eq!(builds[6].0, ["test", "-p", "path+file:///w/b#0.1.0", "--test", "*", "--no-run"]); + let two = archived_runs(&shards).unwrap_err(); + assert!(two.contains("shard 4 makes 2 runs"), "{two}"); + let real = shards::assigned().unwrap(); + let archived = archived_runs(&real).unwrap(); + assert_eq!(archived.len(), shards::GROUPS.len()); + assert!(archived.iter().zip(&real).all(|(r, s)| s.runs == [(*r).clone()])); + } +} diff --git a/xtask/src/shards.rs b/xtask/src/shards.rs index 372d8fbe7d..fa814fb159 100644 --- a/xtask/src/shards.rs +++ b/xtask/src/shards.rs @@ -3,8 +3,7 @@ //! complete. //! //! In CI the gate's `build` job builds every shard's tests once and writes one nextest archive per -//! shard (`cargo xtask ci archive`, [`Shard::filterset`]), and each shard runs its tests from its -//! archive. Without an archive a shard builds and runs the tests of its own crates and what they +//! shard (`cargo xtask ci archive`), and each shard runs its tests from its archive. Without an archive a shard builds and runs the tests of its own crates and what they //! depend on. The `cargo xtask ci` steps that are not tests run in the gate's `lint` leg //! (`cargo xtask ci checks`). [`GROUPS`] names the crates of the first shards; every other //! workspace member goes to the [`Group::Rest`] shard, so a new crate is tested without a change @@ -72,16 +71,6 @@ impl Targets { Targets::Integration => "--test '*'", } } - - /// The nextest filterset of the test binaries [`Targets::args`] selects among a build of - /// `--lib --bins --tests`: `None` for all of them. - pub fn filterset(self) -> Option<&'static str> { - match self { - Targets::All => None, - Targets::Units => Some("kind(lib) | kind(proc-macro) | kind(bin)"), - Targets::Integration => Some("kind(test)"), - } - } } /// Crates whose tests run on several shards, one [`Group::Part`] each. @@ -120,16 +109,13 @@ pub static UI_EGUI: Split = Split { }; /// The shards in order; `test-shards` in `.github/workflows/ci.yml` is its length, and its -/// `shard-members` names each shard's crates. vectorcraft-engine's integration tests run on -/// shard 4, which already builds the engine library for the app crates. +/// `shard-members` names each shard's crates. Each shard makes one run: `cargo xtask ci archive` +/// writes a shard's archive with the run's package and target selection. pub const GROUPS: &[Group] = &[ Group::Part(&UI_EGUI, 1), Group::Part(&UI_EGUI, 2), - Group::Targets(&[(Targets::Units, &["vectorcraft-engine"])]), - Group::Targets(&[ - (Targets::All, &["vectorcraft", "vectorcraft-web", "vectorcraft-cli", "vectorcraft-mcp", "xtask"]), - (Targets::Integration, &["vectorcraft-engine"]), - ]), + Group::Targets(&[(Targets::All, &["vectorcraft-engine"])]), + Group::Targets(&[(Targets::All, &["vectorcraft", "vectorcraft-web", "vectorcraft-cli", "vectorcraft-mcp", "xtask"])]), Group::Rest, ]; @@ -154,24 +140,6 @@ pub struct Shard { pub part: Option<Part>, } -impl Shard { - /// The nextest filterset of the test binaries this shard runs, among a workspace build of - /// `--lib --bins --tests`: each run's crates (`package(=…)`), with its targets' kinds. - pub fn filterset(&self) -> String { - self.runs - .iter() - .map(|r| { - let packages = r.crates.iter().map(|m| format!("package(={})", m.name)).collect::<Vec<_>>().join(" | "); - match r.targets.filterset() { - None => format!("({packages})"), - Some(kinds) => format!("(({packages}) & ({kinds}))"), - } - }) - .collect::<Vec<_>>() - .join(" | ") - } -} - /// One test run of a shard: the given targets of these crates. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Run { @@ -533,96 +501,6 @@ pub fn run() -> Result<Vec<Shard>, String> { mod tests { use super::*; - /// Whether the filterset `expr` (`package(=…)` and `kind(…)` terms joined by `|` and `&`, with - /// parentheses) matches a test binary of `package` whose kind is `kind`, as nextest reads - /// those terms: `&` binds tighter than `|`. - fn matches(expr: &str, package: &str, kind: &str) -> bool { - fn any(s: &mut &str, package: &str, kind: &str) -> bool { - let mut found = all(s, package, kind); - while let Some(rest) = s.trim_start().strip_prefix('|') { - *s = rest; - found |= all(s, package, kind); - } - found - } - fn all(s: &mut &str, package: &str, kind: &str) -> bool { - let mut found = term(s, package, kind); - while let Some(rest) = s.trim_start().strip_prefix('&') { - *s = rest; - found &= term(s, package, kind); - } - found - } - fn term(s: &mut &str, package: &str, kind: &str) -> bool { - *s = s.trim_start(); - if let Some(rest) = s.strip_prefix('(') { - *s = rest; - let found = any(s, package, kind); - *s = s.trim_start().strip_prefix(')').unwrap_or_else(|| panic!("no `)` before `{s}`")); - return found; - } - let (call, rest) = s.split_once(')').unwrap_or_else(|| panic!("no `)` in `{s}`")); - *s = rest; - match call.split_once('(') { - Some(("package", name)) => name.strip_prefix('=') == Some(package), - Some(("kind", k)) => k == kind, - _ => panic!("unknown term `{call})`"), - } - } - let mut s = expr; - let found = any(&mut s, package, kind); - assert!(s.trim().is_empty(), "`{s}` left over in `{expr}`"); - found - } - - #[test] - fn a_shard_s_archive_holds_the_test_binaries_of_its_runs() { - let units = Shard { runs: vec![Run { targets: Targets::Units, crates: vec![m("a")] }], part: None }; - let other = Shard { runs: vec![Run::all(vec![m("b"), m("c")]), Run { targets: Targets::Integration, crates: vec![m("a")] }], part: None }; - let (units, other) = (units.filterset(), other.filterset()); - for kind in ["lib", "proc-macro", "bin"] { - assert!(matches(&units, "a", kind) && !matches(&other, "a", kind), "a {kind}"); - } - assert!(!matches(&units, "a", "test") && matches(&other, "a", "test")); - for (package, kind) in [("b", "lib"), ("b", "test"), ("c", "bin")] { - assert!(matches(&other, package, kind) && !matches(&units, package, kind), "{package} {kind}"); - } - assert!(!matches(&other, "d", "lib")); - // In this workspace each test binary is in the archive of one shard, and a split's later - // parts take part 1's archive. - let meta = crate::metadata().unwrap(); - let ws = members(&meta).unwrap(); - let real = assign(GROUPS, &ws).unwrap(); - let mut binaries = 0; - for p in meta["packages"].as_array().unwrap().iter().filter(|p| ws.iter().any(|m| p["id"] == m.id.as_str())) { - let name = p["name"].as_str().unwrap(); - for target in p["targets"].as_array().unwrap().iter().filter(|t| t["test"] != false) { - let kinds: Vec<&str> = target["kind"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); - let kind = if kinds.contains(&"proc-macro") { - "proc-macro" - } else if kinds.iter().any(|k| k.ends_with("lib")) { - "lib" - } else if let [k @ ("bin" | "test")] = kinds.as_slice() { - k - } else { - continue; - }; - binaries += 1; - let owners: Vec<usize> = (0..real.len()) - .filter(|&i| real[i].part.is_none_or(|p| p.is_first()) && matches(&real[i].filterset(), name, kind)) - .map(|i| i + 1) - .collect(); - assert_eq!(owners.len(), 1, "{name}'s {kind} test binary is in the archive of shards {owners:?}"); - } - } - assert!(binaries > ws.len(), "{binaries} test binaries for {} members", ws.len()); - for (i, shard) in real.iter().enumerate() { - if let Some(p) = shard.part.filter(|p| !p.is_first()) { - assert_eq!(shard.filterset(), real[i + 1 - p.index].filterset(), "shard {}", i + 1); - } - } - } - fn m(name: &str) -> Member { Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into(), doctests: true } } From db476ae16830139f04dacf6de3544016ce6bb290 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 22:58:04 -0800 Subject: [PATCH 69/88] DXF/DWG import: hatch dots keep dashes' lengths; short spans and shifted curved gradients draw - A pattern of dashes and dots puts the dots on a path of their own with round caps, grouped with the dashes, which keep butt caps, so the dashes no longer grow into their gaps. - Pattern spans are dropped only when they have no length at the precision of their own coordinates, and each boundary loop is flattened to within its own size, so small loops far from the rest of a hatch keep their pattern lines and their curves. - The shift of a CURVED or INVCURVED gradient moves it up, as it moves the other named gradients. - A block whose pattern hatch draws its pattern no longer depends on the insert's linetype, and filled art no longer depends on its lineweight or linetype, so inserts that differ only in those share one symbol. A pattern hatch drawn as its boundary still takes the insert's linetype. - The dash clipping test crosses the boundary, and the inverse gradient test checks the stop counts. --- crates/cad/src/import/build.rs | 52 ++++++++++++-- crates/cad/src/import/hatch.rs | 123 ++++++++++++++++++++++++--------- crates/cad/src/import/tests.rs | 35 ++++++++++ 3 files changed, 172 insertions(+), 38 deletions(-) diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index c8dcedee90..b1e6683061 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -7,7 +7,7 @@ use std::collections::{HashMap, HashSet}; use std::rc::Rc; use std::sync::Arc; -use kurbo::BezPath; +use kurbo::{BezPath, PathEl}; use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Dash, Document, LAYER_COLORS, LayerColor, LineCap, Node, NodeKind, Symbol, TextObject}; use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect}; @@ -345,8 +345,13 @@ impl<'d, 'a> Build<'d, 'a> { for it in items.iter() { let p = &it.props; let on_zero = p.layer == "0"; - s |= p.color == Col::ByBlock || p.lineweight == Lw::ByBlock || p.linetype == "BYBLOCK" || p.alpha == Alpha::ByBlock; - s |= on_zero && (p.color == Col::ByLayer || p.lineweight == Lw::ByLayer || p.linetype == "BYLAYER"); + // Fills draw no stroke, and pattern lines carry their own dashes. + let filled = matches!(&it.geom, Geom::Path { fill: true, .. } | Geom::Shaded { shade: Shade::Gradient(_), .. }); + let stroked = !filled; + let in_linetype = !filled && !matches!(&it.geom, Geom::Shaded { shade: Shade::Pattern { .. }, .. }); + s |= p.color == Col::ByBlock || p.alpha == Alpha::ByBlock; + s |= (stroked && p.lineweight == Lw::ByBlock) || (in_linetype && p.linetype == "BYBLOCK"); + s |= on_zero && (p.color == Col::ByLayer || (stroked && p.lineweight == Lw::ByLayer) || (in_linetype && p.linetype == "BYLAYER")); if let Geom::Shaded { shade: Shade::Gradient(g), .. } = &it.geom { let inherited = |c| c == Col::ByBlock || (on_zero && c == Col::ByLayer); s |= inherited(g.first) || matches!(g.second, Second::Col(c) if inherited(c)); @@ -516,7 +521,7 @@ impl<'d, 'a> Build<'d, 'a> { let mut node = match &it.geom { Geom::Path { bp, fill, width } => self.path(bp, if *fill { Look::Fill } else { Look::Line }, *width, &it.props, map, inh)?, Geom::Shaded { bp, shade: Shade::Gradient(g) } => self.path(bp, Look::Gradient(g), 0.0, &it.props, map, inh)?, - Geom::Shaded { bp, shade: Shade::Pattern { dots } } => self.path(bp, Look::Pattern { dots: *dots }, 0.0, &it.props, map, inh)?, + Geom::Shaded { bp, shade: Shade::Pattern { dots } } => self.pattern(bp, *dots, &it.props, map, inh)?, Geom::Text(t) => self.text(t, &it.props, map, inh)?, Geom::Insert(ins) => return self.insert(ins, &it.props, map, inh, depth), }; @@ -525,6 +530,45 @@ impl<'d, 'a> Build<'d, 'a> { Some(node) } + /// Pattern hatch lines (`bp`, a move and a line per piece). With `dots`, the pieces of no + /// length go on a path of their own with round caps, grouped with the dashes, which keep + /// butt caps and their lengths. + fn pattern(&mut self, bp: &BezPath, dots: bool, p: &Props, map: Affine, inh: &Inherit) -> Option<Node> { + if !dots { + return self.path(bp, Look::Pattern { dots: false }, 0.0, p, map, inh); + } + let (mut dashes, mut points) = (BezPath::new(), BezPath::new()); + let mut from = None; + for el in bp.elements() { + match *el { + PathEl::MoveTo(a) => from = Some(a), + PathEl::LineTo(b) => { + if let Some(a) = from { + let out = if a == b { &mut points } else { &mut dashes }; + out.move_to(a); + out.line_to(b); + } + } + _ => {} + } + } + if dashes.elements().is_empty() { + return self.path(&points, Look::Pattern { dots: true }, 0.0, p, map, inh); + } + if points.elements().is_empty() { + return self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh); + } + // The two paths are objects of their own inside the group that `item` counts. + if self.nodes.saturating_add(2) >= MAX_NODES { + self.warn(TOO_MANY); + return None; + } + let lines = self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh)?; + let dots = self.path(&points, Look::Pattern { dots: true }, 0.0, p, map, inh)?; + self.nodes += 2; + Some(Node::group(self.doc.alloc_id(), vec![Arc::new(lines), Arc::new(dots)])) + } + /// A path painted as `look` says; `width`: a line's width in drawing units (0: the /// lineweight). fn path(&mut self, bp: &BezPath, look: Look<'_>, width: f64, p: &Props, map: Affine, inh: &Inherit) -> Option<Node> { diff --git a/crates/cad/src/import/hatch.rs b/crates/cad/src/import/hatch.rs index 506f595ba0..cc375424ba 100644 --- a/crates/cad/src/import/hatch.rs +++ b/crates/cad/src/import/hatch.rs @@ -22,10 +22,13 @@ const MAX_WORK: usize = 20_000_000; pub(crate) const MAX_TOTAL_PIECES: usize = if cfg!(test) { 1_000 } else { 2_000_000 }; /// The most clipping and dash steps all pattern hatches take together. pub(crate) const MAX_TOTAL_WORK: usize = if cfg!(test) { 200_000 } else { 200_000_000 }; -/// How far flattened boundary curves may stray, as a fraction of the boundary's larger side. +/// How far flattened boundary curves may stray, as a fraction of their loop's larger side. const FLATNESS: f64 = 1e-4; -/// Lengths below this fraction of the boundary's larger side count as none. +/// Line spacings and dash periods below this fraction of the boundary's larger side count as +/// none. const TINY: f64 = 1e-9; +/// Spans shorter than this many units of the last place of their coordinates count as none. +const LOCAL_TINY: f64 = 64.0 * f64::EPSILON; /// Why a pattern hatch is not drawn as its pattern. #[derive(Clone, Copy, Debug, PartialEq)] @@ -114,7 +117,7 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu if !(size > 0.0 && size.is_finite()) { return Ok((out, false)); } - let edges = edges(boundary, size * FLATNESS)?; + let edges = edges(boundary)?; if edges.is_empty() { return Ok((out, false)); } @@ -158,7 +161,8 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu let q = base + offset * k as f64; crossings(&edges, q, d, n, &mut t); for &[ta, tb] in t.as_chunks::<2>().0 { - if tb - ta <= tiny { + // Spans of no length at the precision of their own coordinates are dropped. + if tb - ta <= LOCAL_TINY * (q.to_vec2().hypot() + ta.abs().max(tb.abs())) { continue; } let mut emit = |s0: f64, s1: f64, budget: &mut Budget| -> Result<(), NoPattern> { @@ -202,10 +206,19 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu Ok((out, dots)) } -/// The boundary's edges as straight segments, each loop closed. -fn edges(boundary: &BezPath, tolerance: f64) -> Result<Vec<(Point, Point)>, NoPattern> { +/// The boundary's edges as straight segments, each loop closed and its curves flattened to +/// within [`FLATNESS`] of the loop's own size. Loops of no size are left out. +fn edges(boundary: &BezPath) -> Result<Vec<(Point, Point)>, NoPattern> { + let mut loops: Vec<BezPath> = Vec::new(); + for el in boundary.elements() { + if matches!(el, PathEl::MoveTo(_)) { + loops.push(BezPath::new()); + } + if let Some(l) = loops.last_mut() { + l.push(*el); + } + } let mut out = Vec::new(); - let (mut start, mut last) = (None::<Point>, None::<Point>); let mut over = false; let mut push = |a: Point, b: Point, out: &mut Vec<(Point, Point)>| { if out.len() >= MAX_EDGES { @@ -214,30 +227,35 @@ fn edges(boundary: &BezPath, tolerance: f64) -> Result<Vec<(Point, Point)>, NoPa out.push((a, b)); } }; - kurbo::flatten(boundary.iter(), tolerance, |el| match el { - PathEl::MoveTo(p) => { - if let (Some(s), Some(l)) = (start, last) { - push(l, s, &mut out); - } - start = Some(p); - last = Some(p); + for lp in &loops { + let Some(b) = super::curve::bounds(lp) else { continue }; + let tolerance = b.width().max(b.height()) * FLATNESS; + if !(tolerance > 0.0 && tolerance.is_finite()) { + continue; } - PathEl::LineTo(p) => { - if let Some(l) = last { - push(l, p, &mut out); + let (mut start, mut last) = (None::<Point>, None::<Point>); + kurbo::flatten(lp.iter(), tolerance, |el| match el { + PathEl::MoveTo(p) => { + start = Some(p); + last = Some(p); } - last = Some(p); - } - PathEl::ClosePath => { - if let (Some(s), Some(l)) = (start, last) { - push(l, s, &mut out); + PathEl::LineTo(p) => { + if let Some(l) = last { + push(l, p, &mut out); + } + last = Some(p); } - last = start; + PathEl::ClosePath => { + if let (Some(s), Some(l)) = (start, last) { + push(l, s, &mut out); + } + last = start; + } + _ => {} + }); + if let (Some(s), Some(l)) = (start, last) { + push(l, s, &mut out); } - _ => {} - }); - if let (Some(s), Some(l)) = (start, last) { - push(l, s, &mut out); } if over { Err(NoPattern::TooDense) } else { Ok(out) } } @@ -317,8 +335,8 @@ pub(crate) fn gradient(g: &model::Gradient, boundary: &BezPath, ocs: Affine, own let (w, h) = (r.width(), r.height()); let shift = if g.shift.is_finite() { g.shift.clamp(0.0, 1.0) } else { 0.0 }; let c = r.center() + Vec2::new(-w, h) * (shift / 4.0); - // How far the shift moves the center along the gradient (left). - let dx = c.x - r.center().x; + // How far the shift moves the center left and up. + let (dx, dy) = (c.x - r.center().x, c.y - r.center().y); let name = g.name.trim().to_uppercase(); let (inverse, name) = match name.strip_prefix("INV") { Some(rest) => (true, rest), @@ -331,10 +349,10 @@ pub(crate) fn gradient(g: &model::Gradient, boundary: &BezPath, ocs: Affine, own } "SPHERICAL" => (GradientKind::Radial, c, c + Vec2::new(w.max(h) / 2.0, 0.0), swap(&[(0.0, true), (1.0, false)])), "HEMISPHERICAL" => { - let center = Point::new(c.x, r.y0 + (c.y - r.center().y)); + let center = Point::new(c.x, r.y0 + dy); (GradientKind::Radial, center, center + Vec2::new((w / 2.0).max(h), 0.0), swap(&[(0.0, true), (1.0, false)])) } - "CURVED" => (GradientKind::Linear, Point::new(c.x, r.y0), Point::new(c.x, r.y1), swap(&[(0.0, true), (1.0, false)])), + "CURVED" => (GradientKind::Linear, Point::new(c.x, r.y0 + dy), Point::new(c.x, r.y1 + dy), swap(&[(0.0, true), (1.0, false)])), _ => (GradientKind::Linear, Point::new(r.x0 + dx, c.y), Point::new(r.x1 + dx, c.y), swap(&[(0.0, false), (1.0, true)])), }; let mut geom = GradientGeom { start, end, aspect: 1.0, focal: None }; @@ -461,11 +479,41 @@ mod tests { #[test] fn a_dash_across_the_boundary_is_cut_there() { - let (bp, _) = pattern(&[line(0.0, [0.0, 7.0], &[30.0, -10.0])], &square(35.0)).unwrap(); + let (bp, _) = pattern(&[line(0.0, [0.0, 7.0], &[30.0, -10.0])], &square(50.0)).unwrap(); let p = pieces(&bp); assert!(p.iter().any(|(a, b)| (a.x - 0.0).abs() < 1e-9 && (b.x - 30.0).abs() < 1e-9)); - // The second dash, 40 to 70, starts past the boundary at 35. - assert!(p.iter().all(|(_, b)| b.x <= 35.0 + 1e-9), "{p:?}"); + // The second dash, 40 to 70, crosses the boundary at 50 and stops there. + assert!(p.iter().any(|(a, b)| (a.x - 40.0).abs() < 1e-9 && (b.x - 50.0).abs() < 1e-9), "{p:?}"); + assert!(p.iter().all(|(_, b)| b.x <= 50.0 + 1e-9), "{p:?}"); + } + + #[test] + fn short_spans_far_apart_keep_their_pieces_and_curves() { + // Two strips 1 wide and 100 tall, 10 billion units apart: each level line keeps its + // one-unit spans. + let strip = |x: f64| { + let mut s = square(1.0); + s.apply_affine(Affine::translate((x, 0.0)) * Affine::scale_non_uniform(1.0, 100.0)); + s + }; + let mut boundary = strip(0.0); + boundary.extend(strip(1e10)); + let l = PatternLine { angle: 0.0, base: [0.0, 25.0], offset: [0.0, 50.0], dashes: vec![] }; + let (bp, _) = pattern(&[l.clone()], &boundary).unwrap(); + let p = pieces(&bp); + assert_eq!(p.len(), 4, "{p:?}"); + assert!(p.iter().all(|(a, b)| ((b.x - a.x) - 1.0).abs() < 1e-3), "{p:?}"); + // Unit circles as far apart keep their round outlines: the line through y 0.5 spans + // 2 * sqrt(0.75) of each. + let circle = |x: f64| kurbo::Shape::to_path(&kurbo::Circle::new((x, 0.0), 1.0), 0.1); + let mut boundary = circle(0.0); + boundary.extend(circle(1e10)); + let l = PatternLine { angle: 0.0, base: [0.0, 0.5], offset: [0.0, 100.0], dashes: vec![] }; + let (bp, _) = pattern(&[l], &boundary).unwrap(); + let p = pieces(&bp); + assert_eq!(p.len(), 2, "{p:?}"); + let chord = 2.0 * 0.75f64.sqrt(); + assert!(p.iter().all(|(a, b)| ((b.x - a.x).abs() - chord).abs() < chord * 1e-2), "{p:?}"); } #[test] @@ -532,6 +580,11 @@ mod tests { assert_eq!(g.stops, [(0.0, true), (1.0, false)], "the second color in the center"); let g = gradient(&grad("CYLINDER", 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap(); assert_eq!(g.geom.start.midpoint(g.geom.end), Point::new(50.0, 75.0)); + // A curved gradient runs bottom to top, so the shift moves it up. + for name in ["CURVED", "INVCURVED"] { + let g = gradient(&grad(name, 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap(); + assert_eq!((g.geom.start, g.geom.end), (Point::new(50.0, 25.0), Point::new(50.0, 125.0)), "{name}"); + } // A plane stretched twice as wide stretches the circle into an ellipse with it. let g = gradient(&grad("SPHERICAL", 0.0, 0.0), &square(10.0), Affine::scale_non_uniform(2.0, 1.0), Col::ByLayer).unwrap(); assert!((g.geom.aspect - 0.5).abs() < 1e-9 && g.geom.end.distance(Point::new(20.0, 5.0)) < 1e-9, "{:?}", g.geom); @@ -545,6 +598,8 @@ mod tests { let a = gradient(&grad(name, 0.0, 0.0), &square(10.0), Affine::IDENTITY, Col::ByLayer).unwrap(); let b = gradient(&grad(inv, 0.0, 0.0), &square(10.0), Affine::IDENTITY, Col::ByLayer).unwrap(); assert_eq!((a.kind, a.geom), (b.kind, b.geom), "{name}"); + let count = if name == "CYLINDER" { 3 } else { 2 }; + assert_eq!((a.stops.len(), b.stops.len()), (count, count), "{name}"); assert!(a.stops.iter().zip(&b.stops).all(|(x, y)| x.0 == y.0 && x.1 != y.1), "{name}: {:?} {:?}", a.stops, b.stops); } } diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index 9b692caa63..081c40fa5a 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -852,6 +852,25 @@ fn pattern_hatches_draw_their_lines_inside_the_boundary() { let r = open(&entities(&pattern_hatch("CONTINUOUS", &[(79, "2"), (49, "0"), (49, "-5")])), &points()); let [dots] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; assert!(dots.appearance.stroke().is_some_and(|s| s.cap == LineCap::Round), "{:?}", r.warnings); + // Dashes and dots together: the dots take round caps on a path of their own, and the dashes + // keep butt caps, so they do not grow into their gaps. + let mixed = [(79, "4"), (49, "3"), (49, "-2"), (49, "0"), (49, "-5")]; + let r = open(&entities(&pattern_hatch("CONTINUOUS", &mixed)), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [hatch_art] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let [dashes, dots] = &hatch_art.children().unwrap()[..] else { panic!("dashes and dots: {:?}", hatch_art.kind) }; + assert!(dashes.appearance.stroke().is_some_and(|s| s.cap != LineCap::Round)); + assert!(dots.appearance.stroke().is_some_and(|s| s.cap == LineCap::Round)); + let length = |n: &Node| { + let pts = path_points(n); + pts[0].distance(*pts.last().unwrap()) + }; + let pieces = |n: &Node| match &n.kind { + NodeKind::Compound { children, .. } => children.iter().map(|c| (**c).clone()).collect(), + _ => vec![n.clone()], + }; + assert!(pieces(dashes).iter().all(|c| length(c) > 1e-9), "no dots among the dashes"); + assert!(pieces(dots).iter().all(|c| length(c) < 1e-9), "only dots"); // Without its pattern lines a pattern hatch still comes in as its boundary, with a note. let r = open(&entities(&hatch("0")), &points()); assert!(r.warnings.iter().any(|w| w.contains("without usable pattern lines")), "{:?}", r.warnings); @@ -981,6 +1000,22 @@ fn block_gradient_stops_keep_the_inserts_color() { } } +#[test] +fn block_pattern_hatches_ignore_the_inserts_linetype() { + let inserts = [(0, "INSERT"), (2, "Door"), (62, "1"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Door"), (62, "3"), (10, "200"), (20, "0")]; + // Pattern lines draw without a linetype: inserts of other colors share one symbol. + let mut lines = pattern_hatch("BYBLOCK", &[]); + lines.splice(1..1, [(8, "Doors"), (370, "25")]); + let r = open(&with_door(&lines, &inserts), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert_eq!(r.document.symbols.len(), 1); + // A pattern hatch drawn as its boundary strokes it in the insert's linetype. + let mut boundary = hatch("0"); + boundary.splice(1..1, [(8, "Doors"), (370, "25"), (6, "BYBLOCK")]); + let r = open(&with_door(&boundary, &inserts), &points()); + assert_eq!(r.document.symbols.len(), 2, "{:?}", r.warnings); +} + #[test] fn hatch_declaring_many_absent_source_handles_parses_quickly() { let base = hatch("1"); From 3b4530af42824c7919eec081d21d7490a429cdbf Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 23:43:37 -0800 Subject: [PATCH 70/88] DXF/DWG import: close pattern lines far apart draw; far gradients keep their fill - Pattern line spacings and dash periods are refused only when they are below the precision of the boundary's coordinates, or when the lines and dashes that actually cross the boundary exceed the per-hatch limits. Two small areas far apart no longer refuse a fine pattern. - A line family based far from the boundary is moved to the line nearest it by whole offsets (and its dashes by whole periods), so its line indices fit and each line keeps its dash phase. - A dot that ends the period before a span's start is drawn on the span's start. - A pattern of dashes and dots is checked for every object and path point it makes before either path is made, and charges nothing when it is left out. - A gradient hatch whose gradient reaches past the coordinate limit keeps its gradient when its boundary is in range; a gradient that cannot be placed becomes a solid fill. - The dense-pattern warning and docs/mcp.md name the edge and work limits, and docs/mcp.md says when island styles fall back to filling every loop. - Tests check which loops each island style keeps and that a block's boundary fallback takes each insert's linetype. - Fixes the clippy cloned_ref_to_slice_refs error in the hatch tests. --- crates/cad/src/import/build.rs | 80 ++++++++++++++++++++++-- crates/cad/src/import/entity.rs | 28 ++++++--- crates/cad/src/import/hatch.rs | 105 +++++++++++++++++++++++++++----- crates/cad/src/import/tests.rs | 86 ++++++++++++++++++++++++-- docs/mcp.md | 7 ++- 5 files changed, 272 insertions(+), 34 deletions(-) diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index b1e6683061..82d2a6deb9 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -538,15 +538,17 @@ impl<'d, 'a> Build<'d, 'a> { return self.path(bp, Look::Pattern { dots: false }, 0.0, p, map, inh); } let (mut dashes, mut points) = (BezPath::new(), BezPath::new()); + let (mut dash_count, mut dot_count) = (0usize, 0usize); let mut from = None; for el in bp.elements() { match *el { PathEl::MoveTo(a) => from = Some(a), PathEl::LineTo(b) => { if let Some(a) = from { - let out = if a == b { &mut points } else { &mut dashes }; + let (out, count) = if a == b { (&mut points, &mut dot_count) } else { (&mut dashes, &mut dash_count) }; out.move_to(a); out.line_to(b); + *count += 1; } } _ => {} @@ -558,13 +560,25 @@ impl<'d, 'a> Build<'d, 'a> { if points.elements().is_empty() { return self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh); } - // The two paths are objects of their own inside the group that `item` counts. - if self.nodes.saturating_add(2) >= MAX_NODES { + // Every object the split makes: the group (`item` counts it), the two paths, and each + // piece of a path with more than one (`path` counts those). + let loops = |count: usize| if count > 1 { count } else { 0 }; + if loops(dash_count).saturating_add(loops(dot_count)).saturating_add(3) > MAX_NODES.saturating_sub(self.nodes) { self.warn(TOO_MANY); return None; } - let lines = self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh)?; - let dots = self.path(&points, Look::Pattern { dots: true }, 0.0, p, map, inh)?; + if dashes.elements().len().saturating_add(points.elements().len()) > MAX_ELEMENTS.saturating_sub(self.elements) { + self.warn(TOO_MANY_POINTS); + return None; + } + // A split that loses either path is left out whole, and charges nothing. + let (nodes, elements) = (self.nodes, self.elements); + let lines = self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh); + let dots = lines.as_ref().and_then(|_| self.path(&points, Look::Pattern { dots: true }, 0.0, p, map, inh)); + let (Some(lines), Some(dots)) = (lines, dots) else { + (self.nodes, self.elements) = (nodes, elements); + return None; + }; self.nodes += 2; Some(Node::group(self.doc.alloc_id(), vec![Arc::new(lines), Arc::new(dots)])) } @@ -833,3 +847,59 @@ fn unique(base: &str, next: &mut HashMap<String, usize>, taken: &HashSet<String> } } } + +#[cfg(test)] +mod tests { + use super::*; + + const EMPTY: &[u8] = b" 0\nSECTION\n 2\nENTITIES\n 0\nENDSEC\n 0\nEOF\n"; + + fn props() -> Props { + Props { + layer: "0".into(), + color: Col::Rgb([0, 0, 0]), + lineweight: Lw::Default, + linetype: "CONTINUOUS".into(), + ltscale: 1.0, + alpha: Alpha::Opacity(1.0), + } + } + + /// Two dashes and two dots: the group, its two paths and four pieces, in 8 path elements. + fn mixed() -> BezPath { + let mut bp = BezPath::new(); + for (a, b) in [((0.0, 0.0), (1.0, 0.0)), ((0.0, 1.0), (1.0, 1.0)), ((2.0, 0.0), (2.0, 0.0)), ((2.0, 1.0), (2.0, 1.0))] { + bp.move_to(a); + bp.line_to(b); + } + bp + } + + #[test] + fn mixed_patterns_fit_every_object_and_point_or_charge_nothing() { + let (tags, _) = super::super::tags(EMPTY).unwrap(); + let d = Drawing::read(craft_dxf::model::Document::read(&tags)); + let o = ImportOptions::default(); + let (p, inh) = (props(), Inherit::default()); + // Seven objects with six slots free: refused; with seven: drawn, the group left to `item`. + let mut b = Build::new(&d, &o); + b.nodes = MAX_NODES - 6; + assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_none()); + assert_eq!(b.nodes, MAX_NODES - 6); + b.nodes = MAX_NODES - 7; + assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_some()); + assert_eq!(b.nodes, MAX_NODES - 1); + // Eight points with seven left: refused without charging them, so a 4-point path that + // follows still fits. + let mut b = Build::new(&d, &o); + b.elements = MAX_ELEMENTS - 7; + assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_none()); + assert_eq!(b.elements, MAX_ELEMENTS - 7); + let mut line = BezPath::new(); + line.move_to((0.0, 0.0)); + line.line_to((1.0, 0.0)); + line.line_to((1.0, 1.0)); + line.line_to((0.0, 1.0)); + assert!(b.path(&line, Look::Line, 0.0, &p, Affine::IDENTITY, &inh).is_some()); + } +} diff --git a/crates/cad/src/import/entity.rs b/crates/cad/src/import/entity.rs index 3bfecbf61d..3e3ddd26d3 100644 --- a/crates/cad/src/import/entity.rs +++ b/crates/cad/src/import/entity.rs @@ -203,7 +203,8 @@ pub(crate) struct Converter { } const PATTERN_HATCH: &str = "pattern hatches without usable pattern lines come in as their boundaries"; -const DENSE_PATTERN: &str = "pattern hatches of more than 20,000 dashes come in as their boundaries"; +const DENSE_PATTERN: &str = + "pattern hatches of more than 20,000 dashes, 200,000 boundary edges or 20,000,000 clipping steps come in as their boundaries"; const MANY_PATTERNS: &str = "the drawing's pattern hatches have more than 2,000,000 dashes in all: the rest come in as their boundaries"; const MUCH_PATTERN_WORK: &str = "the drawing's pattern hatches take too much work to clip: the rest come in as their boundaries"; const MUCH_ISLAND_WORK: &str = "hatches with too many boundary points to sort into islands are filled as if every loop were a boundary"; @@ -240,7 +241,7 @@ impl Converter { if !m.common.visible { continue; } - match self.geom(e, &m) { + match self.geom(e, &m).map(usable_paint) { Some(geom) if !in_range(&geom) => self.warn(FAR_AWAY), Some(geom) => out.push(Item { props: Props::read(&m.common), geom }), None if is_known(e.kind) => {} @@ -581,7 +582,23 @@ impl Converter { } } -/// Is the geometry within [`MAX_COORD`] of the origin? +/// A gradient hatch whose gradient cannot be placed (numbers out of range) as a solid fill. +fn usable_paint(g: Geom) -> Geom { + match g { + Geom::Shaded { bp, shade: Shade::Gradient(grad) } => { + let geom = &grad.geom; + let finite = |p: Point| p.x.is_finite() && p.y.is_finite(); + if finite(geom.start) && finite(geom.end) && geom.aspect.is_finite() && geom.focal.is_none_or(finite) { + Geom::Shaded { bp, shade: Shade::Gradient(grad) } + } else { + Geom::Path { bp, fill: true, width: 0.0 } + } + } + g => g, + } +} + +/// Is the geometry within [`MAX_COORD`] of the origin? A gradient's handles may lie beyond it. fn in_range(g: &Geom) -> bool { let near = |p: Point| p.x.abs() <= MAX_COORD && p.y.abs() <= MAX_COORD; let origin = |m: &Affine| near(m.translation().to_point()); @@ -589,10 +606,7 @@ fn in_range(g: &Geom) -> bool { Geom::Path { bp, width, .. } => { curve::bounds(bp).is_some_and(|b| near(Point::new(b.x0, b.y0)) && near(Point::new(b.x1, b.y1))) && *width <= MAX_COORD } - Geom::Shaded { bp, shade } => { - let far = matches!(shade, Shade::Gradient(g) if !near(g.geom.start) || !near(g.geom.end) || !g.geom.aspect.is_finite()); - !far && curve::bounds(bp).is_some_and(|b| near(Point::new(b.x0, b.y0)) && near(Point::new(b.x1, b.y1))) - } + Geom::Shaded { bp, .. } => curve::bounds(bp).is_some_and(|b| near(Point::new(b.x0, b.y0)) && near(Point::new(b.x1, b.y1))), Geom::Text(t) => origin(&t.xf) && t.height <= MAX_COORD, Geom::Insert(i) => i.cells.iter().all(|m| origin(m) && m.as_coeffs().iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)), } diff --git a/crates/cad/src/import/hatch.rs b/crates/cad/src/import/hatch.rs index cc375424ba..3457fa4527 100644 --- a/crates/cad/src/import/hatch.rs +++ b/crates/cad/src/import/hatch.rs @@ -24,10 +24,8 @@ pub(crate) const MAX_TOTAL_PIECES: usize = if cfg!(test) { 1_000 } else { 2_000_ pub(crate) const MAX_TOTAL_WORK: usize = if cfg!(test) { 200_000 } else { 200_000_000 }; /// How far flattened boundary curves may stray, as a fraction of their loop's larger side. const FLATNESS: f64 = 1e-4; -/// Line spacings and dash periods below this fraction of the boundary's larger side count as -/// none. -const TINY: f64 = 1e-9; -/// Spans shorter than this many units of the last place of their coordinates count as none. +/// Spans, line spacings and dash periods shorter than this many units of the last place of their +/// coordinates count as none. const LOCAL_TINY: f64 = 64.0 * f64::EPSILON; /// Why a pattern hatch is not drawn as its pattern. @@ -35,7 +33,8 @@ const LOCAL_TINY: f64 = 64.0 * f64::EPSILON; pub(crate) enum NoPattern { /// The hatch holds no pattern lines. Undefined, - /// Drawing it would take more than [`MAX_PIECES`] pieces or [`MAX_WORK`] steps. + /// Drawing it would take more than [`MAX_PIECES`] pieces, [`MAX_EDGES`] boundary edges or + /// [`MAX_WORK`] steps. TooDense, /// The drawing reaches its total piece limit. DrawingPieces, @@ -122,7 +121,9 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu return Ok((out, false)); } let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)]; - let tiny = size * TINY; + let center = b.center(); + // The precision of the boundary's coordinates: spacings and periods below it draw nothing apart. + let tiny = LOCAL_TINY * center.to_vec2().hypot().max(size); let (mut work, mut pieces, mut dots, mut usable) = (0usize, 0usize, false, false); for l in lines { let a = l.angle.to_radians(); @@ -136,10 +137,26 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu continue; } usable = true; - // Lines no distance apart, or as good as none, fill the area past what can be drawn. + // Lines no distance apart, or closer than the coordinates can tell apart, fill the area + // past what can be drawn. if step.abs() <= tiny { return Err(NoPattern::TooDense); } + let period: f64 = l.dashes.iter().map(|v| v.abs()).sum(); + if !l.dashes.is_empty() && period <= tiny { + return Err(NoPattern::TooDense); + } + // The same family from the line nearest the boundary's center: a whole number of offsets + // along, so each line keeps its dashes' phase, and then a whole number of dash periods + // along the line. + let (across, along) = ((base - center).dot(n), (base - center).dot(d)); + let shift = -(across / step).round(); + let across = across + shift * step; + let along = if l.dashes.is_empty() { 0.0 } else { (along + shift * offset.dot(d)).rem_euclid(period) }; + if !(across.is_finite() && along.is_finite()) { + continue; + } + let base = center + n * across + d * along; // The lines crossing the boundary's box: base + k * offset for whole k. let h = corners.map(|c| (c - base).dot(n) / step); let lo = h.iter().copied().fold(f64::INFINITY, f64::min).ceil(); @@ -151,10 +168,6 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu if count * (edges.len() as f64) + work as f64 > MAX_WORK as f64 { return Err(NoPattern::TooDense); } - let period: f64 = l.dashes.iter().map(|v| v.abs()).sum(); - if !l.dashes.is_empty() && period <= tiny { - return Err(NoPattern::TooDense); - } let mut t = Vec::new(); for k in (lo as i64)..=(hi as i64) { budget.work(&mut work, edges.len())?; @@ -175,9 +188,19 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu emit(ta, tb, budget)?; continue; } - // The dashes run from the line's base point: the first period that reaches the - // span, element by element. + // The dashes run from the line's base point, element by element, from the period + // before the one the span starts in, so a dot that ends that period (on the span's + // start) is kept. let mut at = (ta / period).floor() * period; + if at >= ta { + at -= period; + } + // Periods too short to move along the span, or more dashes than one hatch may + // look at, are refused before any of them is looked at. + let steps = ((tb - at) / period + 1.0) * l.dashes.len() as f64; + if period <= LOCAL_TINY * at.abs().max(tb.abs()) || steps + work as f64 > MAX_WORK as f64 { + return Err(NoPattern::TooDense); + } 'span: loop { for v in &l.dashes { if at > tb { @@ -499,7 +522,7 @@ mod tests { let mut boundary = strip(0.0); boundary.extend(strip(1e10)); let l = PatternLine { angle: 0.0, base: [0.0, 25.0], offset: [0.0, 50.0], dashes: vec![] }; - let (bp, _) = pattern(&[l.clone()], &boundary).unwrap(); + let (bp, _) = pattern(std::slice::from_ref(&l), &boundary).unwrap(); let p = pieces(&bp); assert_eq!(p.len(), 4, "{p:?}"); assert!(p.iter().all(|(a, b)| ((b.x - a.x) - 1.0).abs() < 1e-3), "{p:?}"); @@ -516,6 +539,54 @@ mod tests { assert!(p.iter().all(|(a, b)| ((b.x - a.x).abs() - chord).abs() < chord * 1e-2), "{p:?}"); } + #[test] + fn close_lines_across_squares_far_apart_are_drawn() { + // Two unit squares 10 billion units apart, lines 0.5 apart: two lines cross each square. + let mut boundary = square(1.0); + let mut far = square(1.0); + far.apply_affine(Affine::translate((1e10, 0.0))); + boundary.extend(far); + let (bp, _) = pattern(&[line(0.0, [0.0, 0.5], &[])], &boundary).unwrap(); + assert_eq!(pieces(&bp).len(), 4, "{:?}", pieces(&bp)); + // Dashes 0.25 long with 0.25 gaps: two per line in each square. + let (bp, _) = pattern(&[line(0.0, [0.0, 0.5], &[0.25, -0.25])], &boundary).unwrap(); + assert_eq!(pieces(&bp).len(), 8, "{:?}", pieces(&bp)); + } + + #[test] + fn families_based_far_away_draw_the_same_lines() { + // Lines one apart from a base 1e19 up are the lines one apart from the origin. + let mut far = line(0.0, [0.0, 1.0], &[]); + far.base = [0.0, 1e19]; + let (bp, _) = pattern(&[far], &square(100.0)).unwrap(); + let p = pieces(&bp); + assert_eq!(p.len(), 100, "{p:?}"); + assert!(p.iter().all(|(a, b)| a.y == b.y && a.y.fract() == 0.0 && (0.0..100.0).contains(&a.y)), "{p:?}"); + // A staggered family based 100 lines away keeps each line's dash phase. + let mut near = line(0.0, [5.0, 10.0], &[3.0, -7.0]); + near.base = [-497.0, 0.0]; + let mut away = near.clone(); + away.base = [3.0, 1000.0]; + let sorted = |l: PatternLine| { + let mut p = pieces(&pattern(&[l], &square(100.0)).unwrap().0); + p.sort_by(|a, b| (a.0.y, a.0.x).partial_cmp(&(b.0.y, b.0.x)).unwrap_or(std::cmp::Ordering::Equal)); + p + }; + let (a, b) = (sorted(near), sorted(away)); + assert_eq!(a.len(), b.len()); + assert!(!a.is_empty()); + assert!(a.iter().zip(&b).all(|(x, y)| x.0.distance(y.0) < 1e-9 && x.1.distance(y.1) < 1e-9), "{a:?} {b:?}"); + } + + #[test] + fn a_dot_on_the_start_of_a_span_is_kept() { + // A gap of 5 then a dot, from x 0: dots at 0, 5 and 10 on the line along the bottom. + let (bp, dots) = pattern(&[line(0.0, [0.0, 20.0], &[-5.0, 0.0])], &square(10.0)).unwrap(); + assert!(dots); + let xs: Vec<f64> = pieces(&bp).iter().filter(|(a, _)| a.y == 0.0).map(|(a, _)| a.x).collect(); + assert_eq!(xs, [0.0, 5.0, 10.0]); + } + #[test] fn slanted_lines_fill_a_square_evenly() { // 45 degree lines 1 apart across the square's diagonal of 14.1: each piece runs from one @@ -536,9 +607,13 @@ mod tests { // Few lines, but dashes far shorter than the square: more pieces than allowed. assert_eq!(pattern(&[line(0.0, [0.0, 10.0], &[0.01, -0.01])], &square(1000.0)), Err(NoPattern::TooDense)); // A tiny nonempty dash period is too dense; only an empty list draws continuous lines. - // It is refused before any line is clipped or dashed. + // It is refused once the first line is clipped, before any of its dashes is looked at. let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None }; assert_eq!(super::pattern(&[line(0.0, [0.0, 1.0], &[-1e-12])], &square(10.0), &mut budget), Err(NoPattern::TooDense)); + assert_eq!(budget.work, usize::MAX - 4, "one line clipped against four edges, no dashes looked at"); + // A period below the coordinates' precision is refused before any line is clipped. + let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None }; + assert_eq!(super::pattern(&[line(0.0, [0.0, 1.0], &[-1e-15])], &square(10.0), &mut budget), Err(NoPattern::TooDense)); assert_eq!(budget.work, usize::MAX, "no work done"); let (bp, _) = pattern(&[line(0.0, [0.0, 1.0], &[])], &square(10.0)).unwrap(); assert!(!pieces(&bp).is_empty()); diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index 081c40fa5a..2731979702 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -568,19 +568,25 @@ fn hatch_island_styles_select_nested_boundary_levels() { ]); } e.splice(count + 1..end, loops); - for (style, expected) in [("0", 3), ("1", 2), ("2", 1), ("3", 3)] { + // The sides of the squares each style keeps: normal and unknown styles all three, outer the + // outermost and middle ones, ignore the outermost alone. + for (style, expected) in [("0", &[20.0, 60.0, 100.0][..]), ("1", &[60.0, 100.0]), ("2", &[100.0]), ("3", &[20.0, 60.0, 100.0])] { *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, style); let r = open(&entities(&e), &points()); assert!(r.warnings.is_empty(), "style {style}: {:?}", r.warnings); let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; - let count = match &area.kind { + let mut sides: Vec<f64> = match &area.kind { NodeKind::Compound { children, rule } => { assert_eq!(*rule, FillRule::EvenOdd); - children.len() + children.iter().map(|c| bounds(c).width().round()).collect() + } + _ => { + assert_eq!(area.path_data().unwrap().subpaths.len(), 1); + vec![bounds(area).width().round()] } - _ => area.path_data().unwrap().subpaths.len(), }; - assert_eq!(count, expected, "boundary loops for island style {style}"); + sides.sort_by(f64::total_cmp); + assert_eq!(sides, expected, "boundary loops for island style {style}"); assert!(area.appearance.fill().is_some_and(|f| !f.paint.is_none())); } } @@ -1000,6 +1006,57 @@ fn block_gradient_stops_keep_the_inserts_color() { } } +#[test] +fn gradient_hatches_far_out_keep_their_fill() { + // A sphere hatch on a strip 10 wide ending 1e12 out: its circle reaches past 1e12, and the + // strip still comes in, centered on the artboard. + let mut e = vec![(0, "HATCH"), (62, "1"), (10, "0"), (20, "0"), (30, "0"), (2, "SOLID"), (70, "1"), (71, "0"), (91, "1")]; + e.extend([(92, "3"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in [("999999999990", "0"), ("1000000000000", "0"), ("1000000000000", "100"), ("999999999990", "100")] { + e.extend([(10, x), (20, y)]); + } + e.extend([(97, "0"), (75, "0"), (76, "1"), (98, "0")]); + e.extend([(450, "1"), (451, "0"), (452, "0"), (453, "2"), (460, "0"), (461, "0")]); + e.extend([(462, "0"), (463, "0"), (63, "1"), (463, "1"), (63, "5"), (470, "SPHERICAL")]); + let r = open(&entities(&e), &ImportOptions { center: true, ..points() }); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + assert_eq!(gradient_of(area).gradient.kind, vectorcraft_color::GradientKind::Radial); + assert_eq!(bounds(area).width().round(), 10.0); +} + +/// [`with_door`] with a dashed linetype `DASHED` in the drawing. +fn with_dashed_door(block_art: &[(i32, &'static str)], inserts: &[(i32, &'static str)]) -> Vec<u8> { + let mut blocks = vec![(0, "BLOCK"), (8, "0"), (2, "Door"), (70, "0"), (10, "5"), (20, "5"), (3, "Door")]; + blocks.extend_from_slice(block_art); + blocks.push((0, "ENDBLK")); + let tables = [ + (0, "TABLE"), + (2, "LTYPE"), + (0, "LTYPE"), + (2, "DASHED"), + (73, "2"), + (40, "15"), + (49, "10"), + (49, "-5"), + (0, "ENDTAB"), + (0, "TABLE"), + (2, "LAYER"), + (0, "LAYER"), + (2, "Doors"), + (70, "0"), + (62, "5"), + (6, "CONTINUOUS"), + (0, "ENDTAB"), + ]; + drawing(&[], &tables, &blocks, inserts) +} + +/// Whether `n` or any object inside it has a dashed stroke. +fn dashed(n: &Node) -> bool { + n.appearance.stroke().is_some_and(|s| s.dash.is_some()) || n.children().is_some_and(|c| c.iter().any(|c| dashed(c))) +} + #[test] fn block_pattern_hatches_ignore_the_inserts_linetype() { let inserts = [(0, "INSERT"), (2, "Door"), (62, "1"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Door"), (62, "3"), (10, "200"), (20, "0")]; @@ -1014,6 +1071,25 @@ fn block_pattern_hatches_ignore_the_inserts_linetype() { boundary.splice(1..1, [(8, "Doors"), (370, "25"), (6, "BYBLOCK")]); let r = open(&with_door(&boundary, &inserts), &points()); assert_eq!(r.document.symbols.len(), 2, "{:?}", r.warnings); + + // Inserts of one color, one dashed and one continuous. + let inserts = + [(0, "INSERT"), (2, "Door"), (6, "DASHED"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Door"), (6, "CONTINUOUS"), (10, "200"), (20, "0")]; + let r = open(&with_dashed_door(&lines, &inserts), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [symbol] = &r.document.symbols[..] else { panic!("one symbol for both linetypes") }; + assert!(!dashed(&symbol.art), "pattern lines carry no linetype dashes"); + // The boundary drawn for each insert takes that insert's linetype. + let r = open(&with_dashed_door(&boundary, &inserts), &points()); + assert_eq!(r.document.symbols.len(), 2, "{:?}", r.warnings); + let looks: Vec<bool> = leaves(&r.document) + .iter() + .map(|n| { + let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { panic!("{:?}", n.kind) }; + dashed(&r.document.symbols.iter().find(|s| s.name == *symbol).unwrap().art) + }) + .collect(); + assert_eq!(looks, [true, false], "the dashed insert's boundary is dashed, the continuous one's is not"); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 323cc769d6..5ee73290d0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12893,10 +12893,13 @@ artboard under `at`). `center: false` puts the drawing's origin (fitted art: its artboard's bottom-left corner; `mergeLayers` puts all art on one layer. Each DXF layer holding art becomes a layer (off and frozen layers hidden, locked ones locked, non-plotting ones non-printing). Lines, polylines (arc segments from bulges), circles, arcs, ellipses, splines (NURBS, within a millionth of their size), solids and hatches become paths (solid -hatches filled; hatches follow their island style (normal, outer, ignore); gradient hatches filled with a linear or +hatches filled; hatches follow their island style (normal, outer, ignore), except that a hatch with too many boundary +points to sort into islands is filled as if every loop were a boundary, with a warning, so an ignore-style hatch can +keep its holes; gradient hatches filled with a linear or radial gradient at their angle, in their two colors or one color shaded or tinted; pattern hatches as their pattern's lines clipped to the boundary, each cut into its dashes and dots and stroked at the lineweight without the linetype; a pattern hatch with no usable pattern lines, with more -than 20,000 dashes, or past the drawing's budget of 2,000,000 dashes or 200,000,000 clipping steps, as its boundary), +than 20,000 dashes, 200,000 boundary edges or 20,000,000 clipping and dash steps, or past the drawing's budget of +2,000,000 dashes or 200,000,000 clipping steps, as its boundary), text and multiline text point type, named blocks symbols (one per look when their art takes colour "by block"), anonymous blocks such as dimensions groups. 3D faces, polyface meshes and polygon meshes are seen from above, their height dropped: a 3D face or a polyface mesh's face becomes the From fb3f2d545f0fef310e83bc4c50b6552fb020cdf2 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 4 Dec 2026 23:58:57 -0800 Subject: [PATCH 71/88] CI: the build job runs each shard's doctests in a command of its own `cargo xtask ci doctests` ran the doctests of every workspace member in one `cargo test --doc`, which resolves features over all of them and rebuilt the libraries the per-shard builds had built: the step took 24 minutes in the build job of pull request run 47488581650. It now runs one `cargo test --doc` per shard with the crates `ci shard` runs them for. On the build host, after `ci archive`, the step took 34 seconds. --- xtask/src/main.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 73a47429ba..2ec7e394b5 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -56,7 +56,7 @@ commands: ci archive build every shard's tests once and write shard k's nextest archive to $NEXTEST_ARCHIVE_DIR/<k>/$NEXTEST_ARCHIVE_NAME for k from 1 to $GATE_SHARDS; with CRAFT_CACHE_UNITS set, appends Cargo's JSON messages for the build to that file - ci doctests the workspace doctests + ci doctests the doctests of each shard's crates, one cargo command per shard ci checks the ci steps other than the tests, the doctests and the i18n report shards list the crates each shard tests; fails when a member is in no shard or in two, or builds with other features in its shard than in the whole workspace @@ -99,7 +99,7 @@ fn main() -> ExitCode { Some("test") => cmd_test().and_then(|()| cmd_doctests()), Some("ci") if rest.first() == Some(&"shard") => cmd_ci_shard(), Some("ci") if rest.first() == Some(&"archive") => cmd_ci_archive(), - Some("ci") if rest.first() == Some(&"doctests") => cmd_doctests(), + Some("ci") if rest.first() == Some(&"doctests") => cmd_ci_doctests(), Some("ci") if rest.first() == Some(&"checks") => cmd_ci_checks(), Some("ci") => cmd_ci(), Some("shards") => shards::run().map(drop), @@ -540,6 +540,17 @@ fn test_build(r: &shards::Run, units: bool) -> (Command, String) { (c, format!("cargo test {} --no-run ({})", targets.shown(), shards::names(&r.crates))) } +/// `cargo xtask ci doctests`: the doctests of each shard's crates, one cargo command per shard +/// with the crates `ci shard` runs them for, after `ci archive` (the shared gate's +/// `after-archive-command`). Every command runs before the first error is returned. +fn cmd_ci_doctests() -> Result<(), String> { + let mut result = Ok(()); + for s in shards::assigned()?.iter().filter(|s| s.part.is_none_or(|p| p.is_first())) { + result = result.and(doctest_packages(&shards::unit_crates(&s.runs))); + } + result +} + /// `cargo xtask ci checks`: every `ci` step other than [`TEST_STEPS`], for the shared gate's /// `lint` leg. fn cmd_ci_checks() -> Result<(), String> { From 28776f1903c1697acfe3beb3f93b7e5b04f4e88a Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 00:25:31 -0800 Subject: [PATCH 72/88] DXF/DWG import: far pattern bases keep their phase; long dash periods draw A pattern family based far from the boundary lost the fraction of the boundary's center: base minus center rounded to the base, so a family based 1e19 away drew its lines through the center instead of at whole offsets. The base and the center are now each measured from the line through the origin before the offset count is taken. Each pattern line is now measured from its point nearest the boundary's center, with its dash start as a signed distance within one period. A dash period far longer than the boundary (dashes 1e16 long) left the line's origin about 2e16 away, where the span tolerance dropped every span and the hatch drew nothing. The elements that end the period before a span are measured back from that period's end, so a long period no longer moves a dash's start. --- crates/cad/src/import/hatch.rs | 121 +++++++++++++++++++++++++-------- 1 file changed, 91 insertions(+), 30 deletions(-) diff --git a/crates/cad/src/import/hatch.rs b/crates/cad/src/import/hatch.rs index 3457fa4527..1bc3e323f4 100644 --- a/crates/cad/src/import/hatch.rs +++ b/crates/cad/src/import/hatch.rs @@ -146,18 +146,33 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu if !l.dashes.is_empty() && period <= tiny { return Err(NoPattern::TooDense); } - // The same family from the line nearest the boundary's center: a whole number of offsets - // along, so each line keeps its dashes' phase, and then a whole number of dash periods - // along the line. - let (across, along) = ((base - center).dot(n), (base - center).dot(d)); - let shift = -(across / step).round(); - let across = across + shift * step; - let along = if l.dashes.is_empty() { 0.0 } else { (along + shift * offset.dot(d)).rem_euclid(period) }; + // The same family from the line nearest the boundary's center, a whole number of offsets + // away. The base and the center are each measured from the line through the origin + // first, so a base far away keeps the fraction of the center's position. + let (bn, cn) = (base.to_vec2().dot(n), center.to_vec2().dot(n)); + let (to_origin, to_center) = (-(bn / step).round(), (cn / step).round()); + let across = (bn + to_origin * step) + (to_center * step - cn); + let last = -(across / step).round(); + let across = across + last * step; + // Where the dashes start on that line, from its point nearest the center. Each line is + // measured from its own point nearest the center, so its spans stay near the boundary + // however long the dash period is. + let along = if l.dashes.is_empty() { + 0.0 + } else { + let bd = base.to_vec2().dot(d) + to_origin * offset.dot(d); + bd + ((to_center + last) * offset.dot(d) - center.to_vec2().dot(d)) + }; if !(across.is_finite() && along.is_finite()) { continue; } - let base = center + n * across + d * along; - // The lines crossing the boundary's box: base + k * offset for whole k. + // The dash start nearest a line's point nearest the center, as a signed distance. + let phase = |k: f64| { + let s = along + k * offset.dot(d); + s - period * (s / period).round() + }; + let base = center + n * across; + // The lines crossing the boundary's box: base + k * step along the normal for whole k. let h = corners.map(|c| (c - base).dot(n) / step); let lo = h.iter().copied().fold(f64::INFINITY, f64::min).ceil(); let hi = h.iter().copied().fold(f64::NEG_INFINITY, f64::max).floor(); @@ -171,7 +186,7 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu let mut t = Vec::new(); for k in (lo as i64)..=(hi as i64) { budget.work(&mut work, edges.len())?; - let q = base + offset * k as f64; + let q = base + n * (step * k as f64); crossings(&edges, q, d, n, &mut t); for &[ta, tb] in t.as_chunks::<2>().0 { // Spans of no length at the precision of their own coordinates are dropped. @@ -188,36 +203,50 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu emit(ta, tb, budget)?; continue; } - // The dashes run from the line's base point, element by element, from the period - // before the one the span starts in, so a dot that ends that period (on the span's - // start) is kept. - let mut at = (ta / period).floor() * period; - if at >= ta { - at -= period; - } + // The dashes run from the line's dash start, element by element, from the period + // the span starts in. + let start = phase(k as f64); + let mut at = start + ((ta - start) / period).floor() * period; // Periods too short to move along the span, or more dashes than one hatch may // look at, are refused before any of them is looked at. - let steps = ((tb - at) / period + 1.0) * l.dashes.len() as f64; + let steps = ((tb - at) / period + 2.0) * l.dashes.len() as f64; if period <= LOCAL_TINY * at.abs().max(tb.abs()) || steps + work as f64 > MAX_WORK as f64 { return Err(NoPattern::TooDense); } + let mut element = |s: f64, v: f64, budget: &mut Budget| -> Result<(), NoPattern> { + budget.work(&mut work, 1)?; + if v > 0.0 { + let (s0, s1) = (s.max(ta), (s + v).min(tb)); + if s1 > s0 { + emit(s0, s1, budget)?; + } + } else if v == 0.0 && s >= ta { + emit(s, s, budget)?; + dots = true; + } + Ok(()) + }; + // When that period starts on the span's start, or past it, the elements that end + // the period before are measured back from its end, so a dot there is kept and a + // long period does not move them. + if at >= ta { + let (mut rest, mut first) = (0.0, l.dashes.len()); + while first > 0 && at - rest >= ta { + first -= 1; + rest += l.dashes[first].abs(); + } + for v in &l.dashes[first..] { + element(at - rest, *v, budget)?; + rest -= v.abs(); + } + } 'span: loop { for v in &l.dashes { if at > tb { break 'span; } - budget.work(&mut work, 1)?; - let len = v.abs(); - if *v > 0.0 { - let (s0, s1) = (at.max(ta), (at + len).min(tb)); - if s1 > s0 { - emit(s0, s1, budget)?; - } - } else if *v == 0.0 && at >= ta { - emit(at, at, budget)?; - dots = true; - } - at += len; + element(at, *v, budget)?; + at += v.abs(); } } } @@ -578,6 +607,38 @@ mod tests { assert!(a.iter().zip(&b).all(|(x, y)| x.0.distance(y.0) < 1e-9 && x.1.distance(y.1) < 1e-9), "{a:?} {b:?}"); } + #[test] + fn families_based_far_away_keep_lines_off_a_fractional_center() { + // A 3 square centered on y 1.5: lines one apart from a base 1e19 up run at whole y, not + // through the center. + let mut far = line(0.0, [0.0, 1.0], &[]); + far.base = [0.0, 1e19]; + let (bp, _) = pattern(&[far], &square(3.0)).unwrap(); + let p = pieces(&bp); + assert!(p.len() >= 2, "{p:?}"); + assert!(p.iter().all(|(a, b)| a.y == b.y && a.y.fract() == 0.0), "{p:?}"); + } + + #[test] + fn dash_periods_far_longer_than_the_boundary_still_draw() { + // Dashes 1e16 long from x 0, and from x -7.5e15: each row of the 100 square lies in a + // dash, so every row is drawn across the square. + for x in [0.0, -7.5e15] { + let mut l = line(0.0, [0.0, 10.0], &[1e16, -1e16]); + l.base = [x, 0.0]; + let (bp, _) = pattern(&[l], &square(100.0)).unwrap(); + let p = pieces(&bp); + let rows: Vec<_> = p.iter().filter(|(a, _)| a.y > 0.0 && a.y < 100.0).collect(); + assert_eq!(rows.len(), 9, "base x {x}: {p:?}"); + assert!(rows.iter().all(|(a, b)| a.x.abs() < 1e-9 && (b.x - 100.0).abs() < 1e-9), "base x {x}: {p:?}"); + } + // From x 5e15 the square lies in a gap: nothing is drawn. + let mut l = line(0.0, [0.0, 10.0], &[1e16, -1e16]); + l.base = [5e15, 0.0]; + let (bp, _) = pattern(&[l], &square(100.0)).unwrap(); + assert!(pieces(&bp).is_empty(), "{:?}", pieces(&bp)); + } + #[test] fn a_dot_on_the_start_of_a_span_is_kept() { // A gap of 5 then a dot, from x 0: dots at 0, 5 and 10 on the line along the bottom. From 323aa1d56f8407bbb3151d737ee269774d98ac6a Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 01:04:57 -0800 Subject: [PATCH 73/88] DXF/DWG import: dash phases keep their remainders; long dashes keep their ends A pattern line's dash start is now taken from each term reduced to within half a period before the terms are added: the base and the boundary's center along the line, and each whole count of offsets, with the rounding error of the count times the offset reduced on its own. Offset counts that cancel (2^30 offsets each way, 2^30 along) no longer drop the center's 50, and a base 1e19 along keeps its remainder of 4 in a period of 6, so the dashes start at x 4 instead of x 0. The elements that end the period before a span now take their ends from the distances summed back from that period's end. A dash 1e16 long before a gap no longer ends at its rounded start plus its length, which drew a stroke into the gap. --- crates/cad/src/import/hatch.rs | 98 ++++++++++++++++++++++++++++------ 1 file changed, 81 insertions(+), 17 deletions(-) diff --git a/crates/cad/src/import/hatch.rs b/crates/cad/src/import/hatch.rs index 1bc3e323f4..06a50b0b3c 100644 --- a/crates/cad/src/import/hatch.rs +++ b/crates/cad/src/import/hatch.rs @@ -156,21 +156,21 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu let across = across + last * step; // Where the dashes start on that line, from its point nearest the center. Each line is // measured from its own point nearest the center, so its spans stay near the boundary - // however long the dash period is. + // however long the dash period is. Each term is reduced to within half a period before + // the terms are added, so a distant base or a large offset count keeps its remainder. + let od = offset.dot(d); let along = if l.dashes.is_empty() { 0.0 } else { - let bd = base.to_vec2().dot(d) + to_origin * offset.dot(d); - bd + ((to_center + last) * offset.dot(d) - center.to_vec2().dot(d)) + let (bd, cd) = (near_rem(base.to_vec2().dot(d), period), near_rem(center.to_vec2().dot(d), period)); + let counts = near_rem(product_rem(to_origin, od, period) + product_rem(to_center + last, od, period), period); + near_rem((bd - cd) + counts, period) }; if !(across.is_finite() && along.is_finite()) { continue; } // The dash start nearest a line's point nearest the center, as a signed distance. - let phase = |k: f64| { - let s = along + k * offset.dot(d); - s - period * (s / period).round() - }; + let phase = |k: f64| near_rem(along + product_rem(k, od, period), period); let base = center + n * across; // The lines crossing the boundary's box: base + k * step along the normal for whole k. let h = corners.map(|c| (c - base).dot(n) / step); @@ -213,10 +213,11 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu if period <= LOCAL_TINY * at.abs().max(tb.abs()) || steps + work as f64 > MAX_WORK as f64 { return Err(NoPattern::TooDense); } - let mut element = |s: f64, v: f64, budget: &mut Budget| -> Result<(), NoPattern> { + // An element from `s` to `e`: a dash when `v` is positive, a dot when it is zero. + let mut element = |s: f64, e: f64, v: f64, budget: &mut Budget| -> Result<(), NoPattern> { budget.work(&mut work, 1)?; if v > 0.0 { - let (s0, s1) = (s.max(ta), (s + v).min(tb)); + let (s0, s1) = (s.max(ta), e.min(tb)); if s1 > s0 { emit(s0, s1, budget)?; } @@ -228,16 +229,17 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu }; // When that period starts on the span's start, or past it, the elements that end // the period before are measured back from its end, so a dot there is kept and a - // long period does not move them. + // long period does not move them. Each element's start and end are the distances + // summed back from that end, so a long element does not move its known end. if at >= ta { - let (mut rest, mut first) = (0.0, l.dashes.len()); - while first > 0 && at - rest >= ta { + let (mut back, mut first) = (vec![0.0], l.dashes.len()); + while first > 0 && at - back[back.len() - 1] >= ta { first -= 1; - rest += l.dashes[first].abs(); + back.push(back[back.len() - 1] + l.dashes[first].abs()); } - for v in &l.dashes[first..] { - element(at - rest, *v, budget)?; - rest -= v.abs(); + for (i, v) in l.dashes[first..].iter().enumerate() { + let rest = back.len() - 1 - i; + element(at - back[rest], at - back[rest - 1], *v, budget)?; } } 'span: loop { @@ -245,7 +247,7 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu if at > tb { break 'span; } - element(at, *v, budget)?; + element(at, at + v.abs(), *v, budget)?; at += v.abs(); } } @@ -258,6 +260,26 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu Ok((out, dots)) } +/// `x` less the whole number of periods nearest it, within half a period of zero. Both steps +/// are exact: the remainder of a division, then one period added or taken away. +fn near_rem(x: f64, period: f64) -> f64 { + let r = x % period; + if r > period / 2.0 { + r - period + } else if r < -period / 2.0 { + r + period + } else { + r + } +} + +/// `a * b` reduced as [`near_rem`] does. The rounded product and its rounding error are each +/// reduced before they are added, so a large product keeps its remainder. +fn product_rem(a: f64, b: f64, period: f64) -> f64 { + let p = a * b; + near_rem(near_rem(p, period) + near_rem(a.mul_add(b, -p), period), period) +} + /// The boundary's edges as straight segments, each loop closed and its curves flattened to /// within [`FLATNESS`] of the loop's own size. Loops of no size are left out. fn edges(boundary: &BezPath) -> Result<Vec<(Point, Point)>, NoPattern> { @@ -639,6 +661,48 @@ mod tests { assert!(pieces(&bp).is_empty(), "{:?}", pieces(&bp)); } + #[test] + fn large_offset_counts_that_cancel_keep_the_dash_start() { + // A 100 square 2^40 up, its family based on the row through its middle with offsets + // 2^30 along: the row's dashes start at x 0, so it draws 0 to 30. + let b = 2f64.powi(40); + let mut boundary = square(100.0); + boundary.apply_affine(Affine::translate((0.0, b))); + let mut l = line(0.0, [2f64.powi(30), 1024.0], &[30.0, -70.0]); + l.base = [0.0, b + 50.0]; + let p = pieces(&pattern(&[l], &boundary).unwrap().0); + let row: Vec<_> = p.iter().filter(|(a, _)| a.y == b + 50.0).map(|(a, e)| (a.x, e.x)).collect(); + assert_eq!(row.len(), 1, "{p:?}"); + assert!((row[0].0 - 0.0).abs() < 1e-9 && (row[0].1 - 30.0).abs() < 1e-9, "{p:?}"); + } + + #[test] + fn a_long_dash_before_the_boundary_ends_where_its_gap_starts() { + // A gap 1e16 long from x 0, after a dash 1e16 long that ends at x 0: the unit square + // lies in the gap, so nothing is drawn. + let mut l = line(0.0, [0.0, 10.0], &[-1e16, 1e16]); + l.base = [0.0, 0.5]; + let (bp, _) = pattern(&[l], &square(1.0)).unwrap(); + assert!(pieces(&bp).is_empty(), "{:?}", pieces(&bp)); + } + + #[test] + fn distant_bases_keep_their_dash_remainder() { + // Dash 1, gap 5 from x 1e19, which is 4 more than a whole number of periods of 6: the + // dashes run 4 to 5, 10 to 11 … 94 to 95 in squares centered on a whole and a half x. + for side in [96.0, 98.0] { + let mut l = line(0.0, [0.0, 10.0], &[1.0, -5.0]); + l.base = [1e19, 0.0]; + let p = pieces(&pattern(&[l], &square(side)).unwrap().0); + let row: Vec<_> = p.iter().filter(|(a, _)| a.y == 50.0).map(|(a, e)| (a.x, e.x)).collect(); + assert_eq!(row.len(), 16, "side {side}: {row:?}"); + assert!( + row.iter().enumerate().all(|(i, (a, e))| (a - (4.0 + 6.0 * i as f64)).abs() < 1e-9 && (e - a - 1.0).abs() < 1e-9), + "side {side}: {row:?}" + ); + } + } + #[test] fn a_dot_on_the_start_of_a_span_is_kept() { // A gap of 5 then a dot, from x 0: dots at 0, 5 and 10 on the line along the bottom. From cb7c69932aeb97db4e3960515802cf986ad3b05e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 02:12:48 -0800 Subject: [PATCH 74/88] Windows: a maximize skips the monitor above's taskbar; frame limit scales with DPI With monitors stacked vertically, the upper monitor's auto-hidden bottom taskbar is parked mostly past its edge, so most of it lies on the monitor below. The guard counted it as that monitor's top taskbar and trimmed a maximize there a pixel short of the top. A taskbar that is not wholly on a monitor now counts only when most of it is off that monitor, as an auto-hidden taskbar of its own is. The largest frame a parked maximize may have was a fixed 32 px. The resize border grows with DPI (about 40 px at 500 %), so at high scaling a maximize covering the taskbar was never moved clear of it. The limit is now 32 px at 96 DPI, scaled by the window's DPI. --- apps/vectorcraft/src/window_frame.rs | 72 +++++++++++++++++++++------- 1 file changed, 56 insertions(+), 16 deletions(-) diff --git a/apps/vectorcraft/src/window_frame.rs b/apps/vectorcraft/src/window_frame.rs index ba5d3d298d..fb62a91eac 100644 --- a/apps/vectorcraft/src/window_frame.rs +++ b/apps/vectorcraft/src/window_frame.rs @@ -140,7 +140,8 @@ mod platform { let (rect, monitor, work) = ((r.left, r.top, r.right, r.bottom), (m.left, m.top, m.right, m.bottom), (w.left, w.top, w.right, w.bottom)); // The taskbars are looked up (a few `FindWindowEx` calls) only while the window covers its // whole monitor, which it no longer does once trimmed. - let Some((left, top, right, bottom)) = super::clamped_rect(rect, monitor, work).or_else(|| { + let frame = super::frame_limit(hwnd.GetDpiForWindow()); + let Some((left, top, right, bottom)) = super::clamped_rect(rect, monitor, work, frame).or_else(|| { super::covers(rect, monitor).then(|| super::short_of_autohide_taskbars(rect, monitor, work, &taskbar_edges(monitor))).flatten() }) else { return; @@ -238,21 +239,29 @@ impl<H> Viewports<H> { } } -/// How far a parked maximize reaches past a monitor or work-area edge: the resize border (about -/// 8 pt at 100 %, more with DPI). Past that, a maximized window's rect is not parked but being -/// dragged or snapped, and is left alone. -const FRAME: i32 = 32; +/// How far, in physical pixels at 96 DPI (100 %), a parked maximize reaches past a monitor or +/// work-area edge at most: the resize border is about 8 px at 100 %. Past that, a maximized +/// window's rect is not parked but being dragged or snapped, and is left alone. +const FRAME_AT_96_DPI: i32 = 32; + +/// [`FRAME_AT_96_DPI`] for a window at `dpi`, which the resize border grows with; never less than +/// at 96 DPI, so an unknown DPI (0) counts as 100 %. +#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] +fn frame_limit(dpi: u32) -> i32 { + let scaled = i64::from(FRAME_AT_96_DPI) * i64::from(dpi) / 96; + i32::try_from(scaled).unwrap_or(i32::MAX).max(FRAME_AT_96_DPI) +} /// The rect to move a maximize to so it stays inside the work area on every edge, plus the resize /// border it was parked with, or `None` when it already does or `rect` (`left, top, right, /// bottom`, desktop coordinates) is not parked at its maximize place. `monitor` is the monitor's -/// full rect and `work` its work area (the monitor less the taskbar) in the same coordinates. The -/// border is read from the edges that have no taskbar, and every edge must sit that far outside -/// either the monitor (where Windows puts a caption-less maximize) or the work area (where the -/// guard puts it), so a rect it already moved is left alone. Platform-neutral so it is tested -/// everywhere. +/// full rect and `work` its work area (the monitor less the taskbar) in the same coordinates; +/// `frame` is the largest border a parked maximize has ([`frame_limit`]). The border is read from +/// the edges that have no taskbar, and every edge must sit that far outside either the monitor +/// (where Windows puts a caption-less maximize) or the work area (where the guard puts it), so a +/// rect it already moved is left alone. Platform-neutral so it is tested everywhere. #[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] -fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32)) -> Option<(i32, i32, i32, i32)> { +fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32), frame: i32) -> Option<(i32, i32, i32, i32)> { let (l, t, r, b) = rect; let (ml, mt, mr, mb) = monitor; let (wl, wt, wr, wb) = work; @@ -269,7 +278,7 @@ fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: ] .into_iter() .flatten() - .filter(|n| (0..=FRAME).contains(n)) + .filter(|n| (0..=frame).contains(n)) .min()?; let parked = |monitor: Option<i32>, work: Option<i32>| monitor == Some(border) || work == Some(border); if !parked(ml.checked_sub(l), wl.checked_sub(l)) @@ -304,9 +313,11 @@ fn covers(rect: Rect, monitor: Rect) -> bool { } /// The edge of `monitor` that a taskbar with the rect `taskbar` sits on: the edge nearest the -/// taskbar's center, or `None` when the taskbar does not overlap the monitor. An auto-hidden -/// taskbar is parked mostly past its edge with a sliver left on the monitor, so its center can lie -/// outside the monitor. +/// taskbar's center, or `None` when the taskbar is not this monitor's. A shown taskbar lies wholly +/// on its monitor. An auto-hidden taskbar is parked mostly past its edge with a sliver left on the +/// monitor, so its center can lie outside the monitor; the part past the edge can lie on a +/// neighboring monitor, which a taskbar that is neither wholly on the monitor nor mostly off it +/// belongs to. #[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] fn taskbar_edge(taskbar: Rect, monitor: Rect) -> Option<Edge> { let (tl, tt, tr, tb) = (i64::from(taskbar.0), i64::from(taskbar.1), i64::from(taskbar.2), i64::from(taskbar.3)); @@ -314,6 +325,12 @@ fn taskbar_edge(taskbar: Rect, monitor: Rect) -> Option<Edge> { if tl >= tr || tt >= tb || ml >= mr || mt >= mb || tr <= ml || tl >= mr || tb <= mt || tt >= mb { return None; } + let inside = tl >= ml && tt >= mt && tr <= mr && tb <= mb; + let area = |l: i64, t: i64, r: i64, b: i64| i128::from(r - l) * i128::from(b - t); + let on_monitor = area(tl.max(ml), tt.max(mt), tr.min(mr), tb.min(mb)); + if !inside && on_monitor * 2 >= area(tl, tt, tr, tb) { + return None; + } // The center and the distances are doubled, so nothing is rounded. let (cx, cy) = (tl + tr, tt + tb); [(Edge::Left, cx - 2 * ml), (Edge::Top, cy - 2 * mt), (Edge::Right, 2 * mr - cx), (Edge::Bottom, 2 * mb - cy)] @@ -346,7 +363,12 @@ fn short_of_autohide_taskbars(rect: Rect, monitor: Rect, work: Rect, taskbars: & #[cfg(test)] mod tests { - use super::{Edge, Viewports, clamped_rect, short_of_autohide_taskbars, taskbar_edge}; + use super::{Edge, Viewports, frame_limit, short_of_autohide_taskbars, taskbar_edge}; + + /// [`super::clamped_rect`] for a window at 96 DPI (100 %). + fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32)) -> Option<(i32, i32, i32, i32)> { + super::clamped_rect(rect, monitor, work, frame_limit(96)) + } fn viewport(name: &str) -> egui::ViewportId { egui::ViewportId::from_hash_of(name) @@ -453,6 +475,18 @@ mod tests { } } + #[test] + fn the_frame_limit_grows_with_the_monitor_dpi() { + // At 500 % (480 DPI) the resize border is about 40 px, past the limit at 100 %. + let (monitor, work) = ((0, 0, 3840, 2160), (0, 0, 3840, 2000)); + let rect = (-40, -40, 3880, 2200); + assert_eq!(clamped_rect(rect, monitor, work), None, "100 %"); + assert_eq!(super::clamped_rect(rect, monitor, work, frame_limit(480)), Some((-40, -40, 3880, 2040)), "500 %"); + assert_eq!(super::clamped_rect((-8, -8, 1928 + 40, 1088), (0, 0, 1920, 1080), (0, 0, 1920, 1046), frame_limit(96)), None, "past the limit"); + assert_eq!(frame_limit(0), frame_limit(96), "an unknown DPI counts as 100 %"); + assert!(frame_limit(u32::MAX) > frame_limit(480), "no overflow"); + } + #[test] fn a_maximize_without_a_reserved_taskbar_is_left_alone() { let monitor = (0, 0, 1920, 1080); @@ -503,6 +537,12 @@ mod tests { assert_eq!(taskbar_edge((-60, 0, 2, 1080), monitor), Some(Edge::Left)); assert_eq!(taskbar_edge((1918, 0, 1980, 1080), monitor), Some(Edge::Right)); assert_eq!(taskbar_edge((1920, 1032, 3840, 1080), monitor), None, "other monitor"); + // With monitors stacked, the part of the upper monitor's auto-hidden taskbar parked past its + // bottom edge lies on the monitor below, which it does not belong to. + let below = (0, 1080, 1920, 2160); + assert_eq!(taskbar_edge((0, 1078, 1920, 1126), below), None, "neighbor's auto-hidden taskbar"); + assert_eq!(taskbar_edge((0, 2158, 1920, 2206), below), Some(Edge::Bottom), "its own auto-hidden taskbar"); + assert_eq!(taskbar_edge((0, 1080, 1920, 1128), below), Some(Edge::Top), "its own shown top taskbar"); assert!(taskbar_edge((i32::MIN, i32::MIN, i32::MAX, i32::MAX), monitor).is_some(), "no overflow"); } } From f651cf6d1bd4d6a743631110ee37b29c8a7f4af6 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 02:20:05 -0800 Subject: [PATCH 75/88] DXF/DWG import: dash phases keep small terms when large ones cancel A pattern line's dash start is the sum of the base and the boundary's center along the line and the whole counts of offsets, each reduced to within half a period. Those reduced terms were added in plain floating point, so a small term was rounded away before larger ones cancelled: a family based and offset 2^54 along, with a dash 16 long in a period of 2^57, drew the line along the bottom of a unit square from x 0.5 instead of x 0. The terms are now added with their rounding errors kept apart and added back after the sum is reduced, for the dash start and for each line's phase. --- crates/cad/src/import/hatch.rs | 44 +++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/crates/cad/src/import/hatch.rs b/crates/cad/src/import/hatch.rs index 06a50b0b3c..068d873ca5 100644 --- a/crates/cad/src/import/hatch.rs +++ b/crates/cad/src/import/hatch.rs @@ -162,15 +162,17 @@ pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Bu let along = if l.dashes.is_empty() { 0.0 } else { - let (bd, cd) = (near_rem(base.to_vec2().dot(d), period), near_rem(center.to_vec2().dot(d), period)); - let counts = near_rem(product_rem(to_origin, od, period) + product_rem(to_center + last, od, period), period); - near_rem((bd - cd) + counts, period) + let ([o, oe], [c, ce]) = (product_parts(to_origin, od), product_parts(to_center + last, od)); + sum_rem(&[base.to_vec2().dot(d), -center.to_vec2().dot(d), o, oe, c, ce], period) }; if !(across.is_finite() && along.is_finite()) { continue; } // The dash start nearest a line's point nearest the center, as a signed distance. - let phase = |k: f64| near_rem(along + product_rem(k, od, period), period); + let phase = |k: f64| { + let [p, e] = product_parts(k, od); + sum_rem(&[along, p, e], period) + }; let base = center + n * across; // The lines crossing the boundary's box: base + k * step along the normal for whole k. let h = corners.map(|c| (c - base).dot(n) / step); @@ -273,11 +275,25 @@ fn near_rem(x: f64, period: f64) -> f64 { } } -/// `a * b` reduced as [`near_rem`] does. The rounded product and its rounding error are each -/// reduced before they are added, so a large product keeps its remainder. -fn product_rem(a: f64, b: f64, period: f64) -> f64 { +/// `a * b` as the rounded product and its rounding error, which add up to it exactly. +fn product_parts(a: f64, b: f64) -> [f64; 2] { let p = a * b; - near_rem(near_rem(p, period) + near_rem(a.mul_add(b, -p), period), period) + [p, a.mul_add(b, -p)] +} + +/// The sum of `terms` reduced as [`near_rem`] does. Each term is reduced first, so a large term +/// keeps its remainder, and the reduced terms are added with their rounding errors kept apart, so +/// a small term is kept when larger ones cancel. +fn sum_rem(terms: &[f64], period: f64) -> f64 { + let (mut hi, mut lo) = (0.0, 0.0); + for &t in terms { + let t = near_rem(t, period); + let s = hi + t; + let v = s - hi; + lo += (hi - (s - v)) + (t - v); + hi = s; + } + near_rem(near_rem(hi, period) + near_rem(lo, period), period) } /// The boundary's edges as straight segments, each loop closed and its curves flattened to @@ -676,6 +692,18 @@ mod tests { assert!((row[0].0 - 0.0).abs() < 1e-9 && (row[0].1 - 30.0).abs() < 1e-9, "{p:?}"); } + #[test] + fn large_phase_terms_that_cancel_keep_a_small_one() { + // Based and offset by 2^54 along and 10 up: the line one offset back runs along the + // bottom of the unit square with its dash 16 long from x 0, so it covers 0 to 1. + let big = 2f64.powi(54); + let mut l = line(0.0, [big, 10.0], &[16.0, -(2f64.powi(57) - 16.0)]); + l.base = [big, 10.0]; + let p = pieces(&pattern(&[l], &square(1.0)).unwrap().0); + let row: Vec<_> = p.iter().filter(|(a, _)| a.y == 0.0).map(|(a, e)| (a.x, e.x)).collect(); + assert_eq!(row, [(0.0, 1.0)], "{p:?}"); + } + #[test] fn a_long_dash_before_the_boundary_ends_where_its_gap_starts() { // A gap 1e16 long from x 0, after a dash 1e16 long that ends at x 0: the unit square From 116da84bc5e8cabaf5892688a71d3f2bbe5601a7 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 03:55:56 -0800 Subject: [PATCH 76/88] Live Corners: adding or removing an anchor keeps the corners live Adding an anchor with the Pen or Add Anchor Point tool, or removing one with the Pen, Delete Anchor Point, Remove Anchor Points or the Delete key with Delete Removes Anchor Points and Keeps Paths Joined on, turned a path with rounded Live Corners into a plain path: the arcs were baked into anchors and the corner widgets disappeared. path.insertAnchor now adds the anchor on the matching side of the uncut outline, at the point the drawn segment has at t, and cuts the corners again at their radii and kinds. path.removeAnchor and path.removeAnchors remove the uncut corner each removed anchor belongs to, so removing either end of a corner's arc removes that corner and the others stay live; a path left with no corner is removed. A relative radius keeps the length it is drawn at, up to the corner's new largest radius. Selected anchors and segments follow their corners, a split selected segment stays selected as its two halves with the new anchor, and Remove Anchor Points selects the first anchor of the next corner. An anchor added on a corner's arc still makes the path plain, and the status bar now says the corners were expanded. Docs: docs/mcp.md, the params text of path.insertAnchor, path.removeAnchor and path.removeAnchors, and the Live Corners entry in docs/target-app-parity.md. --- crates/doc/src/corners.rs | 187 +++++++++++++++++++++++- crates/doc/src/lib.rs | 2 +- crates/engine/src/cmd/draw2.rs | 2 +- crates/engine/src/cmd/draw2/anchors.rs | 92 +++++++++--- crates/engine/src/cmd/draw2/commands.rs | 4 +- crates/engine/src/cmd/path.rs | 100 ++++++++++--- crates/engine/src/tests/livecorners.rs | 154 ++++++++++++++++++- docs/mcp.md | 14 +- docs/target-app-parity.md | 1 + 9 files changed, 504 insertions(+), 52 deletions(-) diff --git a/crates/doc/src/corners.rs b/crates/doc/src/corners.rs index 56bbb29845..8db1d8fa7f 100644 --- a/crates/doc/src/corners.rs +++ b/crates/doc/src/corners.rs @@ -6,8 +6,9 @@ use std::borrow::Cow; use std::collections::BTreeSet; use vectorcraft_geom::corners::{Corner, cut_corners, fitted_radii, path_corners}; +use vectorcraft_geom::kurbo::ParamCurveNearest; use vectorcraft_geom::shapes::{self, CornerKind}; -use vectorcraft_geom::{Affine, PathData, Point, Rect}; +use vectorcraft_geom::{Affine, ParamCurve, PathData, Point, Rect, SubPath}; use crate::node::{LiveShape, Node, NodeKind}; use crate::selection::AnchorRef; @@ -198,6 +199,31 @@ impl<'a> LiveCorners<'a> { &self.sources } + /// Whether any corner has a radius stored, so the path as drawn has its corners cut (or + /// cuts them again when an edit bends a straightened corner back). + pub fn is_cut(&self) -> bool { + self.radii.iter().any(|r| *r > 0.0) + } + + /// The anchors of `base` (subpath, anchor) that `anchors` of the path as drawn come from. + pub fn outline_anchors(&self, anchors: &BTreeSet<AnchorRef>) -> BTreeSet<AnchorRef> { + let ks: BTreeSet<usize> = anchors.iter().filter_map(|(si, ai)| self.sources.get(*si)?.get(*ai).copied()).collect(); + let mut out = BTreeSet::new(); + let mut first = 0; + for (si, sp) in self.base.subpaths.iter().enumerate() { + out.extend(ks.range(first..first + sp.anchors.len()).map(|k| (si, k - first))); + first += sp.anchors.len(); + } + out + } + + /// The first anchor of the path as drawn that anchor `(si, ai)` of `base` gives. + pub fn drawn_anchor(&self, (si, ai): AnchorRef) -> Option<AnchorRef> { + let first: usize = self.base.subpaths.get(..si)?.iter().map(|sp| sp.anchors.len()).sum(); + let k = first + ai; + self.sources.get(si)?.iter().position(|s| *s == k).map(|drawn| (si, drawn)) + } + /// The radius and kind `corners` share (each `None` when they differ, or for no corners). /// Radius is what was set ([`LiveCorners::radius`]: document lengths, or a fraction in 0..1 /// when [`LiveCorners::radii_relative`]), not the fitted draw size ([`LiveCorners::drawn_radius`]). @@ -325,13 +351,8 @@ pub fn edit_corner_anchors( anchors: &BTreeSet<AnchorRef>, edit: impl FnOnce(&mut PathData, &BTreeSet<AnchorRef>), ) -> Option<()> { - live.as_ref()?; - if let Some(LiveShape::Rectangle { xf, .. }) = live.as_deref() { - let [a, b, c, d, _, _] = xf.as_coeffs(); - let scale = (a * a + b * b).max(c * c + d * d).max(1e-12); - if ((a * a + b * b) - (c * c + d * d)).abs() > 1e-9 * scale || (a * c + b * d).abs() > 1e-9 * scale { - return None; - } + if live.as_deref().is_none_or(uneven_rectangle) { + return None; } let (mut base, moved, mut radii, kinds, relative) = { let lc = LiveCorners::new(path, live.as_deref())?; @@ -369,6 +390,156 @@ pub fn edit_corner_anchors( Some(()) } +/// Whether `live` is a rectangle whose transform shears it or scales it unevenly. +fn uneven_rectangle(live: &LiveShape) -> bool { + let LiveShape::Rectangle { xf, .. } = live else { return false }; + let [a, b, c, d, _, _] = xf.as_coeffs(); + let scale = (a * a + b * b).max(c * c + d * d).max(1e-12); + ((a * a + b * b) - (c * c + d * d)).abs() > 1e-9 * scale || (a * c + b * d).abs() > 1e-9 * scale +} + +/// Change the anchors of the uncut outline of a path with cut Live Corners and cut the corners +/// again. `edit` gets the outline in document space and returns, for each of its anchors after +/// the change, the index of the anchor before the change it is (`None` for an anchor it added). +/// Each corner keeps its radius and kind, and an added anchor has none; relative radii keep their +/// document lengths. A live rectangle or polygon becomes a [`LiveShape::Path`] with that outline, +/// and a path left with no radius and no corner kind other than round (or with no anchor) is a +/// plain path. Returns `None`, leaving the path unchanged, as [`edit_corner_anchors`] does, or when +/// `edit` returns `None` or does not list one entry per anchor. +fn rebuild_corner_outline( + path: &mut PathData, + live: &mut Option<Box<LiveShape>>, + edit: impl FnOnce(&mut PathData) -> Option<Vec<Option<usize>>>, +) -> Option<()> { + if live.as_deref().is_none_or(uneven_rectangle) { + return None; + } + let (mut base, lengths, kinds, relative) = { + let lc = LiveCorners::new(path, live.as_deref())?; + if !lc.is_cut() { + return None; + } + let base = lc.base.transformed(lc.xf); + let mut radii = lc.radii.clone(); + radii.resize(base.anchor_count(), 0.0); + let lengths = if lc.relative { + let mut l = LiveShape::Path { base: base.clone(), radii, kinds: vec![], radii_relative: true }; + convert_radii_relative(&mut l, false); + let LiveShape::Path { radii, .. } = l else { return None }; + radii + } else { + radii + }; + (base, lengths, lc.kinds.clone(), lc.relative) + }; + let from = edit(&mut base)?; + if from.len() != base.anchor_count() { + return None; + } + let radii: Vec<f64> = from.iter().map(|f| f.and_then(|i| lengths.get(i).copied()).unwrap_or(0.0)).collect(); + let kinds: Vec<CornerKind> = from.iter().map(|f| f.and_then(|i| kinds.get(i).copied()).unwrap_or_default()).collect(); + if radii.iter().all(|r| *r <= 0.0) && kinds.iter().all(|k| *k == CornerKind::Round) { + *path = base; + *live = None; + return Some(()); + } + let mut l = LiveShape::Path { base, radii, kinds, radii_relative: false }; + convert_radii_relative(&mut l, relative); + *path = l.to_path(); + *live = Some(Box::new(l)); + Some(()) +} + +/// Add an anchor at `t` (0..1) on segment `seg` of subpath `si` of a path with cut Live Corners: +/// it goes on the side of the uncut outline that the segment is part of, at the point of the +/// segment at `t`, and the corners are cut again, keeping their radii and kinds +/// ([`rebuild_corner_outline`]). Returns the new anchor's index in subpath `si` of the path as +/// drawn, or `None`, leaving the path unchanged, for a segment that is a corner's cut, a segment +/// that does not exist, or a path [`edit_corner_anchors`] leaves as it is. +pub fn insert_corner_anchor(path: &mut PathData, live: &mut Option<Box<LiveShape>>, si: usize, seg: usize, t: f64) -> Option<usize> { + let (target, first, local) = { + let lc = LiveCorners::new(path, live.as_deref())?; + let sp = path.subpaths.get(si)?; + let from = lc.sources.get(si)?; + if seg >= sp.segment_count() || from.len() != sp.anchors.len() { + return None; + } + let (ka, kb) = (*from.get(seg)?, *from.get((seg + 1) % from.len())?); + // Both ends from one corner: the segment is that corner's cut. + if ka == kb { + return None; + } + let first: usize = lc.base.subpaths.get(..si)?.iter().map(|s| s.anchors.len()).sum(); + let outline = lc.base.subpaths.get(si)?; + let local = ka.checked_sub(first).filter(|a| *a < outline.anchors.len())?; + if !outline.has_segment(local, true) || kb != first + (local + 1) % outline.anchors.len() { + return None; + } + (sp.segment(seg).eval(t.clamp(0.0, 1.0)), first, local) + }; + let new_index = first + local + 1; + let (mut p, mut l) = (path.clone(), live.clone()); + rebuild_corner_outline(&mut p, &mut l, |base| { + let sp = base.subpaths.get_mut(si)?; + // A straight side is a cubic with its handles on its ends too, so the parameter of the + // point nearest `target` puts the new anchor there on either kind of side. + let tb = sp.segment(local).nearest(target, 1e-9).t; + sp.insert_anchor(local, tb.clamp(0.0, 1.0)); + Some((0..base.anchor_count()).map(|j| if j < new_index { Some(j) } else { (j > new_index).then(|| j - 1) }).collect()) + })?; + let drawn = match LiveCorners::new(&p, l.as_deref()) { + Some(lc) => lc.sources.get(si)?.iter().position(|k| *k == new_index)?, + None => local + 1, + }; + *path = p; + *live = l; + Some(drawn) +} + +/// Remove the anchors of the uncut outline that `anchors` (of the path as drawn) come from, so a +/// cut corner goes when either of its anchors is removed, and cut the remaining corners again, +/// keeping their radii and kinds ([`rebuild_corner_outline`]). `remove` takes the listed anchors +/// (in ascending order) out of one subpath of the outline, refitting the curve round each; a +/// subpath left with fewer than two anchors is removed, and a path left with none is an empty plain +/// path. Returns `None`, leaving the path unchanged, when no anchor maps to the outline, when +/// `remove` does not remove exactly the anchors listed, or for a path [`edit_corner_anchors`] +/// leaves as it is. +pub fn remove_corner_anchors( + path: &mut PathData, + live: &mut Option<Box<LiveShape>>, + anchors: &BTreeSet<AnchorRef>, + mut remove: impl FnMut(&mut SubPath, &[usize]), +) -> Option<()> { + let outline = LiveCorners::new(path, live.as_deref())?.outline_anchors(anchors); + if outline.is_empty() { + return None; + } + let (mut p, mut l) = (path.clone(), live.clone()); + rebuild_corner_outline(&mut p, &mut l, |base| { + let mut from = vec![]; + let mut first = 0; + for (si, sp) in base.subpaths.iter_mut().enumerate() { + let n = sp.anchors.len(); + let gone: Vec<usize> = outline.range((si, 0)..=(si, usize::MAX)).map(|&(_, ai)| ai).collect(); + if !gone.is_empty() { + remove(sp, &gone); + if sp.anchors.len() + gone.len() != n { + return None; + } + } + if sp.anchors.len() >= 2 { + from.extend((0..n).filter(|ai| gone.binary_search(ai).is_err()).map(|ai| Some(first + ai))); + } + first += n; + } + base.subpaths.retain(|sp| sp.anchors.len() >= 2); + Some(from) + })?; + *path = p; + *live = l; + Some(()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 7bddc2c482..e37a523ad7 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -103,7 +103,7 @@ pub use appearance::{ }; pub use assets::ExportAsset; pub use compound_shape::ShapeMode; -pub use corners::{LiveCorners, edit_corner_anchors, rebase_relative_radii}; +pub use corners::{LiveCorners, edit_corner_anchors, insert_corner_anchor, rebase_relative_radii, remove_corner_anchors}; pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES}; pub use graph::{ ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 1054ca3ddc..71d41bde68 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -31,7 +31,7 @@ mod freehand; mod quickpen; mod smooth; -pub(super) use anchors::{following_anchors, remove_anchors_of}; +pub(super) use anchors::remove_anchors_following; pub use commands::specs; pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt}; pub(super) use cut::{components, erase_outline}; diff --git a/crates/engine/src/cmd/draw2/anchors.rs b/crates/engine/src/cmd/draw2/anchors.rs index 8068418edd..32aa11172c 100644 --- a/crates/engine/src/cmd/draw2/anchors.rs +++ b/crates/engine/src/cmd/draw2/anchors.rs @@ -111,7 +111,12 @@ pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> { let ai = usize_req(p, "anchor", C)?; let curvature = switch_or(p, "curvature", false, C)?; let removed = s.edit("Delete Anchor Point", |d, sel| { - let sp = path_mut(d, id)?.subpaths.get(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + let path = match d.node(id).map(|n| &n.kind) { + Some(NodeKind::Path { path, .. }) => path, + Some(_) => return Err(EngineError::Other(format!("object {id} is not a path"))), + None => return Err(EngineError::NoNode(id)), + }; + let sp = path.subpaths.get(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; if ai >= sp.anchors.len() { return Err(EngineError::Other("no such anchor".into())); } @@ -142,15 +147,14 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> { let mut gone = Vec::new(); let mut emptied = Beside::replacing(d, &jobs.iter().map(|(id, _)| *id).collect::<Vec<_>>()); for (id, anchors) in jobs { - let shape: Vec<(usize, bool)> = - d.node(id).and_then(Node::path_data).map(|p| p.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect()).unwrap_or_default(); - let next = following_anchors(&shape, &anchors); - if remove_anchors_of(d, sel, &mut emptied, id, anchors, false)? { - gone.push(id); - } else if !next.is_empty() { + match remove_anchors_following(d, sel, &mut emptied, id, anchors, false)? { + None => gone.push(id), // The next anchor along is selected, so the next Remove Anchor Points goes on from // there without picking it first (#2241). - sel.anchors.insert(id, next); + Some(next) if !next.is_empty() => { + sel.anchors.insert(id, next); + } + Some(_) => {} } } emptied.finish(d)?; @@ -207,12 +211,41 @@ pub(in crate::cmd) fn remove_anchors_of( sel: &mut Selection, emptied: &mut Beside, id: NodeId, - mut anchors: Vec<(usize, usize)>, + anchors: Vec<(usize, usize)>, curvature: bool, ) -> Result<bool> { - // The last first, so the indexes still to come stay valid. - anchors.sort_unstable_by(|a, b| b.cmp(a)); + Ok(remove_anchors_following(d, sel, emptied, id, anchors, curvature)?.is_none()) +} + +/// [`remove_anchors_of`], returning `None` when the path went, else the anchors that follow the +/// removed ones in each subpath ([`following_anchors`]), numbered as the path is after the removal. +/// A path with cut Live Corners keeps them ([`vectorcraft_doc::remove_corner_anchors`]): the anchors +/// of its uncut outline that `anchors` come from are removed, so removing either anchor of a cut +/// corner removes that corner, and the following anchors are those of the outline. +pub(in crate::cmd) fn remove_anchors_following( + d: &mut Document, + sel: &mut Selection, + emptied: &mut Beside, + id: NodeId, + mut anchors: Vec<(usize, usize)>, + curvature: bool, +) -> Result<Option<BTreeSet<(usize, usize)>>> { + anchors.sort_unstable(); anchors.dedup(); + if let Some(next) = remove_live_corner_anchors(d, id, &anchors, curvature) { + if d.node(id).and_then(Node::path_data).is_none_or(PathData::is_empty) { + emptied.put(d, id, vec![])?; + return Ok(None); + } + sel.anchors.remove(&id); + sel.segments.remove(&id); + return Ok(Some(next)); + } + let shape: Vec<(usize, bool)> = + d.node(id).and_then(Node::path_data).map(|p| p.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect()).unwrap_or_default(); + let next = following_anchors(&shape, &anchors); + // The last first, so the indexes still to come stay valid. + anchors.reverse(); let path = path_mut(d, id)?; let mut rest = &anchors[..]; while let Some(&(si, _)) = rest.first() { @@ -228,14 +261,39 @@ pub(in crate::cmd) fn remove_anchors_of( } } path.subpaths.retain(|sp| sp.anchors.len() >= 2); - let gone = path.is_empty(); - if gone { + if path.is_empty() { emptied.put(d, id, vec![])?; - } else { - sel.anchors.remove(&id); - sel.segments.remove(&id); + return Ok(None); } - Ok(gone) + sel.anchors.remove(&id); + sel.segments.remove(&id); + Ok(Some(next)) +} + +/// Remove `anchors` (ascending, no repeats) of path `id` when it has cut Live Corners, keeping +/// them live ([`vectorcraft_doc::remove_corner_anchors`]), and return the anchors as drawn that +/// follow the removed ones; `None`, changing nothing, when the corners can't stay live. +fn remove_live_corner_anchors(d: &mut Document, id: NodeId, anchors: &[(usize, usize)], curvature: bool) -> Option<BTreeSet<(usize, usize)>> { + let NodeKind::Path { path, live, .. } = &mut d.node_mut(id)?.kind else { return None }; + let set: BTreeSet<(usize, usize)> = anchors.iter().copied().collect(); + let lc = vectorcraft_doc::LiveCorners::new(path, live.as_deref())?; + let shape: Vec<(usize, bool)> = lc.base.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect(); + let outline: Vec<(usize, usize)> = lc.outline_anchors(&set).into_iter().collect(); + drop(lc); + vectorcraft_doc::remove_corner_anchors(path, live, &set, |sp, gone| { + if curvature { + for &ai in gone.iter().rev() { + vectorcraft_tools::draw2::curvature_remove(sp, ai); + } + } else { + po::remove_anchors(sp, gone); + } + })?; + let next = following_anchors(&shape, &outline); + Some(match vectorcraft_doc::LiveCorners::new(path, live.as_deref()) { + Some(lc) => next.into_iter().filter_map(|r| lc.drawn_anchor(r)).collect(), + None => next, + }) } pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result<Value> { diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 08404a3092..4ea2e723a3 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> { "Delete Anchor Point", [], None, - "{id, subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points)", + "{id, subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points); on a path with rounded Live Corners, the corner the anchor belongs to is removed and the other corners stay live", has_doc, remove_anchor ), @@ -66,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> { "Remove Anchor Points", ["Object", "Path"], None, - "{} remove the direct-selected anchors without opening their paths, refitting the curve round each; the anchor after each removed one is selected, so running it again goes on along the path → {removedObjects}", + "{} remove the direct-selected anchors without opening their paths, refitting the curve round each; the anchor after each removed one is selected, so running it again goes on along the path; on a path with rounded Live Corners, the corners the anchors belong to are removed and the other corners stay live → {removedObjects}", has_anchors, remove_anchors ), diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index de0013036c..536a533321 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -149,7 +149,7 @@ pub fn specs() -> Vec<CommandSpec> { "Add Anchor Point", [], None, - "{id, subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected", + "{id, subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected; on a path with rounded Live Corners, an anchor added on a side keeps the corners live (the selection follows its corners), and one added on a corner's arc makes the path plain and answers with a warning", has_doc, insert_anchor ), @@ -2143,18 +2143,9 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo if d.node(*id).is_none() { continue; } - if keep_joined - && !set.is_empty() - && !segments.contains_key(id) - && let Some(path) = d.node(*id).and_then(|n| match &n.kind { - NodeKind::Path { path, .. } => Some(path), - _ => None, - }) - { - let shape: Vec<(usize, bool)> = path.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect(); + if keep_joined && !set.is_empty() && !segments.contains_key(id) && d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })) { let anchors: Vec<(usize, usize)> = set.iter().copied().collect(); - let next = super::draw2::following_anchors(&shape, &anchors); - if !super::draw2::remove_anchors_of(d, selection, &mut emptied, *id, anchors, false)? { + if let Some(next) = super::draw2::remove_anchors_following(d, selection, &mut emptied, *id, anchors, false)? { survivors.push(*id); following.push((*id, next)); } @@ -2451,6 +2442,44 @@ fn stretch_weights(anchors: &Anchors, closed: bool, roles: &[Stretch]) -> Vec<[f /// the same points. /// A selected segment that the new anchor splits stays selected as its two halves, and the new /// anchor joins its ends in the anchors that move with it. +/// After anchor `new` of the uncut outline of path `id` was added on its segment `split` as drawn, +/// and the path's corners were cut again, select the segments as drawn that run between the same +/// anchors of the outline as `segments` (the path's selected segments before), each listed in +/// `before` and `after` as [`corner_sources`] gives them, `before` numbered as the outline is after +/// the addition. A selected `split` gives both its halves, and the new anchor is selected with +/// them, as [`renumber_after_insert`] selects them on a plain path. +fn remap_corner_segments( + sel: &mut Selection, + id: NodeId, + segments: &BTreeSet<SegmentRef>, + before: &[Vec<usize>], + after: &[Vec<usize>], + split: SegmentRef, + new: usize, +) { + let ends = |sources: &[Vec<usize>], (si, g): SegmentRef| { + let v = sources.get(si)?; + Some((*v.get(g)?, *v.get((g + 1) % v.len())?)) + }; + let drawn = + |si: usize, pair: (usize, usize)| after.get(si).and_then(|v| (0..v.len()).find(|&g| ends(after, (si, g)) == Some(pair))).map(|g| (si, g)); + let mut out = BTreeSet::new(); + for &r in segments { + let Some((a, b)) = ends(before, r) else { continue }; + if r == split { + out.extend([drawn(r.0, (a, new)), drawn(r.0, (new, b))].into_iter().flatten()); + if let Some(ai) = after.get(r.0).and_then(|v| v.iter().position(|k| *k == new)) { + sel.anchors.entry(id).or_default().insert((r.0, ai)); + } + } else { + out.extend(drawn(r.0, (a, b))); + } + } + if !out.is_empty() { + sel.segments.insert(id, out); + } +} + fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usize) { if let Some(set) = sel.anchors.get_mut(&id) { // A selected anchor index can name no anchor (`select.anchors` takes any index), so the @@ -2609,14 +2638,37 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> { let seg = index_opt(p, "segment", "path.insertAnchor")?.ok_or_else(|| bad("path.insertAnchor", "missing segment"))?; let t = number_or(p, "t", 0.5, "path.insertAnchor")?.clamp(0.0, 1.0); let select_anchor = switch_or(p, "selectAnchor", false, "path.insertAnchor")?; - let idx = s.edit("Add Anchor Point", |d, sel| { - let path = path_mut(d, id)?; - let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; - if seg >= sp.segment_count() { + let (idx, expanded) = s.edit("Add Anchor Point", |d, sel| { + let sp = d.node(id).and_then(Node::path_data).ok_or(EngineError::NoNode(id))?.subpaths.get(si); + if seg >= sp.ok_or_else(|| EngineError::Other("no such subpath".into()))?.segment_count() { return Err(EngineError::Other("no such segment".into())); } - let idx = sp.insert_anchor(seg, t); - renumber_after_insert(sel, id, si, idx); + let before = corner_sources(d, id); + let cut = d.node(id).and_then(vectorcraft_doc::LiveCorners::of).is_some_and(|lc| lc.is_cut()); + let kept = match d.node_mut(id).map(|n| &mut n.kind) { + Some(NodeKind::Path { path, live, .. }) => vectorcraft_doc::insert_corner_anchor(path, live, si, seg, t), + _ => None, + }; + let idx = match (kept, before, corner_sources(d, id)) { + // The corners stay live: the selection follows the corners its anchors come from, the + // outline's anchors after the new one numbered one higher. + (Some(idx), Some(before), Some(after)) => { + let new = after.get(si).and_then(|v| v.get(idx)).copied().unwrap_or(usize::MAX); + let before: Vec<Vec<usize>> = before.iter().map(|v| v.iter().map(|k| if *k >= new { k + 1 } else { *k }).collect()).collect(); + let segments = sel.segments.get(&id).cloned().unwrap_or_default(); + remap_corner_anchors(sel, id, &before, &after); + remap_corner_segments(sel, id, &segments, &before, &after, (si, seg), new); + idx + } + _ => { + let path = path_mut(d, id)?; + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + let idx = sp.insert_anchor(seg, t); + renumber_after_insert(sel, id, si, idx); + idx + } + }; + let expanded = cut && kept.is_none(); // A path that wasn't selected becomes the selection, its new anchor direct-selected, so // the point added shows and can be edited at once (#4237). `selectAnchor` does the same // for a path that is selected. @@ -2625,11 +2677,19 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> { sel.add(id); sel.anchors.entry(id).or_default().insert((si, idx)); } - Ok(idx) + Ok((idx, expanded)) })?; - Ok(json!({ "anchor": idx })) + let mut out = json!({ "anchor": idx }); + if expanded { + out["warning"] = json!(CORNERS_EXPANDED); + } + Ok(out) } +/// The status when adding an anchor point turned a path's Live Corners into plain anchor points. +/// Anchors added on a straight or curved side keep them; one added on a corner's curve does not. +const CORNERS_EXPANDED: &str = "Live Corners were expanded: the rounded corners are now plain anchor points"; + fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> { const C: &str = "path.cutAtAnchors"; let st = s.doc()?; diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 46a4ace011..beb22dc892 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -7,7 +7,7 @@ use std::collections::BTreeSet; use serde_json::{Value, json}; use vectorcraft_doc::{AnchorRef, LiveCorners, LiveShape, NodeKind}; use vectorcraft_geom::shapes::CornerKind; -use vectorcraft_geom::{Affine, Point}; +use vectorcraft_geom::{Affine, ParamCurve, Point}; use crate::*; @@ -1582,3 +1582,155 @@ fn a_nudge_the_pixel_grid_takes_back_with_an_object_selected_whole_records_no_un assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().live_shape(), Some(LiveShape::Rectangle { .. }))); assert_eq!(s.doc().unwrap().doc, doc); } + +/// The segment of path `id` as drawn that runs from a cut of corner `a` of its uncut outline to +/// a cut of corner `b` (the same corner twice: that corner's curve). +fn segment_between(s: &Session, id: NodeId, a: usize, b: usize) -> usize { + let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + let from = &lc.sources()[0]; + (0..from.len()).find(|&i| from[i] == a && from[(i + 1) % from.len()] == b).unwrap_or_else(|| panic!("no segment {a} -> {b} in {from:?}")) +} + +/// The anchors of path `id` as drawn that come from `corners` of its uncut outline. +fn corner_anchors(s: &Session, id: NodeId, corners: &[usize]) -> BTreeSet<AnchorRef> { + let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + lc.anchors_of(&corners.iter().copied().collect()) +} + +/// Adding an anchor point on a side of a rounded rectangle puts it on that side and keeps every +/// corner live at its radius, in one undo step, with the direct-selected anchors still on their +/// corner. Delete Anchor Point on it leaves the rectangle's outline with its corners still live. +#[test] +fn adding_and_deleting_an_anchor_on_a_side_keeps_the_corners_live() { + let (mut s, id) = session(); + run(&mut s, json!({"radius": 10})); + let before = node_path(&s, id).0; + let picked: Vec<[usize; 2]> = corner_anchors(&s, id, &[2]).into_iter().map(|(si, ai)| [si, ai]).collect(); + s.execute("select.anchors", &json!({"id": id.0, "anchors": picked, "mode": "set"})).unwrap(); + let seg = segment_between(&s, id, 0, 1); + let want = before.subpaths[0].segment(seg).eval(0.3); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("path.insertAnchor", &json!({"id": id.0, "segment": seg, "t": 0.3})).unwrap(); + assert!(r.get("warning").is_none(), "{r}"); + let ai = usize::try_from(r["anchor"].as_u64().unwrap()).unwrap(); + let (path, live) = node_path(&s, id); + assert!(matches!(live, Some(LiveShape::Path { .. })), "{live:?}"); + assert_eq!(live_radii(&s, id), Some(vec![10.0; 4])); + assert_eq!(path.anchor_count(), 9); + assert!(path.subpaths[0].anchors[ai].p.distance(want) < 1e-9, "{:?} vs {want:?}", path.subpaths[0].anchors[ai].p); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + // The new anchor is the outline's anchor 1, so the corner that was 2 is 3 now. + assert_eq!(selected_anchors(&s, id), Some(corner_anchors(&s, id, &[3]))); + + let r = s.execute("path.removeAnchor", &json!({"id": id.0, "anchor": ai})).unwrap(); + assert_eq!(r["removedObject"], false); + assert_eq!(live_radii(&s, id), Some(vec![10.0; 4])); + let after = node_path(&s, id).0; + assert_eq!(after.anchor_count(), 8); + for (_, _, a) in before.anchors() { + assert!(after.anchors().any(|(_, _, b)| b.p.distance(a.p) < 1e-9), "{:?} is still drawn", a.p); + } + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(corners(&s, id), ([10.0; 4], [CornerKind::Round; 4], 8)); +} + +/// Selected segments of a rounded rectangle stay selected when an anchor point is added on a +/// side: a selected side that is split gives both its halves and the new anchor, and the other +/// selected segments stay on the same sides and curves. +#[test] +fn adding_an_anchor_keeps_the_selected_segments_on_their_sides() { + let (mut s, id) = session(); + run(&mut s, json!({"radius": 10})); + let (top, curve, bottom) = (segment_between(&s, id, 0, 1), segment_between(&s, id, 2, 2), segment_between(&s, id, 2, 3)); + s.execute("select.segments", &json!({"id": id.0, "segments": [[0, top], [0, curve], [0, bottom]], "mode": "set"})).unwrap(); + let r = s.execute("path.insertAnchor", &json!({"id": id.0, "segment": top, "t": 0.5})).unwrap(); + let ai = usize::try_from(r["anchor"].as_u64().unwrap()).unwrap(); + // The new anchor is the outline's anchor 1, so corners 1, 2 and 3 are 2, 3 and 4 now. + let want: BTreeSet<_> = + [segment_between(&s, id, 0, 1), segment_between(&s, id, 1, 2), segment_between(&s, id, 3, 3), segment_between(&s, id, 3, 4)] + .map(|g| (0, g)) + .into(); + let st = s.doc().unwrap(); + assert_eq!(st.selection.segments.get(&id), Some(&want)); + assert!(st.selection.anchors.get(&id).is_some_and(|a| a.contains(&(0, ai))), "{:?}", st.selection.anchors); +} + +/// An anchor point added on a corner's curve turns the corners into plain anchor points, as +/// before, and the status bar says so. +#[test] +fn adding_an_anchor_on_a_corners_curve_expands_the_corners_and_warns() { + let (mut s, id) = session(); + run(&mut s, json!({"radius": 10})); + let seg = segment_between(&s, id, 1, 1); + let r = s.execute("path.insertAnchor", &json!({"id": id.0, "segment": seg, "t": 0.5})).unwrap(); + assert!(r["warning"].as_str().is_some_and(|w| w.contains("Live Corners")), "{r}"); + let (path, live) = node_path(&s, id); + assert_eq!((path.anchor_count(), live), (9, None)); +} + +/// Delete Anchor Point on either anchor of a cut corner removes that corner from the outline, and +/// the other corners stay live at their radii. +#[test] +fn deleting_an_anchor_of_a_cut_corner_removes_the_corner_and_keeps_the_rest_live() { + for end in 0..2 { + let (mut s, id) = session(); + run(&mut s, json!({"radius": 10})); + let (_, ai) = corner_anchors(&s, id, &[1]).into_iter().nth(end).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("path.removeAnchor", &json!({"id": id.0, "anchor": ai})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + assert_eq!(lc.base.anchor_count(), 3, "end {end}"); + assert!(lc.corners.iter().all(|c| c.at.distance(Point::new(110.0, 10.0)) > 1.0), "the top-right corner went"); + assert_eq!(live_radii(&s, id), Some(vec![10.0; 3]), "end {end}"); + assert_eq!(node_path(&s, id).0.anchor_count(), 6); + } +} + +/// Remove Anchor Points on a cut corner of a rounded rectangle keeps the other corners live and +/// selects an anchor of the next corner along, so the next Remove Anchor Points goes on there. +#[test] +fn remove_anchor_points_on_a_cut_corner_selects_the_next_corner() { + let (mut s, id) = session(); + run(&mut s, json!({"radius": 10})); + let picked: Vec<[usize; 2]> = corner_anchors(&s, id, &[1]).into_iter().map(|(si, ai)| [si, ai]).collect(); + s.execute("select.anchors", &json!({"id": id.0, "anchors": picked, "mode": "set"})).unwrap(); + s.execute("path.removeAnchors", &json!({})).unwrap(); + assert_eq!(live_radii(&s, id), Some(vec![10.0; 3])); + let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + // The bottom-right corner, which followed the removed one, is the outline's anchor 1 now. + assert!(lc.base.subpaths[0].anchors[1].p.distance(Point::new(110.0, 70.0)) < 1e-9); + assert_eq!(selected_anchors(&s, id), lc.drawn_anchor((0, 1)).map(|a| BTreeSet::from([a]))); +} + +/// Remove Anchor Points with one anchor of every cut corner selected removes every corner, so the +/// path goes, as a plain path with all its anchors removed does. +#[test] +fn removing_an_anchor_of_every_corner_removes_the_path() { + let (mut s, id) = session(); + run(&mut s, json!({"radius": 10})); + let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + let picked: Vec<[usize; 2]> = (0..4).filter_map(|k| lc.drawn_anchor((0, k))).map(|(si, ai)| [si, ai]).collect(); + assert_eq!(picked.len(), 4); + s.execute("select.anchors", &json!({"id": id.0, "anchors": picked, "mode": "set"})).unwrap(); + assert_eq!(s.execute("path.removeAnchors", &json!({})).unwrap()["removedObjects"], 1); + assert!(s.doc().unwrap().doc.node(id).is_none()); +} + +/// A relative radius keeps the length it is drawn at when an added anchor shortens the side its +/// corner's largest radius depends on. +#[test] +fn an_added_anchor_keeps_a_relative_radius_at_its_length() { + let (mut s, id) = session(); + run(&mut s, json!({"relativeRadii": true})); + let max = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().corner(0).unwrap().max_radius(); + run(&mut s, json!({"radius": 0.25 * max})); + let drawn = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().drawn_radius(0); + let seg = segment_between(&s, id, 0, 1); + s.execute("path.insertAnchor", &json!({"id": id.0, "segment": seg, "t": 0.5})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert!(matches!(n.live_shape(), Some(LiveShape::Path { radii_relative: true, .. })), "{:?}", n.live_shape()); + let lc = LiveCorners::of(n).unwrap(); + assert!((lc.drawn_radius(0) - drawn).abs() < 1e-9, "{} vs {drawn}", lc.drawn_radius(0)); +} diff --git a/docs/mcp.md b/docs/mcp.md index 718c5c367c..17e3c9d391 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9450,6 +9450,15 @@ unevenly scaled, when an arrow-key nudge's selected curved segments bend or hold direct-selected anchors is other than a move. A nudge that changes nothing, including one that the pixel-grid snap of a pixel-aligned path takes back (objects selected whole beside the anchors included), records no undo step and leaves Live Corners as they are: a live rectangle stays a live rectangle. These fallbacks edit the drawn anchors rather than recutting the uncut outline. +Adding and removing anchors keeps such corners live as well: `path.insertAnchor` on a straight or curved side puts the +new anchor on that side of the uncut outline, at the point the drawn segment has at `t`, with no radius. `path.removeAnchor`, +`path.removeAnchors` and the Delete key with `deleteKeepsPathsJoined` on remove the uncut corner each removed anchor +belongs to, so removing either end of a corner's arc removes that corner. The other corners are cut again at their radii +and kinds; a relative radius keeps the length it is drawn at, up to the corner's new largest radius. The selected anchors +and segments follow their corners, a selected segment that the new anchor splits stays selected as its two halves with +the new anchor, and `path.removeAnchors` selects the first anchor of the next corner along. An anchor added on a corner's +arc, or on a path the fallbacks above apply to, makes the shape a plain path, and when the path had rounded corners +`path.insertAnchor` answers with a `warning`, which the status bar shows. `path.setHandle` with `symmetric: true` also places the anchor's other handle opposite the moved one at the same length, and the anchor keeps its kind. At an open end, where no segment leaves the anchor on the other side, `symmetric` has no effect and the handle moves as it would without it. Both `symmetric` and `independent` default to false, and a call with both true is @@ -10539,8 +10548,9 @@ the corners holding a Direct-Selected anchor, or every corner of a path selected hold no corner is left out. The pop-up has the corner kind, the radius (blank while the picked corners differ) and the rounding, Relative or Absolute (`relativeRadii`, which applies to each path as a whole; neither is chosen while the paths differ). A path without Live Corners is Absolute: Relative leaves it, an ellipse or a line as it is, with no -undo step. Moving a path's anchors with `path.moveAnchor`, `path.moveAnchors` or the arrow keys keeps Live Corners and -the radius mode under the rules above. An anchor edit that makes the shape a plain path ends Live Corners and resets +undo step. Moving a path's anchors with `path.moveAnchor`, `path.moveAnchors` or the arrow keys, and adding or removing +anchors with `path.insertAnchor`, `path.removeAnchor` or `path.removeAnchors`, keeps Live Corners and the radius mode +under the rules above. An anchor edit that makes the shape a plain path ends Live Corners and resets the radius mode to Absolute. With Relative rounding, a radius is compared as the fraction it stores (its share of the corner's maximum, at most all of it), so typing the radius diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3ded4be862..e925ceea72 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -867,6 +867,7 @@ since 2026-10-01. - **Shift-click on corner widgets (#5188):** with Direct Selection, when every corner of every selected path is selected (the paths selected whole), a Shift-click on a corner widget picks that corner alone, so the next drag rounds just it. When another selected path has only some corners picked, a Shift-click on a widget of a path selected whole deselects that corner and keeps the other picks. The other corners' widgets then show as not picked; a Shift-click on another corner's anchor or widget adds that corner, and a Shift-click on a picked widget deselects its corner. Corner widgets are chosen by clicking one and Shift-clicking the others ([a tutorial on rounded corners](https://logosbynick.com/?p=15787)). Test: `corners::tests::a_shift_click_on_a_widget_of_a_whole_path_picks_its_corner`. - **Picking corner widgets (#1232):** with Direct Selection, every corner's widget shows while some corners are picked: a picked corner's widget has a dot at its center and the others are hollow. A click on a widget that is not picked picks its corner alone, a Shift-click adds or removes a corner across selected paths, and a double-click on a picked widget opens Corners for the picked corners of its path ([Live Corners help page, archived](https://web.archive.org/web/2019/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html)). As VectorCraft's own rules, a plain click on a picked widget keeps the picks (while every corner of every selected path is picked, it picks that corner alone, and a double-click then opens Corners for that corner), a drag or Alt-click on a widget that is not picked edits its corner together with the picked ones, and over a widget that is not picked, a selected anchor's handle end or a nearer anchor takes the press. Tests: `corners::tests::a_press_on_a_widget_not_picked_edits_it_with_the_picked_corners`, `corners::tests::widgets_are_picked_across_paths`, `corners::tests::a_handle_end_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_nearer_anchor_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_shift_click_toggles_a_rounded_corner_whole`, `corners::tests::a_path_with_hidden_widgets_keeps_its_picks`, `tests::corner_widgets_pick_corners_across_paths_through_the_session`. - **Anchor edits keep Live Corners (#10545):** moving an anchor of a path with rounded corners (Direct Selection drag, arrow keys, `path.moveAnchor`) moves its uncut corner by the drag delta and recuts it at its radius. A grabbed arc end can finish away from a snap target. A live rectangle or polygon becomes a path with live corners. When the anchor layout changes, the path's whole anchor selection is remapped and its segment selection is cleared. A corner that a move straightens keeps its radius and rounds again when a later move bends it. An anchor edit makes the shape a plain path when no anchor stores a radius above 0 (a straightened corner's stored radius keeps the path live), a live rectangle is sheared or unevenly scaled, an arrow-key nudge bends selected curved segments or holds their anchors, or direct-selected anchors receive a transform other than a move. A nudge that changes nothing, including one that the pixel-grid snap of pixel-aligned paths takes back (with objects selected whole too), records no undo step and leaves Live Corners as they are: a live rectangle stays a live rectangle. These are VectorCraft's own rules. Tests: `tests::livecorners::moving_an_anchor_keeps_the_corners_live`, `tests::livecorners::dragging_selected_anchors_keeps_the_corners_live`, `tests::livecorners::moving_an_anchor_of_a_distorted_rectangle_edits_the_drawn_path`, `tests::livecorners::a_recut_remaps_the_whole_anchor_selection`, `tests::livecorners::a_recut_clears_segments_even_when_selected_anchor_indices_stay_the_same`, `tests::livecorners::an_unchanged_corner_layout_keeps_the_selection`, `corners::tests::a_straightened_corner_rounds_again_when_it_bends_back`. +- **Adding and removing anchors keeps Live Corners (#10545):** the Pen, Add Anchor Point and Delete Anchor Point tools, Object › Path › Remove Anchor Points and the Delete key with Delete Removes Anchor Points and Keeps Paths Joined on (`path.insertAnchor`, `path.removeAnchor`, `path.removeAnchors`) edit the uncut outline of a path with rounded corners and cut its corners again at their radii and kinds, so the corner widgets stay. An anchor added on a side has no radius; removing either end of a corner's arc removes that corner; a relative radius keeps its drawn length, up to the corner's new largest radius. Selected anchors and segments follow their corners, and Remove Anchor Points selects the first anchor of the next corner. An anchor added on a corner's arc makes the path plain, and the status bar says the corners were expanded. These are VectorCraft's own rules. Tests: `tests::livecorners::adding_and_deleting_an_anchor_on_a_side_keeps_the_corners_live`, `tests::livecorners::adding_an_anchor_keeps_the_selected_segments_on_their_sides`, `tests::livecorners::adding_an_anchor_on_a_corners_curve_expands_the_corners_and_warns`, `tests::livecorners::deleting_an_anchor_of_a_cut_corner_removes_the_corner_and_keeps_the_rest_live`, `tests::livecorners::remove_anchor_points_on_a_cut_corner_selects_the_next_corner`, `tests::livecorners::an_added_anchor_keeps_a_relative_radius_at_its_length`. - **TIFF in screen and asset export:** both format menus expose the existing TIFF encoder and Format Settings. Headless UI regressions choose TIFF and check scaled dimensions, artboard selection, filenames, encoding options, saved settings and collected-asset output. Public reference: [Export for Screens](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-for-screens.html), updated 2026-09-28, lists TIFF for both artboards and assets. Adobe staff [confirmed support in 30.2.1](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/49081034-add-tiff-format-into-export-for-screens-assets-d) on 2026-02-19; the older 2025 Collect assets guide omits TIFF. - **Lossy WebP with a Quality setting:** WebP Options has a Compression menu (Lossless, Lossy) and a Quality slider from 0 to 100 that is enabled for Lossy. Lossy writes a `VP8 ` WebP file, with an `ALPH` chunk that keeps the alpha exactly when some pixels are not opaque. `document.export`, `document.serialize` and Export for Screens take `lossless: false` with `quality` (default 90, VectorCraft's own value), in a format row or in `settings.webp`; Format Settings for WebP keeps both. Lossless stays the default, and a quality above 100 or one that is not a whole number is refused. Public reference: [export file format options](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) describes Lossless and Lossy WebP and a Quality setting for Lossy (`webp_is_lossless_by_default_and_lossy_when_asked`, `lossy_webp_keeps_translucent_pixels`, `webp_quality_out_of_its_range_is_refused` in `crates/engine/src/cmd/fileio/tests_text.rs`, `webp_options_choose_lossless_or_lossy_at_a_quality`). - **Export for Screens of the selected artboards:** while the Artboard tool is in use, File › Export › Export for Screens… (`file.exportForScreens`) opens with the artboards the tool has selected checked on its Artboards tab, and Export Artboard writes only those. Shift-clicks on the canvas, or Shift- or Ctrl/Cmd-clicks on the Artboards panel's rows, select several. The other fields show the settings the document last exported with. With another tool in use, the dialog takes its artboard choice from those settings too. Public reference: [Export selected artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/export-artboards.html). From e69d6c6fcb1fa57efe4fe3d9db382473eb4a011f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 04:03:28 -0800 Subject: [PATCH 77/88] Dialogs: Effect Gallery, Bullets and Numbering and the text style options leave the canvas undimmed Effect Gallery, Bullets and Numbering, Character Style Options and Paragraph Style Options preview on the canvas, but the modal layer dimmed it, so the preview did not show its true colors, and the wheel over the canvas did nothing while they were open. - Effect Gallery and Bullets and Numbering store the current window's canvas (`preview_canvas`) when they open and keep its view open from the dialog body (`Sampler::keep_view_open`), as ParamDialog does. - Character Style Options and Paragraph Style Options pass the canvas to `PropertiesDialog::canvas`. New Character Style and New Paragraph Style do not preview and still cover the canvas. - Every craft-libs rev moves to the head of storytold/craft-libs#5510, which adds `PropertiesDialog::canvas`. Part of #10590. --- Cargo.lock | 182 +++++++++--------- Cargo.toml | 82 ++++---- apps/vectorcraft-web/Cargo.toml | 2 +- .../ui-egui/src/dialogs/bullets_numbering.rs | 11 +- .../ui-egui/src/dialogs/char_style_options.rs | 16 +- crates/ui-egui/src/dialogs/effect_gallery.rs | 14 +- crates/ui-egui/src/dialogs/new_text_style.rs | 4 +- .../ui-egui/src/dialogs/para_style_options.rs | 18 +- crates/ui-egui/src/tests/preview_canvas.rs | 37 ++++ docs/mcp.md | 5 +- xtask/src/pdf_deps.rs | 2 +- 11 files changed, 222 insertions(+), 151 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b878d75456..b764109162 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1256,7 +1256,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-automation", "craft-behavior", @@ -1298,7 +1298,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "crc32fast", "flate2", @@ -1319,7 +1319,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1331,7 +1331,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "rustix 1.1.6", ] @@ -1339,7 +1339,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1364,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1383,7 +1383,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-docpath", @@ -1401,7 +1401,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "crc32fast", "flate2", @@ -1410,7 +1410,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "egui", ] @@ -1418,7 +1418,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "md-5", "rayon", @@ -1427,12 +1427,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-cms", @@ -1452,7 +1452,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-ai-agents", "craft-atomic", @@ -1468,7 +1468,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1478,7 +1478,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "rayon", ] @@ -1486,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1512,7 +1512,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "blake3", "craft-ecproj-format", @@ -1528,7 +1528,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "serde", ] @@ -1536,7 +1536,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1555,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-dwg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "acadrust", "craft-dxf", @@ -1565,7 +1565,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-codepage", "encoding_rs", @@ -1577,7 +1577,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "serde", "serde_json", @@ -1587,12 +1587,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-atomic", "dirs", @@ -1602,7 +1602,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1617,7 +1617,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1636,7 +1636,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1645,7 +1645,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "cap-primitives", "craft-atomic", @@ -1668,12 +1668,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "gif", ] @@ -1681,7 +1681,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "flate2", ] @@ -1689,7 +1689,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1702,7 +1702,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1732,7 +1732,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-dds", "craft-jpeg", @@ -1759,7 +1759,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1777,7 +1777,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "thiserror 2.0.21", ] @@ -1785,7 +1785,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1796,7 +1796,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-host", "craft-i18n", @@ -1811,7 +1811,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-i18n", @@ -1825,7 +1825,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-host", @@ -1843,7 +1843,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1855,7 +1855,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "encoding_rs", "image", @@ -1866,7 +1866,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "chrono", "craft-codepage", @@ -1876,7 +1876,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "uds_windows", "winsafe", @@ -1885,7 +1885,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-keymap", @@ -1901,7 +1901,7 @@ dependencies = [ [[package]] name = "craft-pbr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-texture", "thiserror 2.0.21", @@ -1910,7 +1910,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "flate2", "serde", @@ -1921,7 +1921,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1933,7 +1933,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "async-channel", "async-io", @@ -1966,7 +1966,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1975,7 +1975,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-host", @@ -1999,7 +1999,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -2010,7 +2010,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-eps", "flate2", @@ -2024,7 +2024,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "encoding_rs", "flate2", @@ -2035,7 +2035,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "dispatch2", "egui", @@ -2048,7 +2048,7 @@ dependencies = [ [[package]] name = "craft-raster3d" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "rayon", "thiserror 2.0.21", @@ -2057,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -2076,7 +2076,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-atomic", "craft-host", @@ -2093,7 +2093,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "fax", "hayro-ccitt", @@ -2104,7 +2104,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2125,7 +2125,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-keymap", @@ -2137,7 +2137,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2162,7 +2162,7 @@ dependencies = [ [[package]] name = "craft-texture" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "thiserror 2.0.21", ] @@ -2170,7 +2170,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2185,7 +2185,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-atomic", "craft-behavior", @@ -2200,7 +2200,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "serde", "thiserror 2.0.21", @@ -2210,7 +2210,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "serde", "thiserror 2.0.21", @@ -2219,7 +2219,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-keymap", @@ -2234,12 +2234,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2253,7 +2253,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -2270,7 +2270,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "accesskit", "craft-behavior", @@ -2308,7 +2308,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2319,7 +2319,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-host", @@ -2337,7 +2337,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-host", @@ -2358,7 +2358,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-host", @@ -2379,7 +2379,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-behavior", "craft-host", @@ -2398,7 +2398,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "base64 0.22.1", "chrono", @@ -2430,7 +2430,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "flate2", "serde", @@ -2441,7 +2441,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2451,7 +2451,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "js-sys", "serde_json", @@ -2462,7 +2462,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "winsafe", ] @@ -2470,7 +2470,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "craft-appkit", "craft-atomic", @@ -2502,7 +2502,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3862,7 +3862,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3871,7 +3871,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3889,7 +3889,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3907,12 +3907,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "flate2", "hayro-ccitt", @@ -4895,7 +4895,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "base64 0.22.1", "bumpalo", @@ -5052,7 +5052,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=4c330f6bd1f38dd536f830483ea9618db2cb2bd8#4c330f6bd1f38dd536f830483ea9618db2cb2bd8" +source = "git+https://github.com/storytold/craft-libs?rev=dfd876669dd3d64f0061ab510a94b866a1ae35ab#dfd876669dd3d64f0061ab510a94b866a1ae35ab" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index a48e3c1330..c3b9ba393e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,57 +10,57 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } # 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } # DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified). -craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } # The metallic-roughness BRDF and environment light the 3D effects' Roughness and Metallic shade with. -craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } # The CPU rasterizer that draws a 3D effect's Render Settings › Rendered image: depth-buffered triangles, shadow maps. -craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -200,13 +200,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab" } # skrifa 0.44 (epaint, glifo, usvg) with the automatic hinter's long blue-zone exit (craft-libs vendor/skrifa). # It stays at this rev until craft-libs#5222 merges. skrifa = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 4db9a1dac2..70ffa47530 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "dfd876669dd3d64f0061ab510a94b866a1ae35ab", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index 5812e37270..c8ac078cda 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -29,7 +29,7 @@ use std::sync::{Arc, Weak}; use craft::behavior::{EditEvent, EditEvents, Mixed, Selection, SelectionChange, keyed}; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; +use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Sampler as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; use craft::ui::display::Text; use craft::ui::form::{Field, FieldGroup}; @@ -53,6 +53,7 @@ use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, MAX_LIST_START, Nu use crate::VectorcraftApp; use crate::panels::paragraph::BulletGlyph; +use super::host::preview_canvas; use super::preview::LivePreview; /// The dialog kind of Bullets and Numbering. @@ -131,6 +132,9 @@ pub(crate) struct BulletsDialog { active_document: bool, held: HeldAnswer<Map<String, Value>>, open: bool, + /// The canvas the dialog previews on (from [`preview_canvas`]): the modal layer leaves it undimmed, and the wheel + /// still moves its view. + canvas: Option<egui::Id>, } /// The preview from the opening drawing and the interaction that owns its undo snapshot. @@ -269,6 +273,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { active_document: true, held: HeldAnswer::default(), open: true, + canvas: preview_canvas(app), }; host.with(|h| h.open(dialog)); app.bullets_preview = Some(Preview { document, live: LivePreview::default(), selection: None }); @@ -572,11 +577,15 @@ impl StackDialog for BulletsDialog { FooterButton::new(common.cancel.clone(), DialogRole::Cancel), ]; let mut open = self.open; + let canvas = self.canvas; let dialog = Dialog::new(tl!("Bullets and Numbering")).buttons(buttons).opened(Bind::bound(&mut open)).refusal(move || refusal.clone()); let shown = dialog.show(ui, |ui, cx| { if finish && !measure::active(ui.ctx()) { cx.request_close_as(CloseReason::Activated); } + if let Some(canvas) = canvas { + cx.keep_view_open(canvas); + } self.body(ui); }); self.open = open; diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 584964e0c4..428875120e 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -23,6 +23,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::setup::DocSetup; use vectorcraft_engine::cmd::textstyles::NORMAL_CHAR; +use super::host::preview_canvas; use super::preview::LivePreview; use crate::VectorcraftApp; @@ -1036,12 +1037,18 @@ pub(crate) fn tabs(fields: &DialogFields, opening: &Opening) -> Vec<PropertiesTa .collect() } -/// The dialog of style `name` over `opening`, which `title` heads, kept open by a held OK. -pub(crate) fn hosted(key: &'static str, title: &'static str, opening: &Arc<Opening>, name: &str) -> HostedPropertiesDialog { +/// The dialog of style `name` over `opening`, which `title` heads, kept open by a held OK. A dialog that previews on +/// the document passes its `canvas` (from [`preview_canvas`]): the modal layer leaves it undimmed, and the wheel still +/// moves its view. +pub(crate) fn hosted(key: &'static str, title: &'static str, opening: &Arc<Opening>, name: &str, canvas: Option<egui::Id>) -> HostedPropertiesDialog { let rows_of = Arc::clone(opening); HostedPropertiesDialog::new(key, opening.fields(name), move |values| { let now = values.value().cloned().unwrap_or_else(DialogFields::new); - PropertiesDialog::new(key, title, tabs(&now, &rows_of), values).tab_layout(TabLayout::List) + let dialog = PropertiesDialog::new(key, title, tabs(&now, &rows_of), values).tab_layout(TabLayout::List); + match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + } }) .held_ok() } @@ -1196,6 +1203,7 @@ pub(crate) struct Preview { pub fn open(app: &mut VectorcraftApp, name: &str) -> Result<Value, String> { crate::panels::character::end_typing(app); + let canvas = preview_canvas(app); let state = app.session.active().ok_or("no document open")?; let (document, doc) = ((state.uid, state.reverts), &state.doc); // [Normal Character Style] has no definition until it is first redefined: it sets nothing. @@ -1205,7 +1213,7 @@ pub fn open(app: &mut VectorcraftApp, name: &str) -> Result<Value, String> { None => return Err(format!("no character style `{name}`")), }; let opening = Arc::new(Opening::new(name, attrs, &doc.setup, swatch_choices(doc))); - let dialog = CharStyleOptions { inner: hosted(KIND, tl!("Character Style Options"), &opening, name).previews(), opening, document }; + let dialog = CharStyleOptions { inner: hosted(KIND, tl!("Character Style Options"), &opening, name, canvas).previews(), opening, document }; app.dialogs().ok_or("no window")?.with(|host| host.open(dialog)); Ok(json!({"dialog": KIND})) } diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index b9783083bc..6965493c9c 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -18,7 +18,7 @@ use craft::imaging::ui::filter_gallery::{ }; use craft::theme::variant::Tone; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Props as _, Sampler as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, HoldsOk, StackDialog, dialog_id}; use craft::ui::display::{Picture, PictureSize}; use craft::ui::layout_components::{Row, Stack}; @@ -39,7 +39,7 @@ use vectorcraft_geom::{Affine, Point}; use super::effect; use super::effect_params::{EffectCx, effect_params}; use super::form::json_of; -use super::host::{HeldOptions, open_held_with}; +use super::host::{HeldOptions, open_held_with, preview_canvas}; use super::preview::LivePreview; use crate::VectorcraftApp; use crate::file_asks::Owner; @@ -343,6 +343,9 @@ pub(crate) struct EffectGalleryDialog { held: HeldAnswer<Value>, /// A Browse press waiting for the app's file dialog, with the layer it belongs to. asked: Option<LayerId>, + /// The canvas the gallery previews on (from [`preview_canvas`]): the modal layer leaves it undimmed, and the + /// wheel still moves its view. + canvas: Option<egui::Id>, } impl EffectGalleryDialog { @@ -363,6 +366,7 @@ impl EffectGalleryDialog { preview_on: true, held: HeldAnswer::new(), asked: None, + canvas: preview_canvas(app), } } @@ -423,7 +427,8 @@ impl StackDialog for EffectGalleryDialog { fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<Value>> { let words = Env::of(ui).words::<CommonWords>(); - let EffectGalleryDialog { open, catalog, index, session, selected, preview_on, held, asked, .. } = self; + let EffectGalleryDialog { open, catalog, index, session, selected, preview_on, held, asked, canvas, .. } = self; + let canvas = *canvas; // The app accepted the held OK: this pass closes the dialog with it. A measuring run closes nothing. let finish = held.is_accepted() && !craft::ui::runtime::measure::active(ui.ctx()); // A refusal is cleared once the stack changes, so one still held is for the stack shown. @@ -456,6 +461,9 @@ impl StackDialog for EffectGalleryDialog { if finish { cx.request_close_as(CloseReason::Activated); } + if let Some(canvas) = canvas { + cx.keep_view_open(canvas); + } let Some(layer) = effects.get(current) else { return }; let image = || color_image(&preview_rgba(&visible, PREVIEW_W, PREVIEW_H), PREVIEW_W, PREVIEW_H); Stack::new().show(ui, |ui, _| { diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index b94bf89708..e4da81c6f4 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -65,11 +65,11 @@ pub fn open(app: &mut VectorcraftApp, para: bool, target: Value) -> Result<Value target["attrs"] = Value::Object(attrs.clone()); let (opening, inner) = if para { let opening = Arc::new(para_style_options::Opening::new("", attrs, app.session.general_unit(), para_style_options::vertical_text(app))); - let inner = para_style_options::hosted(KIND, tl!("New Paragraph Style"), &opening, &name); + let inner = para_style_options::hosted(KIND, tl!("New Paragraph Style"), &opening, &name, None); (Opening::Para(opening), inner) } else { let opening = Arc::new(char_style_options::Opening::new("", attrs, &doc.setup, char_style_options::swatch_choices(doc))); - let inner = char_style_options::hosted(KIND, tl!("New Character Style"), &opening, &name); + let inner = char_style_options::hosted(KIND, tl!("New Character Style"), &opening, &name, None); (Opening::Char(opening), inner) }; app.dialogs().ok_or("no window")?.with(|host| host.open(NewTextStyle { inner, opening, para, document, target })); diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index d8483e4543..652ceef10b 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -28,6 +28,7 @@ use vectorcraft_engine::cmd::textstyles::NORMAL_PARA; use super::char_style_options::{ Refusals, Values, canonical_map, general_rows, pump_in_opening_document, rows, select, style_dialog, text, to_fields, tri_state, value_of, }; +use super::host::preview_canvas; use crate::VectorcraftApp; pub const KIND: &str = "paraStyleOptions"; @@ -809,13 +810,19 @@ pub(crate) fn tabs(fields: &DialogFields, opening: &Opening) -> Vec<PropertiesTa .collect() } -/// The dialog of style `name` over `opening`, which `title` heads, kept open by a held OK. -pub(crate) fn hosted(key: &'static str, title: &'static str, opening: &Arc<Opening>, name: &str) -> HostedPropertiesDialog { +/// The dialog of style `name` over `opening`, which `title` heads, kept open by a held OK. A dialog that previews on +/// the document passes its `canvas` (from [`preview_canvas`]): the modal layer leaves it undimmed, and the wheel still +/// moves its view. +pub(crate) fn hosted(key: &'static str, title: &'static str, opening: &Arc<Opening>, name: &str, canvas: Option<egui::Id>) -> HostedPropertiesDialog { let rows_of = Arc::clone(opening); HostedPropertiesDialog::new(key, opening.fields(name), move |values| { let now = values.value().cloned().unwrap_or_else(DialogFields::new); - craft::ui::patterns::form_dialogs::PropertiesDialog::new(key, title, tabs(&now, &rows_of), values) - .tab_layout(craft::ui::patterns::form_dialogs::TabLayout::List) + let dialog = craft::ui::patterns::form_dialogs::PropertiesDialog::new(key, title, tabs(&now, &rows_of), values) + .tab_layout(craft::ui::patterns::form_dialogs::TabLayout::List); + match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + } }) .held_ok() } @@ -844,6 +851,7 @@ style_dialog!(ParaStyleOptions, KIND); pub fn open(app: &mut VectorcraftApp, name: &str) -> Result<Value, String> { crate::panels::character::end_typing(app); let unit = app.session.general_unit(); + let canvas = preview_canvas(app); let state = app.session.active().ok_or("no document open")?; let (document, doc) = ((state.uid, state.reverts), &state.doc); // [Normal Paragraph Style] has no definition until it is first redefined: it sets nothing. @@ -853,7 +861,7 @@ pub fn open(app: &mut VectorcraftApp, name: &str) -> Result<Value, String> { None => return Err(format!("no style `{name}`")), }; let opening = Arc::new(Opening::new(name, attrs, unit, vertical_text(app))); - let dialog = ParaStyleOptions { inner: hosted(KIND, tl!("Paragraph Style Options"), &opening, name).previews(), opening, document }; + let dialog = ParaStyleOptions { inner: hosted(KIND, tl!("Paragraph Style Options"), &opening, name, canvas).previews(), opening, document }; app.dialogs().ok_or("no window")?.with(|host| host.open(dialog)); Ok(json!({"dialog": KIND})) } diff --git a/crates/ui-egui/src/tests/preview_canvas.rs b/crates/ui-egui/src/tests/preview_canvas.rs index 6f9a5d0b0b..cff64e3350 100644 --- a/crates/ui-egui/src/tests/preview_canvas.rs +++ b/crates/ui-egui/src/tests/preview_canvas.rs @@ -80,3 +80,40 @@ fn a_previewing_command_dialog_keeps_the_canvas_open() { crate::dialogs::command::open(&mut app, crate::addons::pathtools::BOUNDING_RECTANGLE, "Bounding Rectangle", Map::new()).unwrap(); assert!(wheel_scrolls_the_view(&mut app, &ctx), "the wheel over the canvas scrolls the view under the command's dialog"); } + +#[test] +fn the_effect_gallery_keeps_the_canvas_open() { + let (mut app, ctx) = app(); + app.run("ui.effectGalleryDialog", json!({})).unwrap(); + assert!(wheel_scrolls_the_view(&mut app, &ctx), "the wheel over the canvas scrolls the view under the Effect Gallery"); +} + +#[test] +fn bullets_and_numbering_keeps_the_canvas_open() { + let (mut app, ctx) = app(); + app.run("text.create", json!({"x": 100, "y": 150, "text": "One"})).unwrap(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + assert!(wheel_scrolls_the_view(&mut app, &ctx), "the wheel over the canvas scrolls the view under Bullets and Numbering"); +} + +#[test] +fn character_style_options_keeps_the_canvas_open() { + let (mut app, ctx) = app(); + app.run("ui.charStyleOptions", json!({"name": vectorcraft_engine::cmd::textstyles::NORMAL_CHAR})).unwrap(); + assert!(wheel_scrolls_the_view(&mut app, &ctx), "the wheel over the canvas scrolls the view under Character Style Options"); +} + +#[test] +fn paragraph_style_options_keeps_the_canvas_open() { + let (mut app, ctx) = app(); + app.run("ui.paraStyleOptions", json!({"name": vectorcraft_engine::cmd::textstyles::NORMAL_PARA})).unwrap(); + assert!(wheel_scrolls_the_view(&mut app, &ctx), "the wheel over the canvas scrolls the view under Paragraph Style Options"); +} + +/// New Character Style shares the style dialog but does not preview, so the canvas stays covered. +#[test] +fn new_character_style_leaves_the_canvas_covered() { + let (mut app, ctx) = app(); + app.run("ui.newCharStyle", json!({})).unwrap(); + assert!(!wheel_scrolls_the_view(&mut app, &ctx), "the wheel over the canvas does not reach the view"); +} diff --git a/docs/mcp.md b/docs/mcp.md index e566d33f70..a861400a14 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17539,8 +17539,9 @@ nothing, and a call that changes no blend records no undo step. With no blend se spacing and orientation new blends start with. The Blend panel's Ramp and Shift sliders run it on the selected blends: a drag previews and its release records one undo step. Blend Options sends only the spacing or orientation set in the dialog. While Blend Options previews a selected blend, the canvas of the current window is not dimmed under the dialog, and the -wheel over it still scrolls the view. Other dialogs with a Preview box on the canvas (envelope, path, Flare Tool, -Justification, Proof Setup, Swatch Options, add-on and command dialogs) work the same way. +wheel over it still scrolls the view. Other dialogs that preview on the canvas (envelope, path, Flare Tool, +Justification, Proof Setup, Swatch Options, Effect Gallery, Bullets and Numbering, Character Style Options, Paragraph +Style Options, add-on and command dialogs) work the same way. `object.blend.setEasing {id?, easingType?, ramp?, colorShift?}` sets one blend's easing and color shift (the first selected blend without `id`) and returns `{id, easingType, ramp, colorShift, changed}`; omitted values are kept. diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 04cf313ca0..4bc9306551 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 = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8"; +const REV: &str = "dfd876669dd3d64f0061ab510a94b866a1ae35ab"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From 1215d59e0051302e8a86f66de1482ace5acf25df Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 04:46:50 -0800 Subject: [PATCH 78/88] DWG import: a drawing of a version the reader skips names its version Opening or placing a DWG drawing whose version code the converter does not read now fails with a message that names the version and says to save the drawing as DXF, or as a DWG from R10 to 2018. That covers R1.0 to R9 (MC0.0, AC1.2 to AC2.22, AC1001 to AC1004), codes newer than AC1032 and unknown codes. Before, R2.5 to R9 drawings went to the converter and failed with its own error, and R1.x and R2.x drawings got a message that did not name the version. Version names follow https://en.wikipedia.org/wiki/.dwg#Version_history. A drawing that starts with an AD10nn code is read as a DWG drawing, as the converter reads AD1009 and AD1012 to AD1032; before, it was read as DXF and failed with "not a DXF drawing". A file that holds only a version code says it is cut short. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/cad/src/dwg.rs | 115 ++++++++++++++++++++++++++++- crates/cad/src/import.rs | 9 ++- crates/cad/src/import/tests_dwg.rs | 21 +++++- docs/mcp.md | 8 +- docs/target-app-parity.md | 2 +- 5 files changed, 144 insertions(+), 11 deletions(-) diff --git a/crates/cad/src/dwg.rs b/crates/cad/src/dwg.rs index c49beecb99..e399d63d77 100644 --- a/crates/cad/src/dwg.rs +++ b/crates/cad/src/dwg.rs @@ -62,9 +62,72 @@ pub fn use_own_worker_for(limit: std::time::Duration) { /// The largest DXF rendition kept for the next read of the same drawing (128 MiB). const MAX_KEPT: usize = 128 << 20; -/// Is `bytes` a DWG drawing (an `AC10nn` version code first)? +/// Is `bytes` a DWG drawing (an `AC10nn` or `AD10nn` version code first)? pub fn is_dwg(bytes: &[u8]) -> bool { - craft_dwg::is_dwg(bytes) + craft_dwg::is_dwg(bytes) || craft_dwg::is_dwg(&ac_code(bytes)) +} + +/// The first six bytes of `bytes`, with an `AD10` start read as `AC10`. +fn ac_code(bytes: &[u8]) -> Vec<u8> { + let mut head = bytes.get(..bytes.len().min(7)).unwrap_or(bytes).to_vec(); + if head.starts_with(b"AD10") { + head[1] = b'C'; + } + head +} + +/// The version codes of DWG drawings and the name of each version, oldest first +/// (<https://en.wikipedia.org/wiki/.dwg#Version_history>). +const VERSIONS: [(&str, &str); 21] = [ + ("MC0.0", "R1.0"), + ("AC1.2", "R1.2"), + ("AC1.40", "R1.40"), + ("AC1.50", "R2.05"), + ("AC2.10", "R2.10"), + ("AC2.21", "R2.21"), + ("AC2.22", "R2.22"), + ("AC1001", "R2.22"), + ("AC1002", "R2.50"), + ("AC1003", "R2.60"), + ("AC1004", "R9"), + ("AC1006", "R10"), + ("AC1009", "R11/12"), + ("AC1012", "R13"), + ("AC1014", "R14"), + ("AC1015", "2000"), + ("AC1018", "2004"), + ("AC1021", "2007"), + ("AC1024", "2010"), + ("AC1027", "2013"), + ("AC1032", "2018"), +]; + +/// The version codes the DWG reader reads, each also with `AD` in place of `AC` except `AC1006`. +const READS: [&str; 10] = ["AC1006", "AC1009", "AC1012", "AC1014", "AC1015", "AC1018", "AC1021", "AC1024", "AC1027", "AC1032"]; + +/// Why `bytes` can't be read when they start with a DWG version code that the DWG reader does +/// not read: the message names the version and says to save the drawing as DXF or as a DWG +/// version that is read. `None` for any other bytes, a DWG drawing of a version that is read +/// included. +pub fn unreadable(bytes: &[u8]) -> Option<String> { + let head = ac_code(bytes); + let numbered = head.starts_with(b"AC10"); + if !numbered && ![&b"MC0."[..], b"AC1.", b"AC2."].iter().any(|m| head.starts_with(m)) { + return None; + } + if numbered && READS.iter().any(|c| head.starts_with(c.as_bytes())) && !bytes.starts_with(b"AD1006") { + return None; + } + let named = match VERSIONS.iter().find(|(c, _)| head.starts_with(c.as_bytes())) { + Some((code, name)) => format!("DWG {name} ({})", if bytes.starts_with(b"AD") { code.replacen("AC", "AD", 1) } else { code.to_string() }), + None => { + let shown: String = bytes.iter().take(6).take_while(|b| b.is_ascii_graphic()).map(|&b| char::from(b)).collect(); + format!("DWG version {shown}") + } + }; + Some(format!( + "this drawing is {named}, a DWG version VectorCraft can't read: save it from the CAD app as a DXF, or as a DWG from R10 to 2018, and open that" + )) } /// A DWG drawing as DXF bytes, and what the conversion left out. @@ -173,6 +236,9 @@ pub fn hold(bytes: &[u8]) -> Result<Held, String> { } fn convert(bytes: &[u8]) -> Result<Converted, String> { + if let Some(why) = unreadable(bytes) { + return Err(why); + } let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(|e| worded(&e))?; Ok(Converted { dxf, notes: notes.iter().map(|n| worded(n)).collect() }) } @@ -278,4 +344,49 @@ mod tests { let n = worded("DWG: 2 objects of types this bridge can't preserve were left out (X × 2); saving over the original file would lose them"); assert_eq!(n, "DWG: 2 objects of types VectorCraft can't read were left out (X × 2)"); } + + #[test] + fn a_dwg_version_the_reader_skips_is_named_with_what_to_save_it_as() { + let named = [ + (&b"AC1001\x00\x00\x00\x00"[..], "DWG R2.22 (AC1001)"), + (b"AD1006\x00\x00\x00\x00", "DWG R10 (AD1006)"), + (b"AD1004\x00\x00\x00\x00", "DWG R9 (AD1004)"), + (b"AC1.50\x00\x00\x00\x00", "DWG R2.05 (AC1.50)"), + (b"AC1.2\x00\x00\x00\x00", "DWG R1.2 (AC1.2)"), + (b"MC0.0\x00\x00\x00\x00", "DWG R1.0 (MC0.0)"), + (b"AC1033\x00\x00\x00\x00", "DWG version AC1033"), + (b"AC1010\x00\x00\x00\x00", "DWG version AC1010"), + (b"AC10\x00\x00\x00\x00", "DWG version AC10"), + ]; + for (bytes, name) in named { + let why = unreadable(bytes).unwrap_or_default(); + assert!(why.starts_with(&format!("this drawing is {name},")), "{name}: {why}"); + assert!(why.contains("as a DXF, or as a DWG from R10 to 2018"), "{why}"); + } + for read in [ + &b"AC1006\x00\x00"[..], + b"AC1009\x00\x00", + b"AD1009\x00\x00", + b"AC1018\x00\x00", + b"AC1032\x00\x00", + b"AD1015\x00\x00", + b"0\nSECTION\n", + b"AC", + b"", + ] { + assert_eq!(unreadable(read), None, "{:?}", String::from_utf8_lossy(read)); + } + } + + #[test] + fn an_ad_version_code_is_a_dwg_drawing() { + assert!(is_dwg(b"AD1018\x00\x00") && is_dwg(b"AC1018\x00\x00")); + assert!(!is_dwg(b"AD10\x00\x00\x00") && !is_dwg(b"AD1018") && !is_dwg(b"0\nSECTION\n")); + } + + #[test] + fn a_dwg_version_the_reader_skips_is_refused_before_converting() { + let e = hold(b"AC1004\x00\x00\x00\x00").unwrap_err(); + assert!(e.starts_with("this drawing is DWG R9 (AC1004),"), "{e}"); + } } diff --git a/crates/cad/src/import.rs b/crates/cad/src/import.rs index bed5bef361..3b72f7322e 100644 --- a/crates/cad/src/import.rs +++ b/crates/cad/src/import.rs @@ -108,15 +108,18 @@ pub fn is_dxf(bytes: &[u8]) -> bool { /// The tags of a DXF file, or of a DWG file converted to DXF ([`crate::dwg`]), and what the read /// left out: where the file is damaged, and what the DWG conversion couldn't read. fn tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Vec<String>), String> { + if let Some(why) = crate::dwg::unreadable(bytes) { + return Err(why); + } if crate::dwg::is_dwg(bytes) { let converted = crate::dwg::to_dxf(bytes)?; let (tags, mut notes) = dxf_tags(&converted.dxf)?; notes.extend(converted.notes.iter().cloned()); return Ok((tags, notes)); } - // R1.x and R2.x drawings (MC0.0, AC1.2 to AC2.10), and an AC10 header with no version number. - if [&b"AC10"[..], b"AC1.", b"AC2.", b"MC0."].iter().any(|magic| bytes.starts_with(magic)) { - return Err("this DWG drawing's version can't be read: save it from the CAD app as a DXF and open that".into()); + // A DWG version code with nothing after it. + if [&b"AC10"[..], b"AD10"].iter().any(|magic| bytes.starts_with(magic)) { + return Err("DWG: the file is cut short".into()); } dxf_tags(bytes) } diff --git a/crates/cad/src/import/tests_dwg.rs b/crates/cad/src/import/tests_dwg.rs index 00ff6aa7da..63b2162de3 100644 --- a/crates/cad/src/import/tests_dwg.rs +++ b/crates/cad/src/import/tests_dwg.rs @@ -77,9 +77,24 @@ fn a_damaged_dwg_is_an_error_that_names_dwg() { let e = import(&cut, &ImportOptions::default()).unwrap_err(); assert!(e.contains("DWG"), "{e}"); assert!(info(&cut).is_err()); - // An R1.x or R2.x drawing is refused without reading it. - for old in [&b"AC1.50\x00\x00\x00\x00"[..], b"AC2.10\x00\x00\x00\x00", b"MC0.0\x00\x00\x00\x00"] { + // A drawing of a version the DWG reader skips is refused by its version, without reading it. + for (old, name) in [ + (&b"AC1.50\x00\x00\x00\x00"[..], "DWG R2.05 (AC1.50)"), + (b"MC0.0\x00\x00\x00\x00", "DWG R1.0 (MC0.0)"), + (b"AC1004\x00\x00\x00\x00", "DWG R9 (AC1004)"), + ] { let e = import(old, &ImportOptions::default()).unwrap_err(); - assert!(e.contains("version can't be read") && e.contains("DXF"), "{e}"); + assert!(e.starts_with(&format!("this drawing is {name},")) && e.contains("DXF"), "{e}"); + assert_eq!(info(old).unwrap_err(), e); } + assert_eq!(import(b"AC1018", &ImportOptions::default()).unwrap_err(), "DWG: the file is cut short"); +} + +#[test] +fn a_dwg_drawing_with_an_ad_version_code_comes_in_as_its_ac_one_does() { + let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() }; + let ac = dwg(); + let mut ad = ac.clone(); + ad[1] = b'D'; + assert_eq!(art(&import(&ad, &o).unwrap().document), art(&import(&ac, &o).unwrap().document)); } diff --git a/docs/mcp.md b/docs/mcp.md index b2674d20e8..3febb923a8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12959,8 +12959,12 @@ Drawing standards files (`.dws`) are read as DWG drawings, and drawing templates that a template opens as a new untitled document. In the desktop app and `vectorcraft-cli` the conversion runs in a copy of the program started with `--dwg-worker`, so a damaged file stops that copy, not the app; it gives up after 30 minutes. Files over 512 MiB, or whose DXF would -pass 1 GiB, are refused. What the conversion skips (objects of types it can't read) is listed in `warnings`. R1.x and -R2.x drawings (`MC0.`, `AC1.` and `AC2.` headers) and the web build answer an error saying to save the drawing as DXF. +pass 1 GiB, are refused. What the conversion skips (objects of types it can't read) is listed in `warnings`. A drawing +whose version code the converter does not read (R1.0 to R9: `MC0.`, `AC1.`, `AC2.` and `AC1001` to `AC1004`, and any +code other than `AC1006`, `AC1009`, `AC1012`, `AC1014`, `AC1015`, `AC1018`, `AC1021`, `AC1024`, `AC1027` and `AC1032`) +answers an error that names its version and says to save it as DXF or as a DWG from R10 to 2018, without converting it. +An `AD10nn` code other than `AD1006` is read as `AC10nn`. The web build answers an error saying to save the drawing as +DXF. When the user opens or places a DWG drawing in the desktop app, it is converted off the UI thread: the status bar and, after 0.4 s, the open progress window show it (`file.cancelOpen` drops it, `file.openInBackground` closes the window), and its DXF Import Options open once it is converted. A drawing being placed goes in the document, on the layer and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3a0971d182..50cb4adeba 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2574,7 +2574,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - DXF export with Use Artboards applies live effects and places symbols' art once for all the artboards' drawings instead of once for each drawing; each drawing's bytes, linked images, warnings and notes are the same as before (`drawings_apply_the_live_effects_once_and_match_drawings_written_alone`, `each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone`). - DXF Options' Always Export Group as Block Reference (`groupBlocks`, off by default and not set by a preset) writes each group with output as a block of its contents, placed by an INSERT on its layer, with groups inside it as blocks placed inside that block, in every version from R12 to 2018; a group whose contents write no entity (an empty group, or one whose objects are all hidden or left out) writes no block or INSERT; the drawing reads back with the same art bounds (`groups_are_blocks_placed_by_inserts_in_every_version`, `blocks_read_back_at_the_place_their_group_was`, `group_blocks_write_a_group_as_an_insert`). Behavior reference: [Export artwork, AutoCAD export options](https://helpx.adobe.com/illustrator/using/exporting-artwork.html). - - DWG drawings open and place in the desktop build, and `document.dxfInfo` reads them: craft-dwg converts the drawing to DXF, in a copy of the app started with `--dwg-worker`, off the UI thread when the user opens or places it, and the DXF reader reads it with the DXF Import Options. The web build and R1.x and R2.x drawings return an error that says to save the drawing as DXF. DWG is not written: Export As keeps it greyed out, exporting to it says to export DXF, and Save over the drawing is refused (`a_dwg_drawing_comes_in_as_its_dxf_does`, `document_open_reads_a_dwg_drawing_as_its_dxf`, `dxf_info_and_place_read_a_dwg`, `a_dwg_opened_is_never_written_back_as_dwg`; scores and estimates unchanged). + - DWG drawings open and place in the desktop build, and `document.dxfInfo` reads them: craft-dwg converts the drawing to DXF, in a copy of the app started with `--dwg-worker`, off the UI thread when the user opens or places it, and the DXF reader reads it with the DXF Import Options. The web build returns an error that says to save the drawing as DXF. A drawing of a DWG version the converter does not read (R1.0 to R9, or a code newer than 2018's `AC1032`) returns an error that names its version and says to save it as DXF or as a DWG from R10 to 2018 (`a_dwg_version_the_reader_skips_is_named_with_what_to_save_it_as`). DWG is not written: Export As keeps it greyed out, exporting to it says to export DXF, and Save over the drawing is refused (`a_dwg_drawing_comes_in_as_its_dxf_does`, `document_open_reads_a_dwg_drawing_as_its_dxf`, `dxf_info_and_place_read_a_dwg`, `a_dwg_opened_is_never_written_back_as_dwg`; scores and estimates unchanged). - `.dws` drawing standards files and `.dwt` drawing templates, which are DWG files, open and place as DWG drawings, are listed in the open and place dialogs, and go through the DXF Import Options; a `.dwt` opens as a new untitled document (`a_dwt_template_opens_untitled_and_a_dws_opens_as_its_drawing`, `a_dwt_or_dws_drawing_places_as_a_dwg_does`, `dwt_and_dws_are_read_only_and_exporting_them_says_to_write_dxf`; scores and estimates unchanged). - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `craft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill, or scaled with the object's matrix, where the file says so), an object without a fill or outline of its own taking its style's, hidden and locked layers, groups and objects, the winding flag as the nonzero fill rule, and a uniform transparency of version 13 and later as the object's opacity and blend mode. A library color stored with its name and values (version 13 and later, in a fill or an outline) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, other transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`). Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`craft-cdr` `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). From d9c4c6b9ee4ad0dac739f181fea88e9db5025b04 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 04:52:52 -0800 Subject: [PATCH 79/88] DWG import: R12, R13, R14 and 2018 files are tested, and R12 reports its own version The DWG import tests read only a 2004 file. They now also read an R12, R13, R14 and 2018 DWG file made from the same drawing, and check that each one imports as the DXF it was made from, with the same layer and the same art. craft-dwg's writer writes 2000 and later, so the 2018 file comes from craft-dwg and the R12, R13 and R14 files come from acadrust, the DWG reader and writer craft-dwg uses. acadrust is a dev-dependency of vectorcraft-cad at the rev craft-libs pins. The tests found that DXF Import Options showed an R12 DWG drawing as R13: `info` reported the version of the DXF the DWG converts to, and an R12 DWG converts to an R13 DXF. `info` now reports a DWG file's own version. --- Cargo.lock | 1 + Cargo.toml | 3 ++ crates/cad/Cargo.toml | 4 ++ crates/cad/src/import.rs | 7 +++- crates/cad/src/import/tests_dwg.rs | 60 ++++++++++++++++++++++++------ 5 files changed, 62 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b878d75456..de218e2b58 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8716,6 +8716,7 @@ dependencies = [ name = "vectorcraft-cad" version = "0.25.1" dependencies = [ + "acadrust", "craft-dwg", "craft-dxf", "craft-image-codecs", diff --git a/Cargo.toml b/Cargo.toml index a48e3c1330..00687f102b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,9 @@ craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "4c330f craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } # DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified). craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } +# The DWG reader and writer craft-dwg uses, at the rev craft-libs pins (its Cargo.toml). Tests only: it writes the +# R12, R13 and R14 DWG files that craft-dwg's writer, 2000 and later, does not. +acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "468b9d8e317755209020d5d3f2f1c8a76210c47f" } # WMF, EMF and EMF+ reader (craft-libs#778). craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "4c330f6bd1f38dd536f830483ea9618db2cb2bd8" } diff --git a/crates/cad/Cargo.toml b/crates/cad/Cargo.toml index c09eb31879..005988ef18 100644 --- a/crates/cad/Cargo.toml +++ b/crates/cad/Cargo.toml @@ -29,3 +29,7 @@ serde_json = { workspace = true } # The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine) # and in fonts built in code (`vectorcraft_text::test_fonts`). vectorcraft-text = { workspace = true, features = ["bundled-fonts", "test-fonts"] } + +# Writes the R12, R13 and R14 DWG files the import tests read. Left out where craft-dwg leaves it out. +[target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dev-dependencies] +acadrust = { workspace = true } diff --git a/crates/cad/src/import.rs b/crates/cad/src/import.rs index bed5bef361..1186ff1714 100644 --- a/crates/cad/src/import.rs +++ b/crates/cad/src/import.rs @@ -74,7 +74,8 @@ pub struct Imported { /// What a drawing holds, for the import options. #[derive(Clone, Debug, PartialEq)] pub struct DxfInfo { - /// The DXF version (`2018`, `R12`…; the `$ACADVER` code when it's none of the known ones). + /// The drawing's version (`2018`, `R12`…; the `$ACADVER` code when it's none of the known ones). A DWG + /// file's is the DWG's own, not that of the DXF it converts to. pub version: String, /// The drawing unit's name (`Millimeters`, `Unitless`…). pub units: String, @@ -187,7 +188,9 @@ pub fn info(bytes: &[u8]) -> Result<DxfInfo, String> { } let h = &d.header; let (unit, scale) = default_ratio(h); - let version = DxfVersion::ALL.into_iter().find(|v| v.acadver() == h.acadver).map_or_else(|| h.acadver.clone(), |v| v.id().to_string()); + // A DWG's own version: the DXF it converts to can be newer (an R12 DWG converts to an R13 DXF). + let acadver = craft_dwg::version(bytes).unwrap_or_else(|| h.acadver.clone()); + let version = DxfVersion::ALL.into_iter().find(|v| v.acadver() == acadver).map_or(acadver, |v| v.id().to_string()); Ok(DxfInfo { version, units: units_name(h.insunits).into(), diff --git a/crates/cad/src/import/tests_dwg.rs b/crates/cad/src/import/tests_dwg.rs index 00ff6aa7da..5fc133ee61 100644 --- a/crates/cad/src/import/tests_dwg.rs +++ b/crates/cad/src/import/tests_dwg.rs @@ -1,5 +1,5 @@ -//! DWG import: drawings written as DXF, converted to DWG by craft-dwg's writer, come in as the DXF -//! does; damaged files are errors. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD +//! DWG import: drawings written as DXF, converted to DWG by craft-dwg's writer (2004 and 2018) or +//! acadrust's (R12, R13 and R14), come in as the DXF does; damaged files are errors. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD //! on aarch64. #![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] @@ -12,6 +12,11 @@ use crate::{DxfOptions, DxfVersion}; /// A drawing in millimetres on a layer named `Walls`: a red rectangle and a blue ellipse. fn dxf() -> Vec<u8> { + dxf_as(DxfVersion::R2000) +} + +/// [`dxf`] written as a DXF of `version`. +fn dxf_as(version: DxfVersion) -> Vec<u8> { let mut d = Document::new(200.0, 100.0); let layer = d.add_layer(Some("Walls")); let stroke = |c| Appearance::basic(Paint::None, Paint::solid(c), 1.0); @@ -20,7 +25,7 @@ fn dxf() -> Vec<u8> { for n in [rect, oval] { d.insert(Some(layer), usize::MAX, n).unwrap(); } - let o = DxfOptions { version: DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Millimeters, ..DxfOptions::default() }; + let o = DxfOptions { version, region: d.artboards[0].rect, unit: Unit::Millimeters, ..DxfOptions::default() }; crate::export(&d, &o).unwrap().bytes } @@ -55,19 +60,52 @@ fn art(doc: &Document) -> Vec<LayerArt> { .collect() } +/// `dxf` as an R12, R13 or R14 DWG file, the version the DXF declares, written by acadrust: the +/// reader craft-dwg reads DWG with. craft-dwg's own writer starts at 2000. +fn old_dwg(dxf: &[u8]) -> Vec<u8> { + let doc = acadrust::DxfReader::from_reader(std::io::Cursor::new(dxf.to_vec())).and_then(acadrust::DxfReader::read).unwrap(); + acadrust::DwgWriter::write_to_vec(&doc).unwrap() +} + +/// `dwg`, a DWG file of `version`, imports as the art `dxf` imports as, and its info names its +/// version and layer. +fn assert_comes_in_as(dxf: &[u8], dwg: &[u8], version: DxfVersion) { + assert!(crate::is_dwg(dwg) && !crate::is_dwg(dxf)); + assert_eq!(craft_dwg::version(dwg).as_deref(), Some(version.acadver())); + let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() }; + let want = art(&import(dxf, &o).unwrap().document); + assert_eq!(want.len(), 1, "{want:?}"); + // An R12 DXF writes layer names in capitals. + assert!(want[0].0.as_deref().is_some_and(|n| n.eq_ignore_ascii_case("Walls")), "{want:?}"); + assert_eq!(want[0].1.len(), 2, "{want:?}"); + assert_eq!(art(&import(dwg, &o).unwrap().document), want, "{}", version.id()); + let i = info(dwg).unwrap(); + assert_eq!(i.version, version.id(), "{i:?}"); + assert!(i.layers.iter().any(|l| Some(l) == want[0].0.as_ref()), "{i:?}"); +} + #[test] fn a_dwg_drawing_comes_in_as_its_dxf_does() { let (dxf, dwg) = (dxf(), dwg()); - assert!(crate::is_dwg(&dwg) && !crate::is_dwg(&dxf)); - let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() }; - let want = art(&import(&dxf, &o).unwrap().document); - assert_eq!(want.len(), 1, "{want:?}"); - assert_eq!(want[0].0.as_deref(), Some("Walls")); - assert_eq!(want[0].1.len(), 2, "{want:?}"); - assert_eq!(art(&import(&dwg, &o).unwrap().document), want); + assert_comes_in_as(&dxf, &dwg, DxfVersion::R2004); let i = info(&dwg).unwrap(); assert_eq!((i.units.as_str(), i.unit, i.layouts.first().map(String::as_str)), ("Millimeters", Unit::Millimeters, Some("Model"))); - assert!(i.layers.iter().any(|l| l == "Walls"), "{i:?}"); +} + +#[test] +fn r12_r13_and_r14_dwg_drawings_come_in_as_their_dxf_does() { + crate::dwg::allow_in_process(); + for version in [DxfVersion::R12, DxfVersion::R13, DxfVersion::R14] { + let dxf = dxf_as(version); + assert_comes_in_as(&dxf, &old_dwg(&dxf), version); + } +} + +#[test] +fn a_2018_dwg_drawing_comes_in_as_its_dxf_does() { + crate::dwg::allow_in_process(); + let dxf = dxf_as(DxfVersion::R2018); + assert_comes_in_as(&dxf, &craft_dwg::dxf_to_dwg_as(&dxf, "AC1032").unwrap(), DxfVersion::R2018); } #[test] From 81c7d60ea645664d1ccf012ace825e28185227c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 05:20:08 -0800 Subject: [PATCH 80/88] Live Corners: an added anchor keeps only the selected segments' ends selected Adding an anchor on a side of a path with rounded Live Corners moved each selected anchor to every anchor of its corner. The ends of a selected segment are selected anchors, so a selected side also selected the far ends of the arcs at its two corners, and an arrow-key nudge then moved those anchors too. The ends of selected segments now follow the segments instead: after the addition, only the ends of the segments as drawn are selected. Anchors selected on their own still select their whole corner. A plain path no longer builds its corner layout for Add Anchor Point, Delete Anchor Point or Remove Anchor Points before falling back to the plain edit, and Add Anchor Point builds it once for the cut check and the selection. The selected segments are matched to the new layout through one lookup per subpath instead of a scan for each segment. docs/mcp.md and the Live Corners entry in docs/target-app-parity.md now say that removing anchors clears the path's selected anchors and segments, and that Remove Anchor Points selects the anchor before the removed one at an open path's end. --- crates/doc/src/corners.rs | 4 +- crates/engine/src/cmd/draw2/anchors.rs | 2 + crates/engine/src/cmd/path.rs | 94 +++++++++++++++++++++----- crates/engine/src/tests/livecorners.rs | 19 ++++++ docs/mcp.md | 8 ++- docs/target-app-parity.md | 2 +- 6 files changed, 105 insertions(+), 24 deletions(-) diff --git a/crates/doc/src/corners.rs b/crates/doc/src/corners.rs index 8db1d8fa7f..f4bda4adb0 100644 --- a/crates/doc/src/corners.rs +++ b/crates/doc/src/corners.rs @@ -458,7 +458,7 @@ fn rebuild_corner_outline( /// that does not exist, or a path [`edit_corner_anchors`] leaves as it is. pub fn insert_corner_anchor(path: &mut PathData, live: &mut Option<Box<LiveShape>>, si: usize, seg: usize, t: f64) -> Option<usize> { let (target, first, local) = { - let lc = LiveCorners::new(path, live.as_deref())?; + let lc = LiveCorners::new(path, Some(live.as_deref()?))?; let sp = path.subpaths.get(si)?; let from = lc.sources.get(si)?; if seg >= sp.segment_count() || from.len() != sp.anchors.len() { @@ -510,7 +510,7 @@ pub fn remove_corner_anchors( anchors: &BTreeSet<AnchorRef>, mut remove: impl FnMut(&mut SubPath, &[usize]), ) -> Option<()> { - let outline = LiveCorners::new(path, live.as_deref())?.outline_anchors(anchors); + let outline = LiveCorners::new(path, Some(live.as_deref()?))?.outline_anchors(anchors); if outline.is_empty() { return None; } diff --git a/crates/engine/src/cmd/draw2/anchors.rs b/crates/engine/src/cmd/draw2/anchors.rs index 75d07fcaf5..90092fd6ae 100644 --- a/crates/engine/src/cmd/draw2/anchors.rs +++ b/crates/engine/src/cmd/draw2/anchors.rs @@ -293,6 +293,8 @@ pub(in crate::cmd) fn remove_anchors_following( /// follow the removed ones; `None`, changing nothing, when the corners can't stay live. fn remove_live_corner_anchors(d: &mut Document, id: NodeId, anchors: &[(usize, usize)], curvature: bool) -> Option<BTreeSet<(usize, usize)>> { let NodeKind::Path { path, live, .. } = &mut d.node_mut(id)?.kind else { return None }; + // A plain path has no corners to keep. + live.as_ref()?; let set: BTreeSet<(usize, usize)> = anchors.iter().copied().collect(); let lc = vectorcraft_doc::LiveCorners::new(path, live.as_deref())?; let shape: Vec<(usize, bool)> = lc.base.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect(); diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index d16c871c48..6005013cd0 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1,6 +1,6 @@ //! Path editing commands (used by the Pen and Direct Selection tools and Object → Path). -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::sync::Arc; use serde_json::{Value, json}; @@ -2462,11 +2462,15 @@ fn stretch_weights(anchors: &Anchors, closed: bool, roles: &[Stretch]) -> Vec<[f /// anchors of the outline as `segments` (the path's selected segments before), each listed in /// `before` and `after` as [`corner_sources`] gives them, `before` numbered as the outline is after /// the addition. A selected `split` gives both its halves, and the new anchor is selected with -/// them, as [`renumber_after_insert`] selects them on a plain path. +/// them, as [`renumber_after_insert`] selects them on a plain path. A segment whose two ends were +/// in `held` (the selected anchors that end a selected segment, as drawn before) has the ends of +/// its segments as drawn selected, and no other anchor of their corners. +#[allow(clippy::too_many_arguments)] fn remap_corner_segments( sel: &mut Selection, id: NodeId, segments: &BTreeSet<SegmentRef>, + held: &BTreeSet<AnchorRef>, before: &[Vec<usize>], after: &[Vec<usize>], split: SegmentRef, @@ -2476,25 +2480,64 @@ fn remap_corner_segments( let v = sources.get(si)?; Some((*v.get(g)?, *v.get((g + 1) % v.len())?)) }; - let drawn = - |si: usize, pair: (usize, usize)| after.get(si).and_then(|v| (0..v.len()).find(|&g| ends(after, (si, g)) == Some(pair))).map(|g| (si, g)); + // Each subpath's segments as drawn by the corners at their ends, the first one for each pair. + let index: Vec<HashMap<(usize, usize), usize>> = after + .iter() + .enumerate() + .map(|(si, v)| { + let mut m = HashMap::new(); + for g in 0..v.len() { + if let Some(pair) = ends(after, (si, g)) { + m.entry(pair).or_insert(g); + } + } + m + }) + .collect(); + let drawn = |si: usize, pair: (usize, usize)| index.get(si).and_then(|m| m.get(&pair)).map(|&g| (si, g)); let mut out = BTreeSet::new(); + let mut picked = BTreeSet::new(); for &r in segments { let Some((a, b)) = ends(before, r) else { continue }; - if r == split { - out.extend([drawn(r.0, (a, new)), drawn(r.0, (new, b))].into_iter().flatten()); - if let Some(ai) = after.get(r.0).and_then(|v| v.iter().position(|k| *k == new)) { - sel.anchors.entry(id).or_default().insert((r.0, ai)); - } + let found: Vec<SegmentRef> = if r == split { + [drawn(r.0, (a, new)), drawn(r.0, (new, b))].into_iter().flatten().collect() } else { - out.extend(drawn(r.0, (a, b))); + drawn(r.0, (a, b)).into_iter().collect() + }; + let len = before.get(r.0).map_or(0, Vec::len); + if len > 0 && held.contains(&r) && held.contains(&(r.0, (r.1 + 1) % len)) { + let n = after.get(r.0).map_or(0, Vec::len); + picked.extend(found.iter().flat_map(|&(si, g)| [(si, g), (si, (g + 1) % n.max(1))])); } + if r == split + && let Some(ai) = after.get(r.0).and_then(|v| v.iter().position(|k| *k == new)) + { + picked.insert((r.0, ai)); + } + out.extend(found); + } + if !picked.is_empty() { + sel.anchors.entry(id).or_default().extend(picked); + } + if sel.anchors.get(&id).is_some_and(BTreeSet::is_empty) { + sel.anchors.remove(&id); } if !out.is_empty() { sel.segments.insert(id, out); } } +/// The anchors as drawn that end the segments in `segments`, on subpaths of the lengths `sources` +/// lists ([`corner_sources`]). +fn segment_ends(segments: &BTreeSet<SegmentRef>, sources: &[Vec<usize>]) -> BTreeSet<AnchorRef> { + let mut out = BTreeSet::new(); + for &(si, g) in segments { + let Some(n) = sources.get(si).map(Vec::len).filter(|n| *n > 0 && g < *n) else { continue }; + out.extend([(si, g), (si, (g + 1) % n)]); + } + out +} + fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usize) { if let Some(set) = sel.anchors.get_mut(&id) { // A selected anchor index can name no anchor (`select.anchors` takes any index), so the @@ -2675,25 +2718,40 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> { sel.add(id); return Ok((idx, false)); } - let sp = d.node(id).and_then(Node::path_data).ok_or(EngineError::NoNode(id))?.subpaths.get(si); - if seg >= sp.ok_or_else(|| EngineError::Other("no such subpath".into()))?.segment_count() { + let (path, live) = match d.node(id).map(|n| &n.kind) { + Some(NodeKind::Path { path, live, .. }) => (path, live), + Some(_) => return Err(EngineError::Other(format!("object {id} is not a path"))), + None => return Err(EngineError::NoNode(id)), + }; + if seg >= path.subpaths.get(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?.segment_count() { return Err(EngineError::Other("no such segment".into())); } - let before = corner_sources(d, id); - let cut = d.node(id).and_then(vectorcraft_doc::LiveCorners::of).is_some_and(|lc| lc.is_cut()); - let kept = match d.node_mut(id).map(|n| &mut n.kind) { - Some(NodeKind::Path { path, live, .. }) => vectorcraft_doc::insert_corner_anchor(path, live, si, seg, t), + // A plain path has no corners to keep, so it skips the Live Corners work. + let (before, cut) = match live.as_deref().and_then(|l| vectorcraft_doc::LiveCorners::new(path, Some(l))) { + Some(lc) => (Some(lc.sources().to_vec()), lc.is_cut()), + None => (None, false), + }; + let kept = match (&before, d.node_mut(id).map(|n| &mut n.kind)) { + (Some(_), Some(NodeKind::Path { path, live, .. })) => vectorcraft_doc::insert_corner_anchor(path, live, si, seg, t), _ => None, }; - let idx = match (kept, before, corner_sources(d, id)) { + let after = if kept.is_some() { corner_sources(d, id) } else { None }; + let idx = match (kept, before, after) { // The corners stay live: the selection follows the corners its anchors come from, the // outline's anchors after the new one numbered one higher. (Some(idx), Some(before), Some(after)) => { let new = after.get(si).and_then(|v| v.get(idx)).copied().unwrap_or(usize::MAX); let before: Vec<Vec<usize>> = before.iter().map(|v| v.iter().map(|k| if *k >= new { k + 1 } else { *k }).collect()).collect(); let segments = sel.segments.get(&id).cloned().unwrap_or_default(); + // The ends of selected segments follow the segments, not their whole corners. + let ends = segment_ends(&segments, &before); + let mut held = BTreeSet::new(); + if let Some(set) = sel.anchors.get_mut(&id) { + held = set.intersection(&ends).copied().collect(); + set.retain(|r| !ends.contains(r)); + } remap_corner_anchors(sel, id, &before, &after); - remap_corner_segments(sel, id, &segments, &before, &after, (si, seg), new); + remap_corner_segments(sel, id, &segments, &held, &before, &after, (si, seg), new); idx } _ => { diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index beb22dc892..0d4e4a46ca 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -1656,6 +1656,25 @@ fn adding_an_anchor_keeps_the_selected_segments_on_their_sides() { assert!(st.selection.anchors.get(&id).is_some_and(|a| a.contains(&(0, ai))), "{:?}", st.selection.anchors); } +/// The anchors selected as the ends of selected segments stay just those ends when an anchor +/// point is added on another side: the far anchors of the corners at a selected side's ends are +/// not selected, so an arrow-key nudge does not move them. +#[test] +fn adding_an_anchor_selects_only_the_ends_of_the_selected_segments() { + let (mut s, id) = session(); + run(&mut s, json!({"radius": 10})); + let (top, curve, bottom) = (segment_between(&s, id, 0, 1), segment_between(&s, id, 2, 2), segment_between(&s, id, 2, 3)); + s.execute("select.segments", &json!({"id": id.0, "segments": [[0, top], [0, curve]], "mode": "set"})).unwrap(); + s.execute("path.insertAnchor", &json!({"id": id.0, "segment": bottom, "t": 0.5})).unwrap(); + let n = node_path(&s, id).0.subpaths[0].anchors.len(); + // The new anchor is the outline's anchor 3, after the corners at the selected segments' ends. + let (top, curve) = (segment_between(&s, id, 0, 1), segment_between(&s, id, 2, 2)); + let want: BTreeSet<AnchorRef> = [top, (top + 1) % n, curve, (curve + 1) % n].map(|a| (0, a)).into(); + let st = s.doc().unwrap(); + assert_eq!(st.selection.anchors.get(&id), Some(&want)); + assert_eq!(st.selection.segments.get(&id), Some(&[(0, top), (0, curve)].into())); +} + /// An anchor point added on a corner's curve turns the corners into plain anchor points, as /// before, and the status bar says so. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index f277ee01de..e670ad92d6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9511,9 +9511,11 @@ Adding and removing anchors keeps such corners live as well: `path.insertAnchor` new anchor on that side of the uncut outline, at the point the drawn segment has at `t`, with no radius. `path.removeAnchor`, `path.removeAnchors` and the Delete key with `deleteKeepsPathsJoined` on remove the uncut corner each removed anchor belongs to, so removing either end of a corner's arc removes that corner. The other corners are cut again at their radii -and kinds; a relative radius keeps the length it is drawn at, up to the corner's new largest radius. The selected anchors -and segments follow their corners, a selected segment that the new anchor splits stays selected as its two halves with -the new anchor, and `path.removeAnchors` selects the first anchor of the next corner along. An anchor added on a corner's +and kinds; a relative radius keeps the length it is drawn at, up to the corner's new largest radius. On `path.insertAnchor` +the selected anchors follow their corners, the selected segments stay on their sides with only their own ends selected, +and a selected segment that the new anchor splits stays selected as its two halves with the new anchor. Removing anchors +clears the path's selected anchors and segments, and `path.removeAnchors` then selects the first anchor of the next +corner along, or the anchor before the removed one at an open path's end. An anchor added on a corner's arc, or on a path the fallbacks above apply to, makes the shape a plain path, and when the path had rounded corners `path.insertAnchor` answers with a `warning`, which the status bar shows. `path.setHandle` with `symmetric: true` also places the anchor's other handle opposite the moved one at the same diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4872fb7574..f9b5d1d7d7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -868,7 +868,7 @@ since 2026-10-01. - **Shift-click on corner widgets (#5188):** with Direct Selection, when every corner of every selected path is selected (the paths selected whole), a Shift-click on a corner widget picks that corner alone, so the next drag rounds just it. When another selected path has only some corners picked, a Shift-click on a widget of a path selected whole deselects that corner and keeps the other picks. The other corners' widgets then show as not picked; a Shift-click on another corner's anchor or widget adds that corner, and a Shift-click on a picked widget deselects its corner. Corner widgets are chosen by clicking one and Shift-clicking the others ([a tutorial on rounded corners](https://logosbynick.com/?p=15787)). Test: `corners::tests::a_shift_click_on_a_widget_of_a_whole_path_picks_its_corner`. - **Picking corner widgets (#1232):** with Direct Selection, every corner's widget shows while some corners are picked: a picked corner's widget has a dot at its center and the others are hollow. A click on a widget that is not picked picks its corner alone, a Shift-click adds or removes a corner across selected paths, and a double-click on a picked widget opens Corners for the picked corners of its path ([Live Corners help page, archived](https://web.archive.org/web/2019/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html)). As VectorCraft's own rules, a plain click on a picked widget keeps the picks (while every corner of every selected path is picked, it picks that corner alone, and a double-click then opens Corners for that corner), a drag or Alt-click on a widget that is not picked edits its corner together with the picked ones, and over a widget that is not picked, a selected anchor's handle end or a nearer anchor takes the press. Tests: `corners::tests::a_press_on_a_widget_not_picked_edits_it_with_the_picked_corners`, `corners::tests::widgets_are_picked_across_paths`, `corners::tests::a_handle_end_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_nearer_anchor_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_shift_click_toggles_a_rounded_corner_whole`, `corners::tests::a_path_with_hidden_widgets_keeps_its_picks`, `tests::corner_widgets_pick_corners_across_paths_through_the_session`. - **Anchor edits keep Live Corners (#10545):** moving an anchor of a path with rounded corners (Direct Selection drag, arrow keys, `path.moveAnchor`) moves its uncut corner by the drag delta and recuts it at its radius. A grabbed arc end can finish away from a snap target. A live rectangle or polygon becomes a path with live corners. When the anchor layout changes, the path's whole anchor selection is remapped and its segment selection is cleared. A corner that a move straightens keeps its radius and rounds again when a later move bends it. An anchor edit makes the shape a plain path when no anchor stores a radius above 0 (a straightened corner's stored radius keeps the path live), a live rectangle is sheared or unevenly scaled, an arrow-key nudge bends selected curved segments or holds their anchors, or direct-selected anchors receive a transform other than a move. A nudge that changes nothing, including one that the pixel-grid snap of pixel-aligned paths takes back (with objects selected whole too), records no undo step and leaves Live Corners as they are: a live rectangle stays a live rectangle. These are VectorCraft's own rules. Tests: `tests::livecorners::moving_an_anchor_keeps_the_corners_live`, `tests::livecorners::dragging_selected_anchors_keeps_the_corners_live`, `tests::livecorners::moving_an_anchor_of_a_distorted_rectangle_edits_the_drawn_path`, `tests::livecorners::a_recut_remaps_the_whole_anchor_selection`, `tests::livecorners::a_recut_clears_segments_even_when_selected_anchor_indices_stay_the_same`, `tests::livecorners::an_unchanged_corner_layout_keeps_the_selection`, `corners::tests::a_straightened_corner_rounds_again_when_it_bends_back`. -- **Adding and removing anchors keeps Live Corners (#10545):** the Pen, Add Anchor Point and Delete Anchor Point tools, Object › Path › Remove Anchor Points and the Delete key with Delete Removes Anchor Points and Keeps Paths Joined on (`path.insertAnchor`, `path.removeAnchor`, `path.removeAnchors`) edit the uncut outline of a path with rounded corners and cut its corners again at their radii and kinds, so the corner widgets stay. An anchor added on a side has no radius; removing either end of a corner's arc removes that corner; a relative radius keeps its drawn length, up to the corner's new largest radius. Selected anchors and segments follow their corners, and Remove Anchor Points selects the first anchor of the next corner. An anchor added on a corner's arc makes the path plain, and the status bar says the corners were expanded. These are VectorCraft's own rules. Tests: `tests::livecorners::adding_and_deleting_an_anchor_on_a_side_keeps_the_corners_live`, `tests::livecorners::adding_an_anchor_keeps_the_selected_segments_on_their_sides`, `tests::livecorners::adding_an_anchor_on_a_corners_curve_expands_the_corners_and_warns`, `tests::livecorners::deleting_an_anchor_of_a_cut_corner_removes_the_corner_and_keeps_the_rest_live`, `tests::livecorners::remove_anchor_points_on_a_cut_corner_selects_the_next_corner`, `tests::livecorners::an_added_anchor_keeps_a_relative_radius_at_its_length`. +- **Adding and removing anchors keeps Live Corners (#10545):** the Pen, Add Anchor Point and Delete Anchor Point tools, Object › Path › Remove Anchor Points and the Delete key with Delete Removes Anchor Points and Keeps Paths Joined on (`path.insertAnchor`, `path.removeAnchor`, `path.removeAnchors`) edit the uncut outline of a path with rounded corners and cut its corners again at their radii and kinds, so the corner widgets stay. An anchor added on a side has no radius; removing either end of a corner's arc removes that corner; a relative radius keeps its drawn length, up to the corner's new largest radius. When an anchor is added, selected anchors follow their corners and selected segments their sides, with only the segments' own ends selected; removing anchors clears the path's selected anchors and segments, and Remove Anchor Points then selects the first anchor of the next corner, or the anchor before the removed one at an open path's end. An anchor added on a corner's arc makes the path plain, and the status bar says the corners were expanded. These are VectorCraft's own rules. Tests: `tests::livecorners::adding_and_deleting_an_anchor_on_a_side_keeps_the_corners_live`, `tests::livecorners::adding_an_anchor_keeps_the_selected_segments_on_their_sides`, `tests::livecorners::adding_an_anchor_selects_only_the_ends_of_the_selected_segments`, `tests::livecorners::adding_an_anchor_on_a_corners_curve_expands_the_corners_and_warns`, `tests::livecorners::deleting_an_anchor_of_a_cut_corner_removes_the_corner_and_keeps_the_rest_live`, `tests::livecorners::remove_anchor_points_on_a_cut_corner_selects_the_next_corner`, `tests::livecorners::an_added_anchor_keeps_a_relative_radius_at_its_length`. - **TIFF in screen and asset export:** both format menus expose the existing TIFF encoder and Format Settings. Headless UI regressions choose TIFF and check scaled dimensions, artboard selection, filenames, encoding options, saved settings and collected-asset output. Public reference: [Export for Screens](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-for-screens.html), updated 2026-09-28, lists TIFF for both artboards and assets. Adobe staff [confirmed support in 30.2.1](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/49081034-add-tiff-format-into-export-for-screens-assets-d) on 2026-02-19; the older 2025 Collect assets guide omits TIFF. - **Lossy WebP with a Quality setting:** WebP Options has a Compression menu (Lossless, Lossy) and a Quality slider from 0 to 100 that is enabled for Lossy. Lossy writes a `VP8 ` WebP file, with an `ALPH` chunk that keeps the alpha exactly when some pixels are not opaque. `document.export`, `document.serialize` and Export for Screens take `lossless: false` with `quality` (default 90, VectorCraft's own value), in a format row or in `settings.webp`; Format Settings for WebP keeps both. Lossless stays the default, and a quality above 100 or one that is not a whole number is refused. Public reference: [export file format options](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) describes Lossless and Lossy WebP and a Quality setting for Lossy (`webp_is_lossless_by_default_and_lossy_when_asked`, `lossy_webp_keeps_translucent_pixels`, `webp_quality_out_of_its_range_is_refused` in `crates/engine/src/cmd/fileio/tests_text.rs`, `webp_options_choose_lossless_or_lossy_at_a_quality`). - **Export for Screens of the selected artboards:** while the Artboard tool is in use, File › Export › Export for Screens… (`file.exportForScreens`) opens with the artboards the tool has selected checked on its Artboards tab, and Export Artboard writes only those. Shift-clicks on the canvas, or Shift- or Ctrl/Cmd-clicks on the Artboards panel's rows, select several. The other fields show the settings the document last exported with. With another tool in use, the dialog takes its artboard choice from those settings too. Public reference: [Export selected artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/export-artboards.html). From e7f3584f5fbd4c8175587cb0a28326dc0b2dc85c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 05:27:59 -0800 Subject: [PATCH 81/88] Docs: list the AD1006 and unlisted DWG codes the reader refuses --- 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 c2655b7491..92a80b074f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2576,7 +2576,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. - DXF export with Use Artboards applies live effects and places symbols' art once for all the artboards' drawings instead of once for each drawing; each drawing's bytes, linked images, warnings and notes are the same as before (`drawings_apply_the_live_effects_once_and_match_drawings_written_alone`, `each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone`). - DXF Options' Always Export Group as Block Reference (`groupBlocks`, off by default and not set by a preset) writes each group with output as a block of its contents, placed by an INSERT on its layer, with groups inside it as blocks placed inside that block, in every version from R12 to 2018; a group whose contents write no entity (an empty group, or one whose objects are all hidden or left out) writes no block or INSERT; the drawing reads back with the same art bounds (`groups_are_blocks_placed_by_inserts_in_every_version`, `blocks_read_back_at_the_place_their_group_was`, `group_blocks_write_a_group_as_an_insert`). Behavior reference: [Export artwork, AutoCAD export options](https://helpx.adobe.com/illustrator/using/exporting-artwork.html). - - DWG drawings open and place in the desktop build, and `document.dxfInfo` reads them: craft-dwg converts the drawing to DXF, in a copy of the app started with `--dwg-worker`, off the UI thread when the user opens or places it, and the DXF reader reads it with the DXF Import Options. The web build returns an error that says to save the drawing as DXF. A drawing of a DWG version the converter does not read (R1.0 to R9, or a code newer than 2018's `AC1032`) returns an error that names its version and says to save it as DXF or as a DWG from R10 to 2018 (`a_dwg_version_the_reader_skips_is_named_with_what_to_save_it_as`). DWG is not written: Export As keeps it greyed out, exporting to it says to export DXF, and Save over the drawing is refused (`a_dwg_drawing_comes_in_as_its_dxf_does`, `document_open_reads_a_dwg_drawing_as_its_dxf`, `dxf_info_and_place_read_a_dwg`, `a_dwg_opened_is_never_written_back_as_dwg`; scores and estimates unchanged). + - DWG drawings open and place in the desktop build, and `document.dxfInfo` reads them: craft-dwg converts the drawing to DXF, in a copy of the app started with `--dwg-worker`, off the UI thread when the user opens or places it, and the DXF reader reads it with the DXF Import Options. The web build returns an error that says to save the drawing as DXF. A drawing of a DWG version the converter does not read (R1.0 to R9, an R10 drawing marked `AD1006`, a code the reader does not list such as `AC1010`, or a code newer than 2018's `AC1032`) returns an error that names its version and says to save it as DXF or as a DWG from R10 to 2018 (`a_dwg_version_the_reader_skips_is_named_with_what_to_save_it_as`). DWG is not written: Export As keeps it greyed out, exporting to it says to export DXF, and Save over the drawing is refused (`a_dwg_drawing_comes_in_as_its_dxf_does`, `document_open_reads_a_dwg_drawing_as_its_dxf`, `dxf_info_and_place_read_a_dwg`, `a_dwg_opened_is_never_written_back_as_dwg`; scores and estimates unchanged). - `.dws` drawing standards files and `.dwt` drawing templates, which are DWG files, open and place as DWG drawings, are listed in the open and place dialogs, and go through the DXF Import Options; a `.dwt` opens as a new untitled document (`a_dwt_template_opens_untitled_and_a_dws_opens_as_its_drawing`, `a_dwt_or_dws_drawing_places_as_a_dwg_does`, `dwt_and_dws_are_read_only_and_exporting_them_says_to_write_dxf`; scores and estimates unchanged). - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `craft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill, or scaled with the object's matrix, where the file says so), an object without a fill or outline of its own taking its style's, hidden and locked layers, groups and objects, the winding flag as the nonzero fill rule, and a uniform transparency of version 13 and later as the object's opacity and blend mode. A library color stored with its name and values (version 13 and later, in a fill or an outline) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, other transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`). Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`craft-cdr` `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`). From bac24f10382c55147669baa1289bad57e735734a Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 05:37:17 -0800 Subject: [PATCH 82/88] Docs: the File formats missing list names what DWG still lacks The detailed missing-items row for File formats still said DWG was missing with DXF as the substitute. It now lists the DWG limits that remain: the web build and FreeBSD for aarch64, R1.x and R2.x drawings, and DWG export before version 2000. --- 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 d372670f01..5af7b9361f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -631,7 +631,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, row menu commands beyond Collect for Export (now on every layer, sublayer, group, object and guide row), menus on blend spine rows, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | | Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already; a marquee leaves locked or hidden guide paths out inside groups too, #8538) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812; distance and angle labels while drawing, #2983) | 2–4; status-bar X/Y uses the active ruler origin and General units | -| File formats | 6 | 85% | `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (#8087, follows #6983; scores and estimates unchanged); `.ai` and EPS import: an Art brush in Tints of a swatch's color comes in brushed (#8200; scores and estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group (#8128; scores and estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; scores and estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one; scores and estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; scores and estimates unchanged); PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Legacy `.ai` files that name but omit their prolog open with their layers, or with their art on one layer when the format has no layers; graph data and settings in these files still come in only as drawn art. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) | +| File formats | 6 | 85% | `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (#8087, follows #6983; scores and estimates unchanged); `.ai` and EPS import: an Art brush in Tints of a swatch's color comes in brushed (#8200; scores and estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group (#8128; scores and estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; scores and estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one; scores and estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; scores and estimates unchanged); PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Legacy `.ai` files that name but omit their prolog open with their layers, or with their art on one layer when the format has no layers; graph data and settings in these files still come in only as drawn art. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG in the web build and on FreeBSD for aarch64, R1.x and R2.x DWG drawings, and DWG export before version 2000 (the desktop app and `vectorcraft-cli` open and place other DWG drawings and export DWG 2000 to 2018 through the `--dwg-worker` copy of the app), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) | | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done, as are the Japanese papers in its Media list: JIS B4/B5/B6, はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判, beside the ISO B4/B5 that settings saved before them keep) | 1–2 | | Automation | 3 | 65% | scripting surface, batch (MCP drops malformed app replies without replay; Variables: text/visibility variables bound to objects, an object may carry several, dataset rows applied in one undo step, panel and Window › Variables with dialogs; image/graph kinds and dataset import/export open) | 6–10 | From bdb87ce7145a7b3d2a45b200776f22f4ce4fe6b6 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 05:47:42 -0800 Subject: [PATCH 83/88] Live Corners: map removal successors in one pass over the subpaths Remove Anchor Points mapped each subpath's next anchor to the path as drawn with `LiveCorners::drawn_anchor`, which counted the anchors of every earlier subpath again for each one. `LiveCorners::drawn_anchors` maps the whole set while walking the subpaths once. The docs now say that Remove Anchor Points selects the next anchor of the uncut outline, which can be an anchor added on a side as well as a corner. --- crates/doc/src/corners.rs | 30 ++++++++++++++++++++++++++ crates/engine/src/cmd/draw2/anchors.rs | 2 +- docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 33 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/corners.rs b/crates/doc/src/corners.rs index f4bda4adb0..a4f4a683d6 100644 --- a/crates/doc/src/corners.rs +++ b/crates/doc/src/corners.rs @@ -224,6 +224,21 @@ impl<'a> LiveCorners<'a> { self.sources.get(si)?.iter().position(|s| *s == k).map(|drawn| (si, drawn)) } + /// [`LiveCorners::drawn_anchor`] of each of `anchors`, counting the subpaths' anchors once. + pub fn drawn_anchors(&self, anchors: &BTreeSet<AnchorRef>) -> BTreeSet<AnchorRef> { + let mut out = BTreeSet::new(); + let mut first = 0; + for (si, sp) in self.base.subpaths.iter().enumerate() { + let Some(sources) = self.sources.get(si) else { break }; + for &(_, ai) in anchors.range((si, 0)..(si + 1, 0)) { + let k = first + ai; + out.extend(sources.iter().position(|s| *s == k).map(|drawn| (si, drawn))); + } + first += sp.anchors.len(); + } + out + } + /// The radius and kind `corners` share (each `None` when they differ, or for no corners). /// Radius is what was set ([`LiveCorners::radius`]: document lengths, or a fraction in 0..1 /// when [`LiveCorners::radii_relative`]), not the fitted draw size ([`LiveCorners::drawn_radius`]). @@ -602,6 +617,21 @@ mod tests { assert_eq!((path, live), (star, None)); } + /// Mapping a set of outline anchors gives the same anchors as drawn as mapping each one. + #[test] + fn drawn_anchors_match_drawn_anchor_across_subpaths() { + let mut star = shapes::star(Point::new(100.0, 100.0), 50.0, 25.0, 5, 0.0); + star.subpaths.extend(shapes::star(Point::new(300.0, 100.0), 50.0, 25.0, 4, 0.0).subpaths); + let (mut path, mut live) = (star, None); + set_corners(&mut path, &mut live, &set(&[0, 2, 10, 13]), Some(5.0), None); + let c = LiveCorners::new(&path, live.as_deref()).unwrap(); + let refs: BTreeSet<AnchorRef> = (0..3).flat_map(|si| (0..12).map(move |ai| (si, ai))).collect(); + let one_by_one: BTreeSet<AnchorRef> = refs.iter().filter_map(|r| c.drawn_anchor(*r)).collect(); + assert_eq!(one_by_one.len(), 18, "ten and eight outline anchors"); + assert_eq!(c.drawn_anchors(&refs), one_by_one); + assert_eq!(c.drawn_anchors(&BTreeSet::from([(1, 3)])), BTreeSet::from([(1, c.drawn_anchor((1, 3)).unwrap().1)])); + } + /// A polygon's corners are cut in the document and survive a change of sides when shared. #[test] fn polygon_corners_follow_their_sides() { diff --git a/crates/engine/src/cmd/draw2/anchors.rs b/crates/engine/src/cmd/draw2/anchors.rs index 90092fd6ae..9d23053e2c 100644 --- a/crates/engine/src/cmd/draw2/anchors.rs +++ b/crates/engine/src/cmd/draw2/anchors.rs @@ -311,7 +311,7 @@ fn remove_live_corner_anchors(d: &mut Document, id: NodeId, anchors: &[(usize, u })?; let next = following_anchors(&shape, &outline); Some(match vectorcraft_doc::LiveCorners::new(path, live.as_deref()) { - Some(lc) => next.into_iter().filter_map(|r| lc.drawn_anchor(r)).collect(), + Some(lc) => lc.drawn_anchors(&next), None => next, }) } diff --git a/docs/mcp.md b/docs/mcp.md index e670ad92d6..d22033c93a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9515,7 +9515,7 @@ and kinds; a relative radius keeps the length it is drawn at, up to the corner's the selected anchors follow their corners, the selected segments stay on their sides with only their own ends selected, and a selected segment that the new anchor splits stays selected as its two halves with the new anchor. Removing anchors clears the path's selected anchors and segments, and `path.removeAnchors` then selects the first anchor of the next -corner along, or the anchor before the removed one at an open path's end. An anchor added on a corner's +anchor of the uncut outline along (a corner, or an anchor added on a side), or the anchor before the removed one at an open path's end. An anchor added on a corner's arc, or on a path the fallbacks above apply to, makes the shape a plain path, and when the path had rounded corners `path.insertAnchor` answers with a `warning`, which the status bar shows. `path.setHandle` with `symmetric: true` also places the anchor's other handle opposite the moved one at the same diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f9b5d1d7d7..596e866a10 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -868,7 +868,7 @@ since 2026-10-01. - **Shift-click on corner widgets (#5188):** with Direct Selection, when every corner of every selected path is selected (the paths selected whole), a Shift-click on a corner widget picks that corner alone, so the next drag rounds just it. When another selected path has only some corners picked, a Shift-click on a widget of a path selected whole deselects that corner and keeps the other picks. The other corners' widgets then show as not picked; a Shift-click on another corner's anchor or widget adds that corner, and a Shift-click on a picked widget deselects its corner. Corner widgets are chosen by clicking one and Shift-clicking the others ([a tutorial on rounded corners](https://logosbynick.com/?p=15787)). Test: `corners::tests::a_shift_click_on_a_widget_of_a_whole_path_picks_its_corner`. - **Picking corner widgets (#1232):** with Direct Selection, every corner's widget shows while some corners are picked: a picked corner's widget has a dot at its center and the others are hollow. A click on a widget that is not picked picks its corner alone, a Shift-click adds or removes a corner across selected paths, and a double-click on a picked widget opens Corners for the picked corners of its path ([Live Corners help page, archived](https://web.archive.org/web/2019/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html)). As VectorCraft's own rules, a plain click on a picked widget keeps the picks (while every corner of every selected path is picked, it picks that corner alone, and a double-click then opens Corners for that corner), a drag or Alt-click on a widget that is not picked edits its corner together with the picked ones, and over a widget that is not picked, a selected anchor's handle end or a nearer anchor takes the press. Tests: `corners::tests::a_press_on_a_widget_not_picked_edits_it_with_the_picked_corners`, `corners::tests::widgets_are_picked_across_paths`, `corners::tests::a_handle_end_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_nearer_anchor_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_shift_click_toggles_a_rounded_corner_whole`, `corners::tests::a_path_with_hidden_widgets_keeps_its_picks`, `tests::corner_widgets_pick_corners_across_paths_through_the_session`. - **Anchor edits keep Live Corners (#10545):** moving an anchor of a path with rounded corners (Direct Selection drag, arrow keys, `path.moveAnchor`) moves its uncut corner by the drag delta and recuts it at its radius. A grabbed arc end can finish away from a snap target. A live rectangle or polygon becomes a path with live corners. When the anchor layout changes, the path's whole anchor selection is remapped and its segment selection is cleared. A corner that a move straightens keeps its radius and rounds again when a later move bends it. An anchor edit makes the shape a plain path when no anchor stores a radius above 0 (a straightened corner's stored radius keeps the path live), a live rectangle is sheared or unevenly scaled, an arrow-key nudge bends selected curved segments or holds their anchors, or direct-selected anchors receive a transform other than a move. A nudge that changes nothing, including one that the pixel-grid snap of pixel-aligned paths takes back (with objects selected whole too), records no undo step and leaves Live Corners as they are: a live rectangle stays a live rectangle. These are VectorCraft's own rules. Tests: `tests::livecorners::moving_an_anchor_keeps_the_corners_live`, `tests::livecorners::dragging_selected_anchors_keeps_the_corners_live`, `tests::livecorners::moving_an_anchor_of_a_distorted_rectangle_edits_the_drawn_path`, `tests::livecorners::a_recut_remaps_the_whole_anchor_selection`, `tests::livecorners::a_recut_clears_segments_even_when_selected_anchor_indices_stay_the_same`, `tests::livecorners::an_unchanged_corner_layout_keeps_the_selection`, `corners::tests::a_straightened_corner_rounds_again_when_it_bends_back`. -- **Adding and removing anchors keeps Live Corners (#10545):** the Pen, Add Anchor Point and Delete Anchor Point tools, Object › Path › Remove Anchor Points and the Delete key with Delete Removes Anchor Points and Keeps Paths Joined on (`path.insertAnchor`, `path.removeAnchor`, `path.removeAnchors`) edit the uncut outline of a path with rounded corners and cut its corners again at their radii and kinds, so the corner widgets stay. An anchor added on a side has no radius; removing either end of a corner's arc removes that corner; a relative radius keeps its drawn length, up to the corner's new largest radius. When an anchor is added, selected anchors follow their corners and selected segments their sides, with only the segments' own ends selected; removing anchors clears the path's selected anchors and segments, and Remove Anchor Points then selects the first anchor of the next corner, or the anchor before the removed one at an open path's end. An anchor added on a corner's arc makes the path plain, and the status bar says the corners were expanded. These are VectorCraft's own rules. Tests: `tests::livecorners::adding_and_deleting_an_anchor_on_a_side_keeps_the_corners_live`, `tests::livecorners::adding_an_anchor_keeps_the_selected_segments_on_their_sides`, `tests::livecorners::adding_an_anchor_selects_only_the_ends_of_the_selected_segments`, `tests::livecorners::adding_an_anchor_on_a_corners_curve_expands_the_corners_and_warns`, `tests::livecorners::deleting_an_anchor_of_a_cut_corner_removes_the_corner_and_keeps_the_rest_live`, `tests::livecorners::remove_anchor_points_on_a_cut_corner_selects_the_next_corner`, `tests::livecorners::an_added_anchor_keeps_a_relative_radius_at_its_length`. +- **Adding and removing anchors keeps Live Corners (#10545):** the Pen, Add Anchor Point and Delete Anchor Point tools, Object › Path › Remove Anchor Points and the Delete key with Delete Removes Anchor Points and Keeps Paths Joined on (`path.insertAnchor`, `path.removeAnchor`, `path.removeAnchors`) edit the uncut outline of a path with rounded corners and cut its corners again at their radii and kinds, so the corner widgets stay. An anchor added on a side has no radius; removing either end of a corner's arc removes that corner; a relative radius keeps its drawn length, up to the corner's new largest radius. When an anchor is added, selected anchors follow their corners and selected segments their sides, with only the segments' own ends selected; removing anchors clears the path's selected anchors and segments, and Remove Anchor Points then selects the first anchor of the next anchor of the uncut outline (a corner, or an anchor added on a side), or the anchor before the removed one at an open path's end. An anchor added on a corner's arc makes the path plain, and the status bar says the corners were expanded. These are VectorCraft's own rules. Tests: `tests::livecorners::adding_and_deleting_an_anchor_on_a_side_keeps_the_corners_live`, `tests::livecorners::adding_an_anchor_keeps_the_selected_segments_on_their_sides`, `tests::livecorners::adding_an_anchor_selects_only_the_ends_of_the_selected_segments`, `tests::livecorners::adding_an_anchor_on_a_corners_curve_expands_the_corners_and_warns`, `tests::livecorners::deleting_an_anchor_of_a_cut_corner_removes_the_corner_and_keeps_the_rest_live`, `tests::livecorners::remove_anchor_points_on_a_cut_corner_selects_the_next_corner`, `tests::livecorners::an_added_anchor_keeps_a_relative_radius_at_its_length`. - **TIFF in screen and asset export:** both format menus expose the existing TIFF encoder and Format Settings. Headless UI regressions choose TIFF and check scaled dimensions, artboard selection, filenames, encoding options, saved settings and collected-asset output. Public reference: [Export for Screens](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-for-screens.html), updated 2026-09-28, lists TIFF for both artboards and assets. Adobe staff [confirmed support in 30.2.1](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/49081034-add-tiff-format-into-export-for-screens-assets-d) on 2026-02-19; the older 2025 Collect assets guide omits TIFF. - **Lossy WebP with a Quality setting:** WebP Options has a Compression menu (Lossless, Lossy) and a Quality slider from 0 to 100 that is enabled for Lossy. Lossy writes a `VP8 ` WebP file, with an `ALPH` chunk that keeps the alpha exactly when some pixels are not opaque. `document.export`, `document.serialize` and Export for Screens take `lossless: false` with `quality` (default 90, VectorCraft's own value), in a format row or in `settings.webp`; Format Settings for WebP keeps both. Lossless stays the default, and a quality above 100 or one that is not a whole number is refused. Public reference: [export file format options](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) describes Lossless and Lossy WebP and a Quality setting for Lossy (`webp_is_lossless_by_default_and_lossy_when_asked`, `lossy_webp_keeps_translucent_pixels`, `webp_quality_out_of_its_range_is_refused` in `crates/engine/src/cmd/fileio/tests_text.rs`, `webp_options_choose_lossless_or_lossy_at_a_quality`). - **Export for Screens of the selected artboards:** while the Artboard tool is in use, File › Export › Export for Screens… (`file.exportForScreens`) opens with the artboards the tool has selected checked on its Artboards tab, and Export Artboard writes only those. Shift-clicks on the canvas, or Shift- or Ctrl/Cmd-clicks on the Artboards panel's rows, select several. The other fields show the settings the document last exported with. With another tool in use, the dialog takes its artboard choice from those settings too. Public reference: [Export selected artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/export-artboards.html). From 53eb048dc969170ba8bd7eb66fda45bc89d4922b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 05:47:54 -0800 Subject: [PATCH 84/88] Tests: check the hatch dash row's length before its all() assertion The gate's test-lint step flags an all() assertion with no length check in dashes_start_at_each_lines_base_point. The test now asserts the row at y 50 holds more than the four pieces it compares. --- crates/cad/src/import/hatch.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/cad/src/import/hatch.rs b/crates/cad/src/import/hatch.rs index 068d873ca5..80cd9339a9 100644 --- a/crates/cad/src/import/hatch.rs +++ b/crates/cad/src/import/hatch.rs @@ -562,6 +562,7 @@ mod tests { let p = pieces(&bp); let row = |y: f64| p.iter().filter(|(a, _)| (a.y - y).abs() < 1e-9).map(|(a, b)| (a.x, b.x)).collect::<Vec<_>>(); let first = row(50.0); + assert!(first.len() > 4, "{first:?}"); // The pattern at y 50 starts at x 5, so the period before it puts a dot on the boundary. assert_eq!(&first[..4], &[(0.0, 0.0), (5.0, 8.0), (10.0, 10.0), (15.0, 18.0)]); assert!(first.iter().all(|(a, b)| *a >= 0.0 && *b <= 100.0)); From 5c3ef10941735f60fd7591c4efa49dddb1575dfe Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 06:01:40 -0800 Subject: [PATCH 85/88] Window frame: the DPI test asserts edge relationships, not written-out pixels CI's test-lint step rejected the 500 % case of the_frame_limit_grows_with_the_monitor_dpi, which compared the clamped rect with a tuple of numbers. The test now checks that only the bottom edge moves and that it hangs below the work area by the same border the top edge hangs above the monitor. --- apps/vectorcraft/src/window_frame.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/vectorcraft/src/window_frame.rs b/apps/vectorcraft/src/window_frame.rs index fb62a91eac..8f92ffbe44 100644 --- a/apps/vectorcraft/src/window_frame.rs +++ b/apps/vectorcraft/src/window_frame.rs @@ -481,7 +481,11 @@ mod tests { let (monitor, work) = ((0, 0, 3840, 2160), (0, 0, 3840, 2000)); let rect = (-40, -40, 3880, 2200); assert_eq!(clamped_rect(rect, monitor, work), None, "100 %"); - assert_eq!(super::clamped_rect(rect, monitor, work, frame_limit(480)), Some((-40, -40, 3880, 2040)), "500 %"); + let Some(clamped) = super::clamped_rect(rect, monitor, work, frame_limit(480)) else { + panic!("500 %: the maximized frame is not clamped"); + }; + assert_eq!((clamped.0, clamped.1, clamped.2), (rect.0, rect.1, rect.2), "500 %: only the bottom edge moves"); + assert_eq!(clamped.3 - work.3, monitor.1 - rect.1, "500 %: the bottom border hangs below the work area as the top one above the monitor"); assert_eq!(super::clamped_rect((-8, -8, 1928 + 40, 1088), (0, 0, 1920, 1080), (0, 0, 1920, 1046), frame_limit(96)), None, "past the limit"); assert_eq!(frame_limit(0), frame_limit(96), "an unknown DPI counts as 100 %"); assert!(frame_limit(u32::MAX) > frame_limit(480), "no overflow"); From d22287196263c9db32d0876cfbf8b2d7665f928d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 06:32:59 -0800 Subject: [PATCH 86/88] Layers: the new-item icon adds a layer, and New Sublayer gets its own icon The Layers panel footer showed Create New Layer as `file-plus` and Create New Sublayer as a plain `+`. Clicking the `+` to add a layer made a sublayer inside the current layer, which the panel shows as a row with a disclosure triangle under it. Create New Layer now shows `dc-new-item`, the icon New Swatch, New Brush, New Symbol and the other panels' new-item buttons show, and Create New Sublayer shows a new `dc-new-sublayer` icon: a layer row with a new-item square nested under it. The commands the buttons run are unchanged. The icon change follows Milo-IZ's #10651. --- ASSETS.md | 1 + assets/icons/dc-new-sublayer.svg | 1 + crates/ui-egui/src/icon_data.rs | 1 + crates/ui-egui/src/panels/layers/controls.rs | 4 +- crates/ui-egui/src/panels/layers/tests.rs | 52 ++++++++++++++++++++ 5 files changed, 57 insertions(+), 2 deletions(-) create mode 100644 assets/icons/dc-new-sublayer.svg diff --git a/ASSETS.md b/ASSETS.md index a74a9a29a4..0f8647fb61 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -255,6 +255,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-new-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-new-item.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-new-stroke.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-new-sublayer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: a layer row with a new-item square nested under it | MIT OR Apache-2.0 | | | `assets/icons/dc-objects-on-path.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: three small squares along a curve | MIT OR Apache-2.0 | | | `assets/icons/dc-options.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-para-bullets.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: three dots, each before a line | MIT OR Apache-2.0 | | diff --git a/assets/icons/dc-new-sublayer.svg b/assets/icons/dc-new-sublayer.svg new file mode 100644 index 0000000000..0efcbf48c0 --- /dev/null +++ b/assets/icons/dc-new-sublayer.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3" y="3" width="18" height="4.5" stroke-width="1.25" /><path d="M6 7.5V16H10" stroke-width="1.25" /><rect x="10" y="11" width="11" height="10" stroke-width="1.25" /><path d="M15.5 13.5V18.5M13 16H18" stroke-width="1.5" /></svg> diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index eb2a544af8..46a6128396 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -124,6 +124,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-new-fill", include_bytes!("../../../assets/icons/dc-new-fill.svg")), ("dc-new-item", include_bytes!("../../../assets/icons/dc-new-item.svg")), ("dc-new-stroke", include_bytes!("../../../assets/icons/dc-new-stroke.svg")), + ("dc-new-sublayer", include_bytes!("../../../assets/icons/dc-new-sublayer.svg")), ("dc-objects-on-path", include_bytes!("../../../assets/icons/dc-objects-on-path.svg")), ("dc-options", include_bytes!("../../../assets/icons/dc-options.svg")), ("dc-para-bullets", include_bytes!("../../../assets/icons/dc-para-bullets.svg")), diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index 890208141d..3c438f7915 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -458,8 +458,8 @@ pub(crate) fn footer(tree: &DocLayers, ui: &mut Ui, out: &mut Vec<(String, Value .takes_drops_disabled(true) .accepts_drops(move |d: &LayersDrag<RowId>| own(d) && !d.layers().is_empty()) .also_accepts_drops(move |d: &PanelDrag| d.appearance_for(uid, reverts).is_some()), - FooterAction::new(icon("file-plus"), tl!("Create New Layer").to_string()).enabled(new_layer_ok).accepts_drops(duplicate), - FooterAction::new(icon("plus"), tl!("Create New Sublayer").to_string()).enabled(new_sublayer_ok), + FooterAction::new(icon("dc-new-item"), tl!("Create New Layer").to_string()).enabled(new_layer_ok).accepts_drops(duplicate), + FooterAction::new(icon("dc-new-sublayer"), tl!("Create New Sublayer").to_string()).enabled(new_sublayer_ok), FooterAction::new(icon("frame"), tl!("Make/Release Clipping Mask").to_string()), FooterAction::new(icon("search"), if layers_only { tl!("Locate Layer").to_string() } else { tl!("Locate Object").to_string() }) .enabled(locate_ok), diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index ef54366ba5..6aba351c34 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -1571,3 +1571,55 @@ fn the_order_revision_follows_what_the_display_order_reads() { name_row(&mut app, a, "A"); assert_ne!(order(&app), closed, "an edit moves it"); } + +/// The Layers panel beside the Swatches panel, for comparing their footer icons. +fn layers_and_swatches(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + show(app, ui); + crate::panels::swatches::show(app, ui); +} + +/// The texture of the icon drawn inside `rect`. +fn icon_texture(shapes: &[egui::Shape], rect: egui::Rect) -> egui::TextureId { + shapes + .iter() + .find_map(|shape| match shape { + egui::Shape::Mesh(mesh) if mesh.texture_id != egui::TextureId::default() && rect.contains_rect(mesh.calc_bounds()) => { + Some(mesh.texture_id) + } + _ => None, + }) + .unwrap_or_else(|| panic!("no icon drawn in {rect:?}")) +} + +/// Create New Layer shows the icon the other panels' new-item buttons show (here New Swatch), and Create New +/// Sublayer shows a different one, so the generic new-item glyph adds a layer rather than a sublayer. A click on +/// each makes a layer directly above the current one and a sublayer inside it. +#[test] +fn the_new_item_icon_makes_a_layer_and_the_sublayer_button_has_its_own() { + use crate::tests::panel_harness::Panel; + + let (app, layer, _) = two_rects(); + let mut panel = Panel::new(app, layers_and_swatches); + let (shapes, _) = panel.paint_at(2.0); + let new_item = icon_texture(&shapes, panel.rect("New Swatch")); + let new_layer = icon_texture(&shapes, panel.rect("Create New Layer")); + let new_sublayer = icon_texture(&shapes, panel.rect("Create New Sublayer")); + assert_eq!(new_layer, new_item, "Create New Layer shows the new-item icon"); + assert_ne!(new_sublayer, new_item, "Create New Sublayer does not show the new-item icon"); + + panel.click("Create New Layer"); + let added = { + let app = panel.app(); + let doc = &app.session.active().unwrap().doc; + let ids: Vec<NodeId> = doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(ids.len(), 2, "a top-level layer is added"); + assert_eq!(ids[0], layer, "directly above the current layer"); + assert!(doc.node(layer).unwrap().children().into_iter().flatten().all(|c| !c.is_layer()), "and not inside it"); + ids[1] + }; + panel.click("Create New Sublayer"); + let app = panel.app(); + let doc = &app.session.active().unwrap().doc; + assert_eq!(doc.layers.len(), 2, "no top-level layer is added"); + assert!(doc.node(added).unwrap().children().into_iter().flatten().any(|c| c.is_layer()), "a sublayer goes inside the current layer"); +} From 0a0ebb52797c4544e4074130eeeb73cb960fa8a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 07:03:59 -0800 Subject: [PATCH 87/88] Plug-ins: a file placed during an add-on preview survives Cancel With an add-on dialog previewing (Arrange in Grid, for example), File > Place ran inside the preview's interaction, because every `file.*` command other than `file.documentColorMode` was treated as one that reads the drawing on show. The placed art went into the preview document with no undo step of its own, and Cancel removed it. `file.place` now runs on the document without the preview, as other edits do: it records its own undo step and stays after Cancel and OK. Save, Export, Copy and the other `file.*` commands still act on the drawing as the preview shows it. Docs: docs/mcp.md (undo/redo row). --- crates/engine/src/session/edit.rs | 5 +++-- crates/ui-egui/src/addons/dialogs/tests.rs | 24 ++++++++++++++++++++++ docs/mcp.md | 2 +- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 9ae0db2902..667fc42aac 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -1004,9 +1004,10 @@ fn take_changed_paints( } /// Whether command `id` acts on the drawing as a dialog's preview shows it (a copy, a save, a -/// revert), so it runs inside that preview rather than as a step of its own. +/// revert), so it runs inside that preview rather than as a step of its own. Place adds art, so +/// it runs on the document without the preview, as other edits do. fn reads_preview(id: &str) -> bool { - id == "edit.copy" || (id.starts_with("file.") && id != "file.documentColorMode") + id == "edit.copy" || (id.starts_with("file.") && id != "file.documentColorMode" && id != "file.place") } /// The selection on show in a dialog's preview `shown`, as a command from outside the dialog acts diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index bd17edf0a6..c65f16492e 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -488,6 +488,30 @@ fn an_add_on_preview_keeps_an_edit_made_outside_the_dialog() { assert_eq!(undo_len(&app), undo + 1); } +#[test] +fn an_add_on_preview_keeps_a_file_placed_outside_the_dialog() { + let dir = std::env::temp_dir().join(format!("vectorcraft-addon-place-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("placed.vectorcraft"); + std::fs::write(&path, vectorcraft_format::save_file(&vectorcraft_doc::Document::new(80.0, 40.0))).unwrap(); + let mut app = two_rects(); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(true)); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0, "previewed"); + let undo = undo_len(&app); + app.run("file.place", json!({"path": path.to_string_lossy(), "at": [300, 300]})).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(undo_len(&app), undo + 1, "the placed file is a step of its own"); + cancel(&app, id); + frame(&mut app); + assert!(!app.session.in_interaction()); + assert_eq!(count(&app), 3, "Cancel keeps the placed file"); + assert_eq!(x0(&app, 1), 100.0, "Cancel rolls the preview back"); +} + #[test] fn an_add_on_preview_waits_for_its_opening_drawing() { let mut app = two_drawings(); diff --git a/docs/mcp.md b/docs/mcp.md index 289695fc2e..1f05269eb0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -889,7 +889,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. A `scale`, `reflect` or `shear` that its command would refuse returns that error before any step runs; nothing changes and no undo step is recorded. The same holds for a step that is neither a number nor null, a `reflect` that is not a string, a `copy` that is not true or false, and an `origin` that is not two numbers. A null `rotate`, `scale`, `scaleX`, `scaleY`, `shear`, `reflect`, `copy` or `origin` is left out; a null `dx` or `dy` counts as 0, so it still runs the move. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. A type object in `ids` with another of them above it in its layer is the text to wrap, not a wrap object, so the objects and the type can be selected together. The reply has a `warning` when no area type lies below any of the wrap objects. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | -| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview, except during an add-on dialog's preview (Object › Plug-ins, other than Edit Points Only): there a command that changes the document records its own undo step, acts on the document without the preview using the shown selection restricted to objects present in that document, and stays after the dialog's Cancel or OK. A shown selection containing only preview objects becomes empty for the command. A path whose selected anchors or segments the preview renumbered (Set Corners recut it) is left out of that selection, so Clear does not delete its points. A command that is refused leaves the dialog's selection as it was. The dialog previews again from the command's result and selection, including after a failed preview when only the selection changed. An outside selection command's selection and paint defaults stay together after Cancel or OK. `edit.copy` and the `file.*` commands other than `file.documentColorMode` still run on the document as the preview shows it. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | +| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview, except during an add-on dialog's preview (Object › Plug-ins, other than Edit Points Only): there a command that changes the document records its own undo step, acts on the document without the preview using the shown selection restricted to objects present in that document, and stays after the dialog's Cancel or OK. A shown selection containing only preview objects becomes empty for the command. A path whose selected anchors or segments the preview renumbered (Set Corners recut it) is left out of that selection, so Clear does not delete its points. A command that is refused leaves the dialog's selection as it was. The dialog previews again from the command's result and selection, including after a failed preview when only the selection changed. An outside selection command's selection and paint defaults stay together after Cancel or OK. `edit.copy` and the `file.*` commands other than `file.documentColorMode` and `file.place` still run on the document as the preview shows it. During an add-on dialog's preview, `file.place` adds its art to the document without the preview, as a step of its own that stays after Cancel. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | | `agent_folders` | `{}` | Where VectorCraft opens and saves files for this session: `{read_folder, write_folder}`, each a path or `null`. In the open window, the agent folders the window enforces: those of Preferences › AI Integrations (`Documents/ArtCraft/Agents/VectorCraft` for an empty one), or `null` for both when a saved folder can't be used (a deleted folder, a file) and the window refuses every file (a window from before `agent.folders` was added answers with the saved folders, even one it can't use); in a headless session started for agents, the folders it was confined to (`read_folders` / `write_folders` list them all when a kind has several); a session started without automation roots answers `unrestricted: true`. An app reached with the deprecated `--connect` answers an error: its own `--automation-*-root` flags, if any, confine it. | For example, create editable Japanese area type with the engine's vertical writing mode: From fc84b657d32811e17df0f852e5caf116aa26b7dc Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 5 Dec 2026 08:26:28 -0800 Subject: [PATCH 88/88] Scripting: a self-crossing clip path counts as enclosing an area The clip-outline check behind `pathItems.removeAll()` measured each subpath by its signed area. The loops of a figure eight turn opposite ways and cancel, so the check treated the outline as enclosing nothing, although both fill rules fill it. A subpath whose signed area is within roundoff of zero is now measured by the area it fills under nonzero. A subpath whose points all lie on one line still encloses nothing. --- crates/engine/src/script/dom/paths.rs | 58 +++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 3f6a1ef1d4..417a7ddfcd 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -869,7 +869,9 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { /// Whether a subpath of `outline` encloses an area. Each subpath's area is measured from its first /// point, so its position does not change the result, and an area within roundoff of its own -/// bounding box's is counted as none. +/// bounding box's is counted as none. A subpath that crosses itself, such as a figure eight whose +/// loops turn opposite ways and cancel in its signed area, is measured by the area it fills under +/// nonzero, which every loop counts toward. fn encloses(outline: &kurbo::BezPath) -> bool { let mut subpaths: Vec<kurbo::BezPath> = Vec::new(); for el in outline.elements() { @@ -883,11 +885,35 @@ fn encloses(outline: &kurbo::BezPath) -> bool { subpaths.into_iter().any(|mut sub| { let Some(start) = sub.elements().iter().find_map(|e| e.end_point()) else { return false }; sub.apply_affine(kurbo::Affine::translate(-start.to_vec2())); - let area = kurbo::Shape::area(&sub).abs(); - area > 0.0 && area > 64.0 * f64::EPSILON * kurbo::Shape::bounding_box(&sub).area() + let floor = 64.0 * f64::EPSILON * kurbo::Shape::bounding_box(&sub).area(); + let counts = |area: f64| area > 0.0 && area > floor; + counts(kurbo::Shape::area(&sub).abs()) + || (!collinear(&sub) + && vectorcraft_pathops::try_area(&vectorcraft_geom::PathData::from_bezpath(&sub), vectorcraft_geom::FillRule::NonZero) + .is_ok_and(counts)) }) } +/// Whether every point and control point of `sub` lies within roundoff of one straight line, as +/// in a frame collapsed to a line, which encloses no area however the path operations snap it. +fn collinear(sub: &kurbo::BezPath) -> bool { + let points: Vec<kurbo::Point> = sub + .elements() + .iter() + .flat_map(|e| match *e { + kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) => vec![p], + kurbo::PathEl::QuadTo(a, p) => vec![a, p], + kurbo::PathEl::CurveTo(a, b, p) => vec![a, b, p], + kurbo::PathEl::ClosePath => vec![], + }) + .collect(); + let Some(&first) = points.first() else { return true }; + let Some(&far) = points.iter().max_by(|a, b| a.distance(first).total_cmp(&b.distance(first))) else { return true }; + let axis = far - first; + let length = axis.hypot(); + length == 0.0 || points.iter().all(|p| axis.cross(*p - first).abs() <= 64.0 * f64::EPSILON * length * length) +} + /// Whether `outline` fills an area under `rule`: a subpath encloses an area ([`encloses`]) and the /// outline with its overlaps resolved, thin strips included, has an area. An outline the path /// operations refuse is judged by [`encloses`] alone. @@ -2536,6 +2562,32 @@ mod tests { assert_eq!(anchors, vec![(0, 1), (0, 3)], "the undo puts back the selection the write changed"); } + #[test] + fn a_figure_eight_clip_outline_fills_its_loops() { + let mut eight = kurbo::BezPath::new(); + eight.move_to((0.0, 0.0)); + eight.line_to((10.0, 10.0)); + eight.line_to((10.0, 0.0)); + eight.line_to((0.0, 10.0)); + eight.close_path(); + assert!(kurbo::Shape::area(&eight).abs() < 1e-9, "the loops cancel in the signed area"); + assert!(encloses(&eight), "each loop of the figure eight encloses an area"); + assert!(fills(&eight, vectorcraft_geom::FillRule::NonZero)); + assert!(fills(&eight, vectorcraft_geom::FillRule::EvenOdd)); + let mut line = kurbo::BezPath::new(); + line.move_to((0.0, 0.0)); + line.line_to((10.0, 10.0)); + line.close_path(); + assert!(!encloses(&line), "a closed line still encloses nothing"); + let mut flat = kurbo::BezPath::new(); + flat.move_to((0.0, 0.0)); + flat.line_to((1000.0, 0.001)); + flat.line_to((2000.0, 0.002)); + flat.line_to((1000.0, 0.001)); + flat.close_path(); + assert!(!encloses(&flat), "a frame collapsed onto a shallow diagonal encloses nothing"); + } + #[test] fn a_made_id_above_two_to_the_53_stays_exact() { let made = |v: Value| made_id(&(Data::Undefined, v));