From 8861fd358bbea99da6fecc82a2f7c662c579818c Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:02:12 +0100 Subject: [PATCH 01/69] Nudge: Ctrl/Cmd+arrow moves by a tenth of the keyboard increment (#5258) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The arrow keys nudged by the keyboard increment and Shift+arrow by ten, but there was no fine step on the canvas, although the Transform panel's fields step by 0.1 with Ctrl. object.nudge and perspective.nudge now take `fine` (÷10; with `big`, one increment), and Ctrl/Cmd+arrow passes it for art, direct-selected anchors, ruler guides and the Perspective Selection tool. Each press stays one undo step. Fixes #5258 --- crates/engine/src/cmd/distortcmds.rs | 2 +- .../engine/src/cmd/distortcmds/perspective.rs | 2 +- crates/engine/src/cmd/object.rs | 2 +- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/object/transform.rs | 16 ++++++- crates/engine/src/tests/persp_select.rs | 7 +++ crates/engine/src/tests/prefs.rs | 43 +++++++++++++++++++ crates/engine/tests/command_sweep.rs | 1 + crates/tools/src/distort/perspective/tools.rs | 2 +- crates/ui-egui/src/shortcuts.rs | 4 +- docs/ui-parity.md | 5 ++- 11 files changed, 75 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index 9e0841de66..d72fa442da 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -171,7 +171,7 @@ pub fn specs() -> Vec { "Nudge in Perspective", [], None, - "{dx, dy: arrow direction (-1, 0 or 1), big?: bool (×10), copy?: bool} move the selection in perspective by the keyboard increment, as the arrow keys do with the Perspective Selection tool → {ids}", + "{dx, dy: arrow direction (-1, 0 or 1), big?: bool (×10), fine?: bool (÷10; with big, one increment), copy?: bool} move the selection in perspective by the keyboard increment, as the arrow keys do with the Perspective Selection tool → {ids}", has_selection, persp_nudge ), diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 786d0d9568..042f6c8dcc 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -503,7 +503,7 @@ pub(super) fn persp_nudge(s: &mut Session, p: &Value) -> Result { if !(dx.is_finite() && dy.is_finite()) || (dx == 0.0 && dy == 0.0) { return Err(bad(C, "dx and dy give the arrow's direction")); } - let k = s.prefs.keyboard_increment * if switch_or(p, "big", false, C)? { 10.0 } else { 1.0 }; + let k = crate::cmd::object::nudge_step(s.prefs.keyboard_increment, switch_or(p, "big", false, C)?, switch_or(p, "fine", false, C)?); let copy = switch_or(p, "copy", false, C)?; let ids = selected_roots(s)?; // The step is measured on the page at the centre of the selection's perspective box. diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index bac3540fad..b1c02d08b5 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -36,4 +36,4 @@ pub(crate) use bounds::{bounds_rewrite, object_bounds_transform}; pub use commands::specs; pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip}; pub(super) use shape::recut; -pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; +pub(crate) use transform::{apply_transform, nudge_step, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 69f464edb1..584b48b61b 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -78,7 +78,7 @@ pub fn specs() -> Vec { "Nudge", [], None, - "{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)", + "{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), fine?: bool (÷10; with big, one increment), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)", has_selection_or_guides, nudge ), diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index bed6e6c381..2c1cbc3db6 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -290,11 +290,23 @@ pub(crate) fn along_constrain_angle(dx: f64, dy: f64, deg: f64) -> (f64, f64) { (v.x, v.y) } +/// The arrow keys' step: the keyboard increment, ×10 with Shift (`big`) and ÷10 with Ctrl/Cmd +/// (`fine`), so Shift+Ctrl+arrow moves by one increment. Divided, not multiplied by 0.1, so a tenth +/// of a 1 pt increment is the nearest `f64` to 0.1. +pub(crate) fn nudge_step(increment: f64, big: bool, fine: bool) -> f64 { + match (big, fine) { + (true, true) => increment, + (true, false) => increment * 10.0, + (false, true) => increment / 10.0, + (false, false) => increment, + } +} + pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["dx", "dy"], "object.nudge")?; check_switches(p, &TRANSFORM_SWITCHES, "object.nudge")?; - check_switches(p, &["big"], "object.nudge")?; - let k = s.prefs.keyboard_increment * if bool_or(p, "big", false) { 10.0 } else { 1.0 }; + check_switches(p, &["big", "fine"], "object.nudge")?; + let k = nudge_step(s.prefs.keyboard_increment, bool_or(p, "big", false), bool_or(p, "fine", false)); let (dx, dy) = (f64_or(p, "dx", 0.0) * k, f64_or(p, "dy", 0.0) * k); // Guides keep to the page's axes; art and anchors move along the constrain angle's. let (gx, gy) = (dx, dy); diff --git a/crates/engine/src/tests/persp_select.rs b/crates/engine/src/tests/persp_select.rs index 4ca4b46faf..60fd1dcfb0 100644 --- a/crates/engine/src/tests/persp_select.rs +++ b/crates/engine/src/tests/persp_select.rs @@ -508,6 +508,13 @@ fn arrow_keys_nudge_in_perspective() { let c = bounds_of(&before).center(); let step = h.apply(c + d).unwrap() - h.apply(c).unwrap(); assert!((step - Vec2::new(s.prefs.keyboard_increment, 0.0)).hypot() < 1e-6, "{step:?}"); + // Ctrl/Cmd takes a tenth of a step. + let before = plane_pts(&s, id, Plane::Right, 0.0); + s.tool_key(ToolKey::Right, Mods { cmd: true, ..Default::default() }, v).unwrap(); + let after = plane_pts(&s, id, Plane::Right, 0.0); + let c = bounds_of(&before).center(); + let step = h.apply(c + (after[0] - before[0])).unwrap() - h.apply(c).unwrap(); + assert!((step - Vec2::new(s.prefs.keyboard_increment / 10.0, 0.0)).hypot() < 1e-6, "{step:?}"); // Alt copies; Shift takes ten steps. s.tool_key(ToolKey::Left, Mods { alt: true, shift: true, ..Default::default() }, v).unwrap(); let copy = *s.doc().unwrap().selection.objects.first().unwrap(); diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index b590e3c289..46a9c24a12 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -38,6 +38,49 @@ fn set_and_get_keyboard_increment_drives_nudge() { assert!((b.x0 - 15.0).abs() < 1e-9); } +/// Ctrl/Cmd+arrow (`fine`) nudges by a tenth of the keyboard increment, and Shift+Ctrl+arrow +/// (`big` and `fine`) by one increment: art, direct-selected anchors and ruler guides, one undo +/// step per press, and repeated fine nudges add up to whole increments. +#[test] +fn fine_nudge_moves_a_tenth_of_the_keyboard_increment() { + let mut s = Session::new(); + s.execute("prefs.set", &json!({"key": "keyboardIncrement", "value": 5})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let x0 = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().x0; + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let n = undo(&s); + s.execute("object.nudge", &json!({"dx": 1, "dy": 0, "fine": true})).unwrap(); + assert!((x0(&s) - 10.5).abs() < 1e-9, "{}", x0(&s)); + assert_eq!(undo(&s), n + 1, "one undo step per press"); + s.execute("object.nudge", &json!({"dx": -1, "dy": 0, "big": true, "fine": true})).unwrap(); + assert!((x0(&s) - 5.5).abs() < 1e-9, "Shift+Ctrl: one increment, {}", x0(&s)); + for _ in 0..10 { + s.execute("object.nudge", &json!({"dx": 1, "dy": 0, "fine": true})).unwrap(); + } + assert!((x0(&s) - 10.5).abs() < 1e-9, "ten fine nudges are one increment, {}", x0(&s)); + assert_eq!(undo(&s), n + 12); + + // Direct-selected anchors. + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0]]})).unwrap(); + let p0 = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[0].p; + let before = p0(&s); + s.execute("object.nudge", &json!({"dx": 0, "dy": 1, "fine": true})).unwrap(); + let d = p0(&s) - before; + assert!(d.x.abs() < 1e-9 && (d.y - 0.5).abs() < 1e-9, "{d:?}"); + + // Ruler guides. + s.execute("select.none", &json!({})).unwrap(); + s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + s.execute("object.nudge", &json!({"dx": 1, "dy": 0, "fine": true})).unwrap(); + let pos = s.doc().unwrap().doc.guides[0].pos; + assert!((pos - 100.5).abs() < 1e-9, "{pos}"); + + assert!(s.execute("object.nudge", &json!({"dx": 1, "fine": "true"})).is_err()); +} + #[test] fn set_rejects_out_of_range_and_wrong_types() { let mut s = Session::new(); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 45f6b47680..223269a873 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -336,6 +336,7 @@ fn structured_junk() { ("perspective.transform", json!({"matrix": [1, 0, 0, 1, 0, 0], "depth": -1e9, "plane": "left", "copy": true})), ("perspective.transform", json!({"matrix": [1, 0, 0, 1, 1e300, 0], "plane": "left"})), ("perspective.nudge", json!({"dx": 1e308, "dy": -1e308, "big": true, "copy": true})), + ("perspective.nudge", json!({"dx": 1e308, "dy": -1e308, "fine": true})), ("perspective.plane.move", json!({"plane": "ground", "offset": 1e308, "objects": "copy"})), ("perspective.plane.move", json!({"plane": "left", "by": -1e7, "objects": "move"})), ("perspective.plane.move", json!({"plane": "none", "offset": 0})), diff --git a/crates/tools/src/distort/perspective/tools.rs b/crates/tools/src/distort/perspective/tools.rs index 915e4a8835..4e501e3339 100644 --- a/crates/tools/src/distort/perspective/tools.rs +++ b/crates/tools/src/distort/perspective/tools.rs @@ -330,7 +330,7 @@ impl Tool for PerspectiveSelectionTool { if !self.claims_key(cx, key) { return vec![]; } - vec![Action::Exec("perspective.nudge".into(), json!({"dx": dx, "dy": dy, "big": mods.shift, "copy": mods.alt}))] + vec![Action::Exec("perspective.nudge".into(), json!({"dx": dx, "dy": dy, "big": mods.shift, "fine": mods.cmd, "copy": mods.alt}))] } fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { // The arrows nudge a selection in perspective. diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 9c62eb1885..0af986dc36 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -508,12 +508,12 @@ fn type_tool_input(app: &mut VectorcraftApp, ctx: &egui::Context, composing: boo /// Apply arrow-key movement and clear selected art when no text editor owns input, unless a Layers /// or Appearance row has Delete/Backspace (`rows_keys`). fn nudge_and_clear(app: &mut VectorcraftApp, ctx: &egui::Context, rows_keys: bool) { - // Arrow nudges (Shift = ×10, Alt = copy). + // Arrow nudges (Shift = ×10, Ctrl/Cmd = ÷10, Alt = copy). let arrows = [(Key::ArrowLeft, -1.0, 0.0), (Key::ArrowRight, 1.0, 0.0), (Key::ArrowUp, 0.0, -1.0), (Key::ArrowDown, 0.0, 1.0)]; for (k, dx, dy) in arrows { let m = ctx.input(|i| i.modifiers); if ctx.input_mut(|i| i.consume_key(m, k)) && app.session.active().is_some_and(|d| d.selection.has_objects_or_guides()) { - let _ = app.run("object.nudge", json!({"dx": dx, "dy": dy, "big": m.shift, "copy": m.alt})); + let _ = app.run("object.nudge", json!({"dx": dx, "dy": dy, "big": m.shift, "fine": m.command, "copy": m.alt})); } } // Delete / Backspace clear the selection. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 26d3dd6790..7a946e35a1 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-03 · **Change:** minor (Type on a Path Options has a Preview checkbox, #5360; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Type on a Path Options has a Preview checkbox, #5360; Ctrl/Cmd+arrow fine nudge, #5258; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -210,7 +210,7 @@ tools, never checked side by side) isn't captured row by row. | Behaviour | Status | Notes | |---|---|---| | Wheel over a closed font-family field in Character, Properties or Control | done | #5253: applies the next or previous family to selected text, one undo step per notch; uses saved font filters, ignores search text and stops at the list's ends. Escape and pointer departure keep the change. Other font-picking menus and modifier-wheel input keep their existing behavior. | -| Arrow keys nudge by Keyboard Increment (0.001–1296 pt); Shift ×10; Alt copies | done | | +| Arrow keys nudge by Keyboard Increment (0.001–1296 pt); Shift ×10; Ctrl/Cmd ÷10 (Shift+Ctrl/Cmd: one increment), as the Transform panel fields step; Alt copies | done | Ctrl/Cmd ÷10 is VectorCraft's own addition (#5258) | | Fields commit what was typed on a click away or a move to another field, as Enter does; Escape discards it | done | #1787 | | Number fields: Up/Down step, Shift ×10, Cmd/Ctrl ÷10, wheel over a focused field; steps, the wheel and label scrubs stop at the field's bounds (a stroke weight at 0, a miter limit at 1) | done | Shift+arrow in the Stroke weight field doesn't step by 10 (#991); bounds #3370 | | Arithmetic in fields (`+ - * /`, and `%` of the value before it: `3cm*50%`, `50pt+25%`) and unit suffixes (`3 mm`, `1in`, `2p6`) | done | `Unit::parse`; mixed units in one expression not verified | @@ -418,6 +418,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | Arrow keys: Ctrl/Cmd+arrow nudges art, direct-selected anchors, ruler guides and a selection in perspective by a tenth of the Keyboard Increment, and Shift+Ctrl/Cmd+arrow by one increment; `object.nudge` and `perspective.nudge` take `fine` (#5258); scores and estimates unchanged | | 2026-11-03 | minor | Enclosing Lasso selects fully enclosed objects with a freehand loop under Object › Plug-ins; scores and estimates unchanged. | | 2026-11-03 | minor | Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show); scores and estimates unchanged | | 2026-11-02 | minor | Font-family fields in Character, Properties and Control accept the wheel without opening the menu (#5253); scores and estimates unchanged. | From b9e385404065ff33e55f8ec5651a98100392e443 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 3 Nov 2026 01:59:18 +0100 Subject: [PATCH 02/69] Perspective nudge: skip Snap to Grid so grid-aligned art moves Snap to Grid pulled an edge within a quarter cell of a gridline back onto it, so an arrow-key nudge (1 pt or 0.1 pt) of art on the gridlines moved nothing and recorded no undo step. `perspective.nudge` now passes `snap: false`; `perspective.move` still snaps. Also: `fine` is covered by both commands' non-boolean refusal tests, and the no-op test no longer lists the snapped nudge. --- crates/engine/src/cmd/distortcmds.rs | 2 +- .../engine/src/cmd/distortcmds/perspective.rs | 10 +++++- crates/engine/src/cmd/object/transform.rs | 3 ++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/distort.rs | 24 ++++++------- crates/engine/src/tests/persp_select.rs | 35 +++++++++++++++++++ crates/ui-egui/src/shortcuts/tests.rs | 22 ++++++++++++ docs/mcp.md | 10 +++--- docs/ui-parity.md | 2 +- 9 files changed, 87 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index d72fa442da..aa580d31a9 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -171,7 +171,7 @@ pub fn specs() -> Vec { "Nudge in Perspective", [], None, - "{dx, dy: arrow direction (-1, 0 or 1), big?: bool (×10), fine?: bool (÷10; with big, one increment), copy?: bool} move the selection in perspective by the keyboard increment, as the arrow keys do with the Perspective Selection tool → {ids}", + "{dx, dy: arrow direction (-1, 0 or 1), big?: bool (×10), fine?: bool (÷10; with big, one increment), copy?: bool} move the selection in perspective by the keyboard increment (Snap to Grid doesn't apply), as the arrow keys do with the Perspective Selection tool → {ids}", has_selection, persp_nudge ), diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 042f6c8dcc..4b46da1718 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -497,6 +497,9 @@ pub(super) fn plane_match(s: &mut Session, p: &Value) -> Result { Ok(json!({ "plane": plane.id(), "offset": depth })) } +/// `perspective.nudge`, the arrow keys with the Perspective Selection tool: the selection moves +/// within its plane by [`nudge_step`](crate::cmd::object::nudge_step), measured on the page at the +/// centre of its perspective box, without Snap to Grid. pub(super) fn persp_nudge(s: &mut Session, p: &Value) -> Result { const C: &str = "perspective.nudge"; let (dx, dy) = (number_or(p, "dx", 0.0, C)?, number_or(p, "dy", 0.0, C)?); @@ -512,7 +515,12 @@ pub(super) fn persp_nudge(s: &mut Session, p: &Value) -> Result { let (plane, depth, rect) = g.plane_bounds(&st.doc, &ids).ok_or_else(|| EngineError::Other("the selection isn't in perspective".into()))?; let from = g.homography_at(plane, depth).and_then(|h| h.apply(rect.center())).ok_or_else(beyond_horizon)?; let to = from + vectorcraft_geom::Vec2::new(dx.clamp(-1.0, 1.0), dy.clamp(-1.0, 1.0)) * k; - persp_move(s, &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "from": [from.x, from.y], "to": [to.x, to.y], "copy": copy})) + // The arrow keys move by the step: Snap to Grid would pull an edge on a gridline back onto it, + // so a nudge smaller than a quarter cell would move nothing. + persp_move( + s, + &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "from": [from.x, from.y], "to": [to.x, to.y], "copy": copy, "snap": false}), + ) } pub(super) fn persp_draw(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 2c1cbc3db6..4c686d3fc0 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -302,6 +302,9 @@ pub(crate) fn nudge_step(increment: f64, big: bool, fine: bool) -> f64 { } } +/// `object.nudge`, the arrow keys: the selected anchors, else the selected objects (and the guides +/// that move with them), else the selected ruler guides move by [`nudge_step`] in the arrow's +/// direction, in one undo step. pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["dx", "dy"], "object.nudge")?; check_switches(p, &TRANSFORM_SWITCHES, "object.nudge")?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b1f1c2599d..ef231cddd4 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1396,6 +1396,7 @@ fn a_boolean_given_as_text_for_a_transform_is_an_error() { ("object.move", json!({"dx": 5, "copy": "true"}), "copy"), ("object.move", json!({"dx": 5, "objects": 0}), "objects"), ("object.nudge", json!({"dx": 1, "big": "true"}), "big"), + ("object.nudge", json!({"dx": 1, "fine": "true"}), "fine"), ("object.rotate", json!({"angle": 45, "absolute": "true"}), "absolute"), ("object.scale", json!({"sx": 200, "strokes": "false"}), "strokes"), ("object.scale", json!({"sx": 200, "corners": [true]}), "corners"), diff --git a/crates/engine/src/tests/distort.rs b/crates/engine/src/tests/distort.rs index d033fadee6..a2e1b8df62 100644 --- a/crates/engine/src/tests/distort.rs +++ b/crates/engine/src/tests/distort.rs @@ -796,9 +796,10 @@ fn perspective_grid_commands_refuse_a_boolean_given_as_text() { /// For an object in perspective, Move in Perspective by 0 (along its plane or its normal), /// Transform in Perspective by the identity, Transform Again after each, and a Perspective Selection -/// drag that ends where it started record no undo step. So do a Move by 0 and a 1 pt Nudge that -/// Snap to Grid takes back to the gridlines the object's edges are on, and Transform Again after -/// each. With Copy, the identity copies the object in one undo step. +/// drag that ends where it started record no undo step. So do a Move by 0 of an object Snap to Grid +/// keeps on the gridlines its edges are on, and Transform Again after it. With Copy, the identity +/// copies the object in one undo step. (A Nudge in Perspective isn't snapped: it moves by its step, +/// see `arrow_keys_nudge_in_perspective_by_the_step_with_snap_to_grid`.) #[test] fn perspective_moves_that_move_nothing_record_no_undo_step() { let mut s = session(); @@ -830,8 +831,8 @@ fn perspective_moves_that_move_nothing_record_no_undo_step() { assert_eq!(s.journal.last().unwrap().0, "perspective.move"); let (undo, redo, _) = history(&s); assert_eq!(((undo, redo), path(&s, a)), ((before.0, before.1), shape.clone()), "a drag back to its start"); - // Snap to Grid takes a move that ends 0.3 pt past a gridline crossing onto the crossing. Then it - // takes a move by 0 and a 1 pt nudge back there, and Transform Again after each moves nothing. + // Snap to Grid takes a move that ends 0.3 pt past a gridline crossing onto the crossing. Then a + // move by 0 there, and Transform Again after it, moves nothing. s.execute("perspective.grid.snap", &json!({"on": true})).unwrap(); let g = grid(&s); let (_, _, b) = g.plane_bounds(&s.doc().unwrap().doc, &[a]).unwrap(); @@ -842,12 +843,7 @@ fn perspective_moves_that_move_nothing_record_no_undo_step() { with_a_step_to_redo(&mut s); let before = history(&s); let on_grid = path(&s, a); - let calls = [ - ("perspective.move", json!({"from": [to.x, to.y], "to": [to.x, to.y]})), - ("object.transformAgain", json!({})), - ("perspective.nudge", json!({"dx": 1, "dy": 0})), - ("object.transformAgain", json!({})), - ]; + let calls = [("perspective.move", json!({"from": [to.x, to.y], "to": [to.x, to.y]})), ("object.transformAgain", json!({}))]; for (c, p) in calls { assert_eq!(s.execute(c, &p).unwrap(), json!({"ids": [a.0]}), "{c} {p}"); assert_eq!((history(&s), path(&s, a)), (before, on_grid.clone()), "{c} {p}"); @@ -859,7 +855,7 @@ fn perspective_moves_that_move_nothing_record_no_undo_step() { } /// Move in Perspective refuses a `copy`, `perpendicular` or `snap`, Transform in Perspective a `copy`, -/// and Nudge in Perspective a `big` or `copy`, given as text or as another value that is not true or +/// and Nudge in Perspective a `big`, `fine` or `copy`, given as text or as another value that is not true or /// false: the object stays where it is, nothing is copied, and the undo history stays as it was. Null /// is read as the key left out. #[test] @@ -877,7 +873,7 @@ fn perspective_moves_refuse_a_boolean_given_as_text() { refuses_non_boolean(&mut s, "perspective.move", &json!({"from": from, "to": to, key: v}), key); } refuses_non_boolean(&mut s, "perspective.transform", &json!({"matrix": [1.5, 0, 0, 1.5, 0, 0], "copy": v}), "copy"); - for key in ["big", "copy"] { + for key in ["big", "fine", "copy"] { refuses_non_boolean(&mut s, "perspective.nudge", &json!({"dx": 1, "dy": 0, key: v}), key); } assert_eq!(state(&s), before, "{v}"); @@ -885,7 +881,7 @@ fn perspective_moves_refuse_a_boolean_given_as_text() { let calls = [ ("perspective.move", json!({"from": from, "to": to, "copy": null, "perpendicular": null, "snap": null})), ("perspective.transform", json!({"matrix": [1.5, 0, 0, 1.5, 0, 0], "copy": null})), - ("perspective.nudge", json!({"dx": 1, "dy": 0, "big": null, "copy": null})), + ("perspective.nudge", json!({"dx": 1, "dy": 0, "big": null, "fine": null, "copy": null})), ]; for (i, (c, p)) in calls.into_iter().enumerate() { assert_eq!(s.execute(c, &p).unwrap(), json!({"ids": [a.0]}), "{c} {p}"); diff --git a/crates/engine/src/tests/persp_select.rs b/crates/engine/src/tests/persp_select.rs index 60fd1dcfb0..0131468927 100644 --- a/crates/engine/src/tests/persp_select.rs +++ b/crates/engine/src/tests/persp_select.rs @@ -488,6 +488,41 @@ fn transform_again_repeats_a_perspective_scale_and_copies() { assert!(s.execute("perspective.transform", &json!({"matrix": [1, 0, 0, 1, 0, 0], "depth": f64::MAX})).is_err()); } +/// Snap to Grid (on by default) leaves the arrow keys' step alone: art whose edges are on +/// gridlines moves by the step (a tenth of it with Ctrl/Cmd) in one undo step each, instead of +/// being pulled back onto the gridlines and not moving at all. +#[test] +fn arrow_keys_nudge_in_perspective_by_the_step_with_snap_to_grid() { + let (mut s, id) = persp_session(); + s.execute("perspective.grid.snap", &json!({"on": true})).unwrap(); + // A move that ends 0.3 pt past a gridline crossing snaps the corner onto it. + let g = grid(&s); + let b = bounds_of(&plane_pts(&s, id, Plane::Right, 0.0)); + let past = |v: f64| (v / g.cell).ceil() * g.cell + 0.3 - v; + let (c, dv) = (b.center(), Vec2::new(past(b.x0), past(b.y0))); + let (from, to) = (g.to_page(Plane::Right, c).unwrap(), g.to_page(Plane::Right, c + dv).unwrap()); + s.execute("perspective.move", &json!({"from": [from.x, from.y], "to": [to.x, to.y]})).unwrap(); + let on_grid = bounds_of(&plane_pts(&s, id, Plane::Right, 0.0)); + assert!((on_grid.x0 / g.cell - (on_grid.x0 / g.cell).round()).abs() < 1e-6, "{on_grid:?}"); + // The page step measured at the centre of the selection, as `perspective.nudge` measures it. + let page_step = |s: &Session, before: &[Point]| { + let after = plane_pts(s, id, Plane::Right, 0.0); + let h = grid(s).homography(Plane::Right).unwrap(); + let c = bounds_of(before).center(); + h.apply(c + (after[0] - before[0])).unwrap() - h.apply(c).unwrap() + }; + let v = ViewInfo::default(); + s.select_tool("perspectiveSelection", v).unwrap(); + let k = s.prefs.keyboard_increment; + for (mods, step) in [(Mods::default(), k), (Mods { cmd: true, ..Default::default() }, k / 10.0)] { + let (before, n) = (plane_pts(&s, id, Plane::Right, 0.0), undo_len(&s)); + s.tool_key(ToolKey::Right, mods, v).unwrap(); + assert_eq!(undo_len(&s), n + 1, "{mods:?}"); + let d = page_step(&s, &before); + assert!((d - Vec2::new(step, 0.0)).hypot() < 1e-6, "{mods:?} {d:?}"); + } +} + #[test] fn arrow_keys_nudge_in_perspective() { let (mut s, id) = persp_session(); diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index efe9917492..64b5ba15ab 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1551,6 +1551,28 @@ fn selected_vertical_area_and_path_type_use_vertical_spacing_chords() { } /// #3786: Alt+arrows step a selected text object's spacing instead of copying and nudging it. +/// #5258: Ctrl/Cmd+arrow nudges the selection by a tenth of the keyboard increment, and +/// Shift+Ctrl/Cmd+arrow by one increment, one undo step each. +#[test] +fn command_arrows_nudge_by_a_tenth_of_the_keyboard_increment() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let x0 = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().geometric_bounds().unwrap().x0; + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + + let press = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + let shift_command = Modifiers::SHIFT | Modifiers::COMMAND; + let before = undo(&app); + for (m, x, n) in [(Modifiers::COMMAND, 20.1, 1), (shift_command, 21.1, 2), (Modifiers::NONE, 22.1, 3)] { + frame(&mut app, vec![egui::Event::ModifiersChanged(m), press(Key::ArrowRight, m)]); + assert!((x0(&app) - x).abs() < 1e-9, "{m:?}: {}", x0(&app)); + assert_eq!(undo(&app), before + n, "{m:?}"); + } +} + #[test] fn alt_arrows_step_selected_type_object() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/docs/mcp.md b/docs/mcp.md index 0ca4e32353..6f523f4b93 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1142,7 +1142,7 @@ The transform, Align, Object Properties and Live Shape Properties commands refus that is not true or false with `` `strokes` must be true or false ``, naming the key, and leave the document and its undo history as they were: the options `copy`, `strokes`, `corners`, `patterns`, `objects` and `typeAreas` in `object.transform`, `object.move`, `object.nudge`, `object.rotate`, `object.scale`, `object.reflect`, `object.shear`, -`object.transformAgain` and `object.setBounds`; `anchors` and `releaseOutside` in `object.transform`; `big` in `object.nudge`; +`object.transformAgain` and `object.setBounds`; `anchors` and `releaseOutside` in `object.transform`; `big` and `fine` in `object.nudge`; `absolute` in `object.rotate`; `proportional` in `object.setBounds`; `patterns` in `object.align`, `object.distribute` and `object.distributeSpacing`; `visible`, `locked`, `isolate` and `knockoutShape` in `object.setProps`; and `invertPie`, `makeSidesEqual` and `relativeRadii` in `object.setLiveShape`. A null is read as a key left out. @@ -5971,8 +5971,8 @@ back). Holding Shift during an in-plane move constrains each object's displaceme own plane. `perspective.move` accepts `constrain: true` (default false) and adjusts Snap to Grid along the constrained direction on the first object's plane and depth. `press_key` Escape during a move, a resize or a plane widget drag cancels it and puts the objects and the -grid back. The arrow keys nudge a selection in perspective by the keyboard increment (`perspective.nudge`; Shift ×10, Alt -copies). Object › Transform › Transform Again repeats the last perspective move or scale in plane space. +grid back. The arrow keys nudge a selection in perspective by the keyboard increment (`perspective.nudge`; Shift ×10, +Ctrl/Cmd ÷10 (`fine`), Shift+Ctrl/Cmd one increment, Alt copies); Snap to Grid doesn't pull a nudge onto the gridlines. Object › Transform › Transform Again repeats the last perspective move or scale in plane space. ```json {"name":"pointer_gesture","arguments":{"tool":"perspectiveSelection","events":[{"kind":"down","x":480,"y":410},{"kind":"drag","x":470,"y":405}]}} @@ -5984,8 +5984,8 @@ copies). Object › Transform › Transform Again repeats the last perspective m The perspective, width point, Liquify and Puppet Warp commands refuse a string, a number or another value that is not true or false with `` `copy` must be true or false ``, naming the key, and leave the document and its undo history as -they were: `copy`, `perpendicular` and `snap` in `perspective.move`; `copy` in `perspective.transform`; `big` and -`copy` in `perspective.nudge`; `snap` in `perspective.draw`; `reproject` in `perspective.grid.set`; `visible` in +they were: `copy`, `perpendicular` and `snap` in `perspective.move`; `copy` in `perspective.transform`; `big`, `fine` +and `copy` in `perspective.nudge`; `snap` in `perspective.draw`; `reproject` in `perspective.grid.set`; `visible` in `perspective.grid.show`; `adjustAdjoining` in `stroke.widthPoint.set`; `usePressure`, `simplifyOn`, `affectAnchors`, `affectIn` and `affectOut` in `object.liquify`, with any `tool`; and `rest` in `object.puppetWarp`. A null is read as a key left out. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 7a946e35a1..adfbfe04a9 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -418,7 +418,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| -| 2026-11-02 | minor | Arrow keys: Ctrl/Cmd+arrow nudges art, direct-selected anchors, ruler guides and a selection in perspective by a tenth of the Keyboard Increment, and Shift+Ctrl/Cmd+arrow by one increment; `object.nudge` and `perspective.nudge` take `fine` (#5258); scores and estimates unchanged | +| 2026-11-02 | minor | Arrow keys: Ctrl/Cmd+arrow nudges art, direct-selected anchors, ruler guides and a selection in perspective by a tenth of the Keyboard Increment, and Shift+Ctrl/Cmd+arrow by one increment; `object.nudge` and `perspective.nudge` take `fine`; Snap to Grid no longer pulls a nudge in perspective back onto the gridlines, which left grid-aligned art unmoved (#5258); scores and estimates unchanged | | 2026-11-03 | minor | Enclosing Lasso selects fully enclosed objects with a freehand loop under Object › Plug-ins; scores and estimates unchanged. | | 2026-11-03 | minor | Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show); scores and estimates unchanged | | 2026-11-02 | minor | Font-family fields in Character, Properties and Control accept the wheel without opening the menu (#5253); scores and estimates unchanged. | From ffe68938cec9d9fc2ff1a585bf46ff78d5e7b600 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:02:54 +0100 Subject: [PATCH 03/69] Nudge: Ctrl/Cmd+arrow moves Direct Selection's frame anchors and mesh points by a tenth too Direct Selection nudges selected area-type frame anchors and gradient-mesh points itself (ToolContext::arrow_nudge), before object.nudge sees the key, and that step ignored Ctrl/Cmd. nudge_step moves into vectorcraft-tools, the engine re-exports it, and arrow_nudge uses it, so every arrow nudge takes the same step: x10 with Shift, /10 with Ctrl/Cmd, one increment with both. --- crates/engine/src/cmd/object/transform.rs | 12 +----------- crates/tools/src/context.rs | 19 ++++++++++++++++--- crates/tools/src/direct/tests.rs | 5 ++++- crates/tools/src/lib.rs | 2 +- crates/ui-egui/src/shortcuts/tests.rs | 2 +- 5 files changed, 23 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 694946a83a..3d9eb4ef67 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -301,17 +301,7 @@ pub(crate) fn along_constrain_angle(dx: f64, dy: f64, deg: f64) -> (f64, f64) { (v.x, v.y) } -/// The arrow keys' step: the keyboard increment, ×10 with Shift (`big`) and ÷10 with Ctrl/Cmd -/// (`fine`), so Shift+Ctrl+arrow moves by one increment. Divided, not multiplied by 0.1, so a tenth -/// of a 1 pt increment is the nearest `f64` to 0.1. -pub(crate) fn nudge_step(increment: f64, big: bool, fine: bool) -> f64 { - match (big, fine) { - (true, true) => increment, - (true, false) => increment * 10.0, - (false, true) => increment / 10.0, - (false, false) => increment, - } -} +pub(crate) use vectorcraft_tools::nudge_step; /// `object.nudge`, the arrow keys: the selected anchors, else the selected objects (and the guides /// that move with them), else the selected ruler guides move by [`nudge_step`] in the arrow's diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 741e962290..fe6bf82ea1 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -319,11 +319,12 @@ impl ToolContext<'_> { pub fn star_radii_label(&self, outer: f64, inner: f64) -> String { format!("R1: {}\nR2: {}", self.len(outer), self.len(inner)) } - /// The move an arrow key nudges by: General › Keyboard Increment (ten times with Shift), - /// along General › Constrain Angle's axes; `None` for other keys. + /// The move an arrow key nudges by: General › Keyboard Increment, ten times with Shift and a + /// tenth with Ctrl/Cmd ([`nudge_step`]), along General › Constrain Angle's axes; `None` for + /// other keys. pub fn arrow_nudge(&self, key: crate::ToolKey, mods: crate::Mods) -> Option { use crate::ToolKey; - let step = self.keyboard_increment * if mods.shift { 10.0 } else { 1.0 }; + let step = nudge_step(self.keyboard_increment, mods.shift, mods.cmd); let d = match key { ToolKey::Left => Point::new(-step, 0.0), ToolKey::Right => Point::new(step, 0.0), @@ -380,3 +381,15 @@ impl ToolContext<'_> { vectorcraft_doc::hit::HitOptions { clip_outlines: true, ..self.hit_options() } } } + +/// The arrow keys' step: the keyboard increment, ×10 with Shift (`big`) and ÷10 with Ctrl/Cmd +/// (`fine`), so Shift+Ctrl+arrow moves by one increment. Divided, not multiplied by 0.1, so a tenth +/// of a 1 pt increment is the nearest `f64` to 0.1. +pub fn nudge_step(increment: f64, big: bool, fine: bool) -> f64 { + match (big, fine) { + (true, true) => increment, + (true, false) => increment * 10.0, + (false, true) => increment / 10.0, + (false, false) => increment, + } +} diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 0ac443c731..6cf5f6797e 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -415,7 +415,8 @@ fn a_marquee_selects_frame_anchors_of_area_type() { assert_eq!(a[0], Action::Begin("Reshape Type Area".into())); assert_eq!(a[1], Action::Preview("text.reshapeArea".into(), json!({"id": text.0, "anchors": [[0, 1], [0, 2]], "dx": 20.0, "dy": 20.0}))); assert_eq!(t.pointer(&cx2, &ev(PointerKind::Up, 440.0, 360.0)), vec![Action::Commit, Action::Notify(FRAME_PICKED.into())]); - // The arrow keys nudge them by the keyboard increment, ten times that with Shift. + // The arrow keys nudge them by the keyboard increment, ten times that with Shift, a tenth with + // Ctrl/Cmd and one increment with both (#5258). let nudged = |anchors: Value, dx: f64, dy: f64| { vec![ Action::Exec("text.reshapeArea".into(), json!({"id": text.0, "anchors": anchors, "dx": dx, "dy": dy})), @@ -425,6 +426,8 @@ fn a_marquee_selects_frame_anchors_of_area_type() { assert!(t.claims_key(&cx2, ToolKey::Right) && !t.claims_key(&cx2, ToolKey::Enter)); assert_eq!(t.key(&cx2, ToolKey::Right, Mods::default()), nudged(json!([[0, 1], [0, 2]]), 1.0, 0.0)); assert_eq!(t.key(&cx2, ToolKey::Up, Mods { shift: true, ..Mods::default() }), nudged(json!([[0, 1], [0, 2]]), 0.0, -10.0)); + assert_eq!(t.key(&cx2, ToolKey::Left, Mods { cmd: true, ..Mods::default() }), nudged(json!([[0, 1], [0, 2]]), -0.1, 0.0)); + assert_eq!(t.key(&cx2, ToolKey::Down, Mods { shift: true, cmd: true, ..Mods::default() }), nudged(json!([[0, 1], [0, 2]]), 0.0, 1.0)); // Any other change of the document or the selection (Deselect, then the same type selected // again) leaves the type selected whole: the arrow keys are no longer the tool's. let mut later = cx(&d, &s, &p); diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index c397231495..198c70e27d 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -57,7 +57,7 @@ mod context; mod cursor; mod input; -pub use context::{GlyphSnap, MarqueeMode, PaintDefaults, ScreenFrame, ToolContext}; +pub use context::{GlyphSnap, MarqueeMode, PaintDefaults, ScreenFrame, ToolContext, nudge_step}; pub use cursor::Cursor; pub use input::{Action, Mods, PenPose, PointerEvent, PointerKind, ToolKey}; diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index e66a27b22f..dd7f7fba26 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -2095,7 +2095,6 @@ fn selected_vertical_area_and_path_type_use_vertical_spacing_chords() { } } -/// #3786: Alt+arrows step a selected text object's spacing instead of copying and nudging it. /// #5258: Ctrl/Cmd+arrow nudges the selection by a tenth of the keyboard increment, and /// Shift+Ctrl/Cmd+arrow by one increment, one undo step each. #[test] @@ -2118,6 +2117,7 @@ fn command_arrows_nudge_by_a_tenth_of_the_keyboard_increment() { } } +/// #3786: Alt+arrows step a selected text object's spacing instead of copying and nudging it. #[test] fn alt_arrows_step_selected_type_object() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); From 55f7dc920538db9a773dca99fd03429e3f0889c4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:51:09 -0800 Subject: [PATCH 04/69] Scripts: Document.saveAs, Document.exportFile and app.open with option classes Scripts save, export and open documents through Document.saveAs, Document.exportFile and app.open, with IllustratorSaveOptions, EPSSaveOptions, PDFSaveOptions, ExportOptionsPNG24, ExportOptionsJPEG, ExportOptionsSVG and a PDFFileOptions record, the ExportType and related enumerations, and app.userInteractionLevel. Each method runs file.saveAs, document.export or document.open inside the run's transaction. - A File argument reaches the host as its path only when the File class made it: the path is held in an internal slot that scripts cannot set, and a plain object that imitates a File is refused. - Each path is checked as a File opened for reading or writing would be, before the command runs, and the command's own reads and writes are then held to the script's grants, leaving out the open documents' files. A read-only file is not written over. - Options a command maps are applied; a listed option that is not mapped is accepted only at its documented default, and any other value, a bad type or an out-of-range number throws before anything is written. Without options, saveAs to a .ai, .eps or .pdf path and exportFile as PNG24, JPEG or SVG use the defaults a new options object holds. With pDFPreset named, a PDFSaveOptions option still at its default keeps the preset's value. A raster export at 100% has one pixel per point. - An export or save that writes several files, such as an SVG that writes its embedded images beside it or an EPS with a file per artboard, checks every path before writing the first. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/fileio/export_names.rs | 10 +- crates/engine/src/cmd/fileio/save.rs | 14 +- crates/engine/src/file_access.rs | 26 +- crates/engine/src/script/dom.rs | 11 +- crates/engine/src/script/dom/save_open.rs | 738 +++++++++++++++++++ crates/engine/src/script/files.rs | 36 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_save_open.rs | 510 +++++++++++++ crates/js/src/file_classes.rs | 93 ++- crates/js/src/heap.rs | 7 +- crates/js/src/host.rs | 12 +- crates/js/src/lib.rs | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 36 + docs/target-app-parity.md | 1 + 39 files changed, 1499 insertions(+), 22 deletions(-) create mode 100644 crates/engine/src/script/dom/save_open.rs create mode 100644 crates/engine/src/tests/script_save_open.rs diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 5f2c14bfd5..48a8c828ab 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -73,7 +73,9 @@ pub(super) fn distinct_names_by(names: impl IntoIterator, key: im /// Write an export's files for the destination `path` → `{path, bytes, files?, linked?, …extra}` /// (`files`: every file when there are several; `linked`: the images it links to); with no path -/// → the same with `dataBase64` and `{name, dataBase64}` rows, named after `name`. +/// → the same with `dataBase64` and `{name, dataBase64}` rows, named after `name`. Every path is +/// checked against the file access in force before the first file is written, so a refused path +/// writes none of them. pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_doc::Document, enc: &Encoded, extra: Value) -> Result { let files = enc.named(doc, path.unwrap_or(name)); let (main, linked) = files.split_at(enc.files.len()); @@ -82,6 +84,12 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do None => json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) }), }; if path.is_some() { + #[cfg(not(target_arch = "wasm32"))] + if files.len() > 1 { + for (p, _) in &files { + super::may_write(p)?; + } + } for (p, bytes) in &files { write_file(p, bytes)?; } diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index f03dc6fe0d..94187808c6 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1044,7 +1044,8 @@ impl SaveJob { } /// [`SaveJob::write`], once `stop` has seen the paths of every file it writes to a path, in - /// order: when `stop` returns a value, nothing is written and that value is returned. Work + /// order: when `stop` returns a value, nothing is written and that value is returned. When a + /// save writes several files and the file access in force refuses one, none is written. Work /// canceled ([`crate::cancel`]) before the first file is written returns /// [`crate::EngineError::Cancelled`] and writes nothing; once the first file is written, the /// others are written too. @@ -1069,6 +1070,15 @@ impl SaveJob { if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::>()) { return Ok(stopped); } + // Every path is checked against the file access in force before the first file is + // written. A refused file goes to `write` first, which refuses it with the error the + // caller gives (naming the path as the caller does), so none of the files is written. + #[cfg(not(target_arch = "wasm32"))] + if files.len() > 1 + && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) + { + write(p, bytes)?; + } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { write(p, bytes)?; @@ -1369,7 +1379,7 @@ pub(super) fn specs() -> Vec { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when one of a save's files may not be written, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", has_doc, |s, p| save(s, SaveMode::Save, p) ), diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c5ecee374e..4769146ad8 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -310,7 +310,9 @@ impl ScriptGate { Access::Read => self.read.allows(&real) || self.write.allows(&real), Access::Write => self.write.allows(&real), }; - scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) + // A read-only file is not written over, also where a rename could replace it. + let read_only = matches!(access, Access::Write) && std::fs::metadata(&real).is_ok_and(|m| m.is_file() && m.permissions().readonly()); + !read_only && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real))) }); if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } } @@ -957,6 +959,28 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + #[test] + fn a_script_gate_does_not_write_over_a_read_only_file() { + let (base, _) = folders("gate-read-only"); + let out = base.join("out/kept.svg"); + std::fs::write(&out, "").unwrap(); + let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::of_folder(&base.join("out")), documents: vec![], also: None }; + let (kept, fresh) = (s(out.clone()), s(base.join("out/new.svg"))); + let check = |p: &str| with_script_gate(gate.clone(), || (check_write(p).is_ok(), check_read(p).is_ok())); + assert_eq!(check(&kept), (true, true)); + let mut perms = std::fs::metadata(&out).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&out, perms.clone()).unwrap(); + assert_eq!(check(&kept), (false, true), "a read-only file is read but not written"); + assert!(check(&fresh).0, "a new file next to it is written"); + let documents = ScriptGate { documents: vec![kept.clone()], ..gate.clone() }; + assert!(!with_script_gate(documents, || check_write(&kept).is_ok()), "also when it is an open document's file"); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(&out, perms).unwrap(); + let _ = std::fs::remove_dir_all(base); + } + #[test] fn network_paths_are_told_by_name() { for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 241720f786..5e16f2a121 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod save_open; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -92,6 +94,8 @@ pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, + /// `app.userInteractionLevel` ([`save_open`]). + save_options: save_open::State, } impl State { @@ -1707,7 +1711,7 @@ const ENUMS: &[(&str, &[&str])] = &[ /// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { - for (name, members) in ENUMS { + for (name, members) in ENUMS.iter().chain(save_open::ENUMS) { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } @@ -1721,6 +1725,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(save_open::application_members(l)); let preset = { let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { @@ -1761,10 +1766,11 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("selection", property(l, doc_selection, doc_set_selection)), ]); document.extend( - ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] + ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "close"] .into_iter() .map(|m| later(l, "Document", m)), ); + document.extend(save_open::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", @@ -1829,6 +1835,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ); classes.push(class("PageItem", None, page_item, None)); classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.extend(save_open::classes(l)); classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) } diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs new file mode 100644 index 0000000000..ebdebc4c10 --- /dev/null +++ b/crates/engine/src/script/dom/save_open.rs @@ -0,0 +1,738 @@ +//! Saving, exporting and opening documents in the script object model: `Document.saveAs`, +//! `Document.exportFile`, `app.open` and `app.userInteractionLevel`, with the option classes the +//! help pages , +//! , +//! , +//! , +//! , +//! , +//! , +//! and +//! describe. +//! +//! Each method runs a command (`file.saveAs`, `document.export`, `document.open`) inside the run's +//! transaction. The file is a `File` object, and the method reads and writes only where that +//! `File` may ([`super::super::files`]): the path is checked before the command runs, and the +//! command's own reads and writes leave out the files of the open documents that `vc.run`'s +//! commands may use. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `saveAs` without options saves in the format the path's extension names; it writes the file +//! at the path as given. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and +//! `exportFile` as PNG24, JPEG or SVG use the defaults a new options object of that class holds. +//! `exportFile` adds the format's extension unless the name already ends +//! with it (`.png`, `.jpg` or `.jpeg`, `.gif`, `.tif` or `.tiff`, `.svg`, `.svgz`), and writes +//! 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. +//! - An option the classes here map is applied; a listed option that is not mapped is accepted at +//! the default its help page gives and throws an error that says it is not available yet at any +//! other value; a property the help pages do not list is left out. With `pDFPreset` named, a +//! `PDFSaveOptions` option still at a new object's default keeps the preset's value. +//! - `app.open(file, documentColorSpace?, options?)` takes `options` as a `PDFFileOptions` record: +//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. +//! - `app.userInteractionLevel` starts at `UserInteractionLevel.DISPLAYALERTS` in each run. The +//! commands a script runs never show a dialog, so the level does not change what they do, and it +//! never allows a file the script's grants do not. + +use std::cell::Cell; +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; + +use super::{ + Answer, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, current, doc_ref, given, method, named, num, on_doc, property, + text, this_doc, whole, +}; + +/// The most a scale factor of an export takes, in percent. +pub const MAX_SCALE_PERCENT: f64 = 776.19; + +/// What the run keeps for these members: whether `userInteractionLevel` is `DONTDISPLAYALERTS`. +#[derive(Default)] +pub(in crate::script) struct State { + quiet: Cell, +} + +/// The enumerations these members use, as `dom`'s are made. +pub(super) const ENUMS: &[(&str, &[&str])] = &[ + ("ExportType", &["AutoCAD", "FLASH", "GIF", "JPEG", "PNG24", "PNG8", "SVG", "TIFF"]), + ( + "Compatibility", + &[ + "ILLUSTRATOR8", + "ILLUSTRATOR9", + "ILLUSTRATOR10", + "ILLUSTRATOR11", + "ILLUSTRATOR12", + "ILLUSTRATOR13", + "ILLUSTRATOR14", + "ILLUSTRATOR15", + "ILLUSTRATOR16", + "ILLUSTRATOR17", + "ILLUSTRATOR19", + "JAPANESEVERSION3", + ], + ), + ("PDFCompatibility", &["ACROBAT4", "ACROBAT5", "ACROBAT6", "ACROBAT7", "ACROBAT8"]), + ("PDFBoxType", &["PDFARTBOX", "PDFBLEEDBOX", "PDFBOUNDINGBOX", "PDFCROPBOX", "PDFMEDIABOX", "PDFTRIMBOX"]), + ("EPSPreview", &["BWTIFF", "COLORTIFF", "TRANSPARENTCOLORTIFF", "None"]), + ("EPSPostScriptLevelEnum", &["LEVEL2", "LEVEL3"]), + ("PDFOverprint", &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"]), + ("UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"]), +]; + +const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS"; +const QUIET: &str = "UserInteractionLevel.DONTDISPLAYALERTS"; + +/// The default a listed option that is not mapped keeps: a value equal to it is accepted. +#[derive(Clone, Copy)] +enum Default { + Bool(bool), + Num(f64), + Text(&'static str), + /// An enumerated value, by its enumeration and member (`("DownsampleMethod", "NODOWNSAMPLE")` for + /// `DownsampleMethod.NODOWNSAMPLE`). + Member(&'static str, &'static str), + /// The help page gives no default: any value throws. + Unset, +} + +impl Default { + fn matches(self, d: &Data) -> bool { + match (self, d) { + (Default::Bool(a), Data::Bool(b)) => a == *b, + (Default::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9, + (Default::Text(a), Data::String(b)) => a == b, + (Default::Member(e, m), Data::String(b)) => b.split_once('.').is_some_and(|(be, bm)| be == e && bm == m), + _ => false, + } + } +} + +/// A mapped option: from its name and value into the command's params, `Ok(false)` for a name it +/// does not map. +type Mapper = fn(&str, &Data, &mut Map) -> std::result::Result; + +/// An option class: its name, its mapped options, its listed options that are not mapped, and the +/// defaults a new object starts with. +struct OptionClass { + name: &'static str, + map: Mapper, + kept: &'static [(&'static str, Default)], + starts: fn() -> Vec<(&'static str, Data)>, +} + +fn not_available(class: &str, name: &str) -> HostError { + HostError::Error(format!("{class}.{name} is not available yet")) +} + +fn whole_in(d: &Data, what: &str, lo: u64, hi: u64) -> std::result::Result { + match d { + Data::Number(n) => { + whole(*n).filter(|n| (lo..=hi).contains(n)).ok_or_else(|| HostError::Range(format!("{what} must be a whole number from {lo} to {hi}"))) + } + _ => Err(HostError::Type(format!("{what} must be a number"))), + } +} + +/// The member of `enumeration` that `d` names (`"Enumeration.MEMBER"`), one of `members`. +fn member<'a>(d: &'a Data, enumeration: &str, members: &[&str], what: &str) -> std::result::Result<&'a str, HostError> { + let bad = || HostError::Type(format!("{what} must be a {enumeration} value")); + let Data::String(s) = d else { return Err(bad()) }; + let m = s.strip_prefix(enumeration).and_then(|r| r.strip_prefix('.')).ok_or_else(bad)?; + if members.contains(&m) { Ok(m) } else { Err(bad()) } +} + +/// A `Compatibility` value: the versions from 17 on are the file VectorCraft writes; older ones are +/// not available. +fn compatibility(class: &str, d: &Data) -> std::result::Result<(), HostError> { + let all = ENUMS.iter().find(|(n, _)| *n == "Compatibility").map_or(&[][..], |(_, m)| *m); + match member(d, "Compatibility", all, &format!("{class}.compatibility"))? { + "ILLUSTRATOR17" | "ILLUSTRATOR19" => Ok(()), + _ => Err(not_available(class, "compatibility")), + } +} + +/// An artboard range: a string, given to the command as `range` unless it is empty. +fn range(d: &Data, what: &str, p: &mut Map) -> std::result::Result<(), HostError> { + let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) }; + if s.len() > MAX_TEXT_BYTES { + return Err(HostError::Range(format!("{what} is too long"))); + } + if !s.trim().is_empty() { + p.insert("range".into(), json!(s)); + } + Ok(()) +} + +// ---- Save options ---- + +fn ai_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("IllustratorSaveOptions.{name}"); + match name { + "compressed" => p.insert("compress".into(), json!(boolean(d, &what)?)), + "pdfCompatible" => p.insert("pdfCompatible".into(), json!(boolean(d, &what)?)), + "embedICCProfile" => p.insert("embedProfiles".into(), json!(boolean(d, &what)?)), + "compatibility" => { + compatibility("IllustratorSaveOptions", d)?; + None + } + _ => return Ok(false), + }; + Ok(true) +} + +const AI_KEPT: &[(&str, Default)] = &[ + ("artboardRange", Default::Text("")), + ("embedLinkedFiles", Default::Bool(false)), + ("flattenOutput", Default::Member("OutputFlattening", "PRESERVEAPPEARANCE")), + ("fontSubsetThreshold", Default::Num(100.0)), + ("saveMultipleArtboards", Default::Bool(false)), +]; + +fn ai_starts() -> Vec<(&'static str, Data)> { + vec![("compressed", Data::Bool(true)), ("pdfCompatible", Data::Bool(true)), ("embedICCProfile", Data::Bool(false))] +} + +fn eps_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("EPSSaveOptions.{name}"); + match name { + "cmykPostScript" => { + p.insert("cmykPostScript".into(), json!(boolean(d, &what)?)); + } + "includeDocumentThumbnails" => { + p.insert("thumbnails".into(), json!(boolean(d, &what)?)); + } + "postScript" => { + let level = if member(d, "EPSPostScriptLevelEnum", &["LEVEL2", "LEVEL3"], &what)? == "LEVEL2" { 2 } else { 3 }; + p.insert("level".into(), json!(level)); + } + "preview" => { + let (format, transparent) = match member(d, "EPSPreview", &["BWTIFF", "COLORTIFF", "TRANSPARENTCOLORTIFF", "None"], &what)? { + "BWTIFF" => ("tiffBw", None), + "COLORTIFF" => ("tiffColor", Some(false)), + "TRANSPARENTCOLORTIFF" => ("tiffColor", Some(true)), + _ => ("none", None), + }; + p.insert("previewFormat".into(), json!(format)); + if let Some(t) = transparent { + p.insert("transparentPreview".into(), json!(t)); + } + } + "overprint" => { + let keep = member(d, "PDFOverprint", &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"], &what)? == "PRESERVEPDFOVERPRINT"; + p.insert("overprints".into(), json!(if keep { "preserve" } else { "discard" })); + } + "compatibility" => compatibility("EPSSaveOptions", d)?, + _ => return Ok(false), + } + Ok(true) +} + +const EPS_KEPT: &[(&str, Default)] = &[ + ("artboardRange", Default::Text("")), + ("compatibleGradientPrinting", Default::Bool(false)), + ("embedAllFonts", Default::Bool(false)), + ("embedLinkedFiles", Default::Unset), + ("flattenOuput", Default::Unset), + ("saveMultipleArtboards", Default::Bool(false)), +]; + +fn eps_starts() -> Vec<(&'static str, Data)> { + vec![("postScript", text("EPSPostScriptLevelEnum.LEVEL2")), ("overprint", text("PDFOverprint.PRESERVEPDFOVERPRINT"))] +} + +fn pdf_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("PDFSaveOptions.{name}"); + match name { + "pDFPreset" => { + let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) }; + if s.len() > MAX_TEXT_BYTES { + return Err(HostError::Range(format!("{what} is too long"))); + } + p.insert("preset".into(), json!(s)); + } + "compatibility" => { + let version = match member(d, "PDFCompatibility", &["ACROBAT4", "ACROBAT5", "ACROBAT6", "ACROBAT7", "ACROBAT8"], &what)? { + "ACROBAT4" => "1.3", + "ACROBAT5" => "1.4", + "ACROBAT6" => "1.5", + "ACROBAT7" => "1.6", + _ => "1.7", + }; + p.insert("compatibility".into(), json!(version)); + } + "artboardRange" => range(d, &what, p)?, + "preserveEditability" => { + p.insert("preserveEditing".into(), json!(boolean(d, &what)?)); + } + "acrobatLayers" => { + p.insert("createLayers".into(), json!(boolean(d, &what)?)); + } + "compressArt" => { + p.insert("compression".into(), json!({"compressText": boolean(d, &what)?})); + } + _ => return Ok(false), + } + Ok(true) +} + +const PDF_KEPT: &[(&str, Default)] = &[ + ("bleedLink", Default::Bool(true)), + ("bleedOffsetRect", Default::Unset), + ("colorBars", Default::Bool(false)), + ("colorCompression", Default::Member("CompressionQuality", "None")), + ("colorConversionID", Default::Member("ColorConversion", "None")), + ("colorDestinationID", Default::Member("ColorDestination", "None")), + ("colorDownsampling", Default::Num(150.0)), + ("colorDownsamplingImageThreshold", Default::Num(225.0)), + ("colorDownsamplingMethod", Default::Member("DownsampleMethod", "NODOWNSAMPLE")), + ("colorProfileID", Default::Member("ColorProfile", "None")), + ("colorTileSize", Default::Num(256.0)), + ("documentPassword", Default::Text("")), + ("enableAccess", Default::Bool(true)), + ("enableCopy", Default::Bool(true)), + ("enableCopyAccess", Default::Bool(true)), + ("enablePlainText", Default::Bool(false)), + ("flattenerOptions", Default::Unset), + ("flattenerPreset", Default::Unset), + ("fontSubsetThreshold", Default::Num(100.0)), + ("generateThumbnails", Default::Bool(true)), + ("grayscaleCompression", Default::Member("CompressionQuality", "None")), + ("grayscaleDownsampling", Default::Num(150.0)), + ("grayscaleDownsamplingImageThreshold", Default::Num(225.0)), + ("grayscaleDownsamplingMethod", Default::Member("DownsampleMethod", "NODOWNSAMPLE")), + ("grayscaleTileSize", Default::Num(256.0)), + ("monochromeCompression", Default::Member("MonochromeCompression", "None")), + ("monochromeDownsampling", Default::Num(300.0)), + ("monochromeDownsamplingImageThreshold", Default::Num(450.0)), + ("monochromeDownsamplingMethod", Default::Member("DownsampleMethod", "NODOWNSAMPLE")), + ("offset", Default::Num(0.0)), + ("optimization", Default::Bool(false)), + ("outputCondition", Default::Unset), + ("outputConditionID", Default::Unset), + ("pageInformation", Default::Bool(false)), + ("pageMarksType", Default::Member("PageMarksTypes", "Roman")), + ("pDFAllowPrinting", Default::Member("PDFPrintAllowedEnum", "PRINT128HIGHRESOLUTION")), + ("pDFChangesAllowed", Default::Member("PDFChangesAllowedEnum", "CHANGE128ANYCHANGES")), + ("pDFXStandard", Default::Member("PDFXStandard", "PDFXNONE")), + ("pDFXStandardDescription", Default::Unset), + ("permissionPassword", Default::Text("")), + ("printerResolution", Default::Num(800.0)), + ("registrationMarks", Default::Bool(false)), + ("requireDocumentPassword", Default::Bool(false)), + ("requirePermissionPassword", Default::Bool(false)), + ("trapped", Default::Bool(false)), + ("trimMarks", Default::Bool(false)), + ("trimMarkWeight", Default::Member("PDFTrimMarkWeight", "TRIMMARKWEIGHT0125")), + ("viewAfterSaving", Default::Bool(false)), +]; + +fn pdf_starts() -> Vec<(&'static str, Data)> { + vec![ + ("compatibility", text("PDFCompatibility.ACROBAT5")), + ("artboardRange", text("")), + ("preserveEditability", Data::Bool(true)), + ("acrobatLayers", Data::Bool(false)), + ("compressArt", Data::Bool(true)), + ] +} + +const SAVE_CLASSES: &[(OptionClass, &str)] = &[ + (OptionClass { name: "IllustratorSaveOptions", map: ai_map, kept: AI_KEPT, starts: ai_starts }, "ai"), + (OptionClass { name: "EPSSaveOptions", map: eps_map, kept: EPS_KEPT, starts: eps_starts }, "eps"), + (OptionClass { name: "PDFSaveOptions", map: pdf_map, kept: PDF_KEPT, starts: pdf_starts }, "pdf"), +]; + +// ---- Export options ---- + +/// The raster options PNG24 and JPEG share: anti-aliasing, the clip to the artboard and the scale. +fn raster_map(class: &str, name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("{class}.{name}"); + match name { + "antiAliasing" => { + p.insert("antiAlias".into(), json!(if boolean(d, &what)? { "art" } else { "none" })); + } + "artBoardClipping" => { + p.insert("_clip".into(), json!(boolean(d, &what)?)); + } + "horizontalScale" | "verticalScale" => { + let n = match d { + Data::Number(n) if n.is_finite() => *n, + _ => return Err(HostError::Type(format!("{what} must be a finite number"))), + }; + if n <= 0.0 || n > MAX_SCALE_PERCENT { + return Err(HostError::Range(format!("{what} must be more than 0 and at most 776.19"))); + } + let key = if name == "horizontalScale" { "_h" } else { "_v" }; + p.insert(key.into(), json!(n)); + } + _ => return Ok(false), + } + Ok(true) +} + +fn png24_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + if name == "transparency" { + let clear = boolean(d, "ExportOptionsPNG24.transparency")?; + p.insert("background".into(), json!(if clear { "transparent" } else { "white" })); + return Ok(true); + } + raster_map("ExportOptionsPNG24", name, d, p) +} + +const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))]; + +fn png24_starts() -> Vec<(&'static str, Data)> { + vec![ + ("antiAliasing", Data::Bool(true)), + ("artBoardClipping", Data::Bool(false)), + ("horizontalScale", num(100.0)), + ("verticalScale", num(100.0)), + ("transparency", Data::Bool(true)), + ] +} + +fn jpeg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + match name { + "qualitySetting" => { + p.insert("quality".into(), json!(whole_in(d, "ExportOptionsJPEG.qualitySetting", 0, 100)?)); + Ok(true) + } + "optimization" => { + let optimized = boolean(d, "ExportOptionsJPEG.optimization")?; + p.insert("method".into(), json!(if optimized { "optimized" } else { "baseline" })); + Ok(true) + } + _ => raster_map("ExportOptionsJPEG", name, d, p), + } +} + +const JPEG_KEPT: &[(&str, Default)] = + &[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))]; + +fn jpeg_starts() -> Vec<(&'static str, Data)> { + vec![ + ("antiAliasing", Data::Bool(true)), + ("horizontalScale", num(100.0)), + ("verticalScale", num(100.0)), + ("optimization", Data::Bool(true)), + ("qualitySetting", num(30.0)), + ] +} + +fn svg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("ExportOptionsSVG.{name}"); + match name { + "coordinatePrecision" => { + p.insert("decimals".into(), json!(whole_in(d, &what, 1, 7)?)); + } + "embedRasterImages" => { + p.insert("images".into(), json!(if boolean(d, &what)? { "embed" } else { "link" })); + } + "compressed" => { + p.insert("_svgz".into(), json!(boolean(d, &what)?)); + } + "preserveEditability" => { + p.insert("preserveEditing".into(), json!(boolean(d, &what)?)); + } + "includeVariablesAndDatasets" => { + p.insert("variableData".into(), json!(boolean(d, &what)?)); + } + _ => return Ok(false), + } + Ok(true) +} + +const SVG_KEPT: &[(&str, Default)] = &[ + ("artboardRange", Default::Text("")), + ("cssProperties", Default::Member("SVGCSSPropertyLocation", "STYLEATTRIBUTES")), + ("documentEncoding", Default::Member("SVGDocumentEncoding", "ASCII")), + ("DTD", Default::Member("SVGDTDVersion", "SVG1_1")), + ("fontSubsetting", Default::Member("SVGFontSubsetting", "ALLGLYPHS")), + ("fontType", Default::Member("SVGFontType", "CEFFONT")), + ("includeFileInfo", Default::Bool(false)), + ("includeUnusedStyles", Default::Bool(false)), + ("optimizeForSVGViewer", Default::Bool(false)), + ("saveMultipleArtboards", Default::Bool(false)), + ("slices", Default::Bool(false)), + ("sVGAutoKerning", Default::Bool(false)), + ("sVGTextOnPath", Default::Bool(false)), +]; + +fn svg_starts() -> Vec<(&'static str, Data)> { + vec![ + ("compressed", Data::Bool(false)), + ("coordinatePrecision", num(3.0)), + ("embedRasterImages", Data::Bool(false)), + ("includeVariablesAndDatasets", Data::Bool(false)), + ("preserveEditability", Data::Bool(false)), + ] +} + +const PNG24: OptionClass = OptionClass { name: "ExportOptionsPNG24", map: png24_map, kept: PNG24_KEPT, starts: png24_starts }; +const JPEG: OptionClass = OptionClass { name: "ExportOptionsJPEG", map: jpeg_map, kept: JPEG_KEPT, starts: jpeg_starts }; +const SVG: OptionClass = OptionClass { name: "ExportOptionsSVG", map: svg_map, kept: SVG_KEPT, starts: svg_starts }; + +/// An `ExportType`: the format `document.export` writes, the extensions a file name may already +/// end with (the first is added), and its option class (`None`: no options are taken). +struct ExportKind { + format: &'static str, + extensions: &'static [&'static str], + options: Option<&'static OptionClass>, +} + +fn export_kind(d: &Data) -> std::result::Result { + let all = ENUMS.iter().find(|(n, _)| *n == "ExportType").map_or(&[][..], |(_, m)| *m); + let raster = |format, extensions| ExportKind { format, extensions, options: None }; + Ok(match member(d, "ExportType", all, "exportType")? { + "PNG24" => ExportKind { format: "png", extensions: &["png"], options: Some(&PNG24) }, + "JPEG" => ExportKind { format: "jpg", extensions: &["jpg", "jpeg"], options: Some(&JPEG) }, + "SVG" => ExportKind { format: "svg", extensions: &["svg"], options: Some(&SVG) }, + "PNG8" => raster("png8", &["png"]), + "GIF" => raster("gif", &["gif"]), + "TIFF" => raster("tiff", &["tif", "tiff"]), + other => return Err(HostError::Error(format!("ExportType.{other} is not available yet"))), + }) +} + +/// The command's params for the options object `d` of `class`, read as the module's rules say. +fn options_params(class: &OptionClass, d: &Data) -> std::result::Result, HostError> { + let wrong = || HostError::Type(format!("the options must be an {} object", class.name)); + let Data::Object(items) = d else { return Err(wrong()) }; + if !items.iter().any(|(k, v)| k == "typename" && matches!(v, Data::String(s) if s == class.name)) { + return Err(wrong()); + } + // With a PDF preset named, an option still at a new object's default leaves the preset's value. + let preset = class.name == "PDFSaveOptions" && items.iter().any(|(k, v)| k == "pDFPreset" && matches!(v, Data::String(s) if !s.is_empty())); + let starts = if preset { (class.starts)() } else { Vec::new() }; + let mut p = Map::new(); + for (k, v) in items { + if k == "typename" || matches!(v, Data::Undefined) || starts.iter().any(|(n, s)| n == k && s == v) { + continue; + } + if (class.map)(k, v, &mut p)? { + continue; + } + match class.kept.iter().find(|(n, _)| n == k) { + Some((_, default)) if default.matches(v) => {} + Some(_) => return Err(not_available(class.name, k)), + None => {} + } + } + Ok(p) +} + +/// What `new Name()` gives for `class`: its `typename` and the defaults its help page gives for the +/// options mapped here. +fn fresh(class: &OptionClass) -> Data { + let mut items = vec![("typename".to_string(), text(class.name))]; + items.extend((class.starts)().into_iter().map(|(k, v)| (k.to_string(), v))); + Data::Object(items) +} + +/// The typename of an options object, when it has one. +fn typename(d: &Data) -> Option<&str> { + let Data::Object(items) = d else { return None }; + items.iter().find_map(|(k, v)| match (k.as_str(), v) { + ("typename", Data::String(s)) => Some(s.as_str()), + _ => None, + }) +} + +// ---- Files ---- + +/// The path of the `File` argument `d`, or a `TypeError` naming the method. +fn file_path<'a>(d: &'a Data, method: &str) -> std::result::Result<&'a str, HostError> { + vectorcraft_js::file_ref_path(d).ok_or_else(|| HostError::Type(format!("{method} needs a File"))) +} + +/// The error a refused path throws: the `File` error and the path. +fn refused(message: &str, path: &str) -> HostError { + HostError::Error(format!("{message}: {path}")) +} + +/// Runs `f` with the commands' reads and writes held to the script's own grants +/// ([`super::super::files::Disk::exact`]). +fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer { + h.disk.borrow_mut().exact = true; + let r = f(); + h.disk.borrow_mut().exact = false; + r +} + +/// The path to give a command for the real path `real`. +fn plain(real: std::path::PathBuf) -> String { + crate::cmd::findfiles::plain(real).to_string_lossy().into_owned() +} + +/// `document.saveAs(file, options?)`: `file.saveAs` on the document, in the format the options' +/// class names (`ai`, `eps`, `pdf`), or without options in the format of the path's extension. +fn doc_save_as(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = file_path(arg(a, 1), "saveAs")?; + let mut p = Map::new(); + let given_options = given(arg(a, 2)).filter(|d| !matches!(d, Data::Null)); + // Without options, a path ending in `.ai`, `.eps` or `.pdf` takes the defaults a new options + // object of that format's class holds. + let extension = path.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).map(|(_, e)| e.to_ascii_lowercase()); + let by_extension = SAVE_CLASSES.iter().find(|(_, f)| Some(*f) == extension.as_deref()).map(|(c, _)| fresh(c)); + if let Some(o) = given_options.or(by_extension.as_ref()) { + let name = typename(o); + let Some((class, format)) = SAVE_CLASSES.iter().find(|(c, _)| Some(c.name) == name) else { + return Err(HostError::Type("saveAs options must be IllustratorSaveOptions, EPSSaveOptions or PDFSaveOptions".into())); + }; + let q = options_params(class, o)?; + p.insert("format".into(), json!(format)); + if *format == "ai" { + p.extend(q); + } else if !q.is_empty() { + p.insert("options".into(), Value::Object(q)); + } + } + let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; + p.insert("path".into(), json!(plain(real))); + exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; + Ok(Data::Undefined) +} + +/// `path` with the extension of `kind` added, unless its name already ends with one of them. +fn with_extension(path: &str, kind: &ExportKind, svgz: bool) -> String { + let extensions: &[&str] = if svgz { &["svgz"] } else { kind.extensions }; + let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_lowercase(); + match extensions.first() { + Some(first) if !extensions.iter().any(|e| name.ends_with(&format!(".{e}"))) => format!("{path}.{first}"), + _ => path.to_string(), + } +} + +/// `document.exportFile(file, exportType, options?)`: `document.export` of one file, which leaves +/// the document's path as it is. +fn doc_export_file(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = file_path(arg(a, 1), "exportFile")?; + let kind = export_kind(arg(a, 2))?; + // Without options, an export takes the defaults a new options object of its class holds. + let mut p = match given(arg(a, 3)).filter(|d| !matches!(d, Data::Null)) { + None => match kind.options { + Some(class) => options_params(class, &fresh(class))?, + None => Map::new(), + }, + Some(o) => match kind.options { + Some(class) => options_params(class, o)?, + None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))), + }, + }; + let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false); + let clip = p.remove("_clip").and_then(|v| v.as_bool()).unwrap_or(false); + let (hs, vs) = (p.remove("_h").and_then(|v| v.as_f64()).unwrap_or(100.0), p.remove("_v").and_then(|v| v.as_f64()).unwrap_or(100.0)); + if (hs - vs).abs() > 1e-9 { + 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. + if kind.format != "svg" { + p.insert("scale".into(), json!(hs / 100.0)); + } + let format = if svgz { "svgz" } else { kind.format }; + p.insert("format".into(), json!(format)); + if kind.format == "svg" { + p.insert("useArtboards".into(), json!(false)); + } else if clip { + let artboard = super::with_doc(h, doc, |_, st| super::active_artboard(st)); + p.insert("artboard".into(), json!(artboard)); + } else { + p.insert("useArtboards".into(), json!(false)); + } + let named = with_extension(path, &kind, svgz); + let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; + p.insert("path".into(), json!(plain(real))); + exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; + Ok(Data::Undefined) +} + +/// `app.open(file, documentColorSpace?, options?)`: `document.open` of the file, which becomes +/// the active document. → the document. +fn app_open(h: &Host, a: &[Data]) -> Answer { + let path = file_path(arg(a, 1), "open")?; + let mut p = Map::new(); + if let Some(d) = given(arg(a, 2)).filter(|d| !matches!(d, Data::Null)) { + let mode = if member(d, "DocumentColorSpace", &["CMYK", "RGB"], "documentColorSpace")? == "RGB" { "rgb" } else { "cmyk" }; + p.insert("colorMode".into(), json!(mode)); + } + if let Some(o) = given(arg(a, 3)).filter(|d| !matches!(d, Data::Null)) { + let Data::Object(items) = o else { return Err(HostError::Type("open's options must be a PDFFileOptions record".into())) }; + if typename(o).is_some_and(|t| t != "PDFFileOptions") { + return Err(HostError::Type("open's options must be a PDFFileOptions record".into())); + } + for (k, v) in items { + match k.as_str() { + "pageToOpen" => { + p.insert("page".into(), json!(whole_in(v, "PDFFileOptions.pageToOpen", 1, 1_000_000)?)); + } + "pDFCropToBox" => { + let boxes = ["PDFARTBOX", "PDFBLEEDBOX", "PDFBOUNDINGBOX", "PDFCROPBOX", "PDFMEDIABOX", "PDFTRIMBOX"]; + let crop = match member(v, "PDFBoxType", &boxes, "PDFFileOptions.pDFCropToBox")? { + "PDFARTBOX" => "art", + "PDFBLEEDBOX" => "bleed", + "PDFBOUNDINGBOX" => "bounding", + "PDFCROPBOX" => "crop", + "PDFMEDIABOX" => "media", + _ => "trim", + }; + p.insert("cropTo".into(), json!(crop)); + } + _ => {} + } + } + } + let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; + p.insert("path".into(), json!(plain(real))); + let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?; + let index = match &r { + Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { + ("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()), + _ => None, + }), + _ => None, + }; + let s = h.session.borrow(); + let st = index.and_then(|i| s.documents().get(i)).or_else(|| s.active()).ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) +} + +fn app_interaction(h: &Host, _: &[Data]) -> Answer { + Ok(text(if h.dom.save_options.quiet.get() { QUIET } else { DISPLAY })) +} + +fn app_set_interaction(h: &Host, a: &[Data]) -> Answer { + let quiet = member(arg(a, 1), "UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"], "userInteractionLevel")? == "DONTDISPLAYALERTS"; + h.dom.save_options.quiet.set(quiet); + Ok(Data::Undefined) +} + +/// The members these add to `Application`. +pub(super) fn application_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("open", method(l, app_open)), ("userInteractionLevel", property(l, app_interaction, app_set_interaction))]) +} + +/// The members these add to `Document`. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("saveAs", method(l, doc_save_as)), ("exportFile", method(l, doc_export_file))]) +} + +/// The option classes: each `new Name()` gives a record with its `typename` and the defaults its +/// help page gives for the options mapped here. +pub(super) fn classes(link: &Link) -> Vec { + let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG]); + all.map(|c| { + let l = link.clone(); + let f: HostFunction = Rc::new(move |_: Vec| { + current(&l)?.charge_call(64)?; + Ok(fresh(c)) + }); + HostClass { name: c.name.into(), parent: None, members: Vec::new(), index: None, construct: Some(f) } + }) + .collect() +} diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index c0694bbd81..40b1fe0465 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -115,6 +115,7 @@ pub(crate) const MASK_TOO_COSTLY: &str = "Script folder mask takes too many step pub(crate) const NOT_WRITABLE: &str = "Script file is not open for writing"; pub(crate) const UNENCODABLE: &str = "Script file cannot encode the text"; pub(crate) const WRITE_FAILED: &str = "Script file could not be written"; +pub(crate) const READ_ONLY: &str = "Script file is read-only"; pub(crate) const NOT_EMPTY: &str = "Script folder is not empty"; pub(crate) const NAME_TAKEN: &str = "Script file name is already in use"; pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder"; @@ -271,6 +272,9 @@ pub(crate) struct Disk { /// when they were last written to the grants file. kept: Vec<(std::path::PathBuf, bool, bool)>, recorded: usize, + /// While set, the gate of a command the script runs leaves out the files of the open documents + /// ([`Disk::gate`]): the command reads and writes only where the script's `File` objects may. + pub(crate) exact: bool, /// The write bits setting `readonly` cleared from each file in this run, by its device and /// inode, which a rename keeps, at most [`MAX_ENTRIES`] files: clearing `readonly` gives them back. #[cfg(unix)] @@ -324,6 +328,7 @@ impl Disk { ran_too_much: setup.engine_code.1, kept: Vec::new(), recorded: 0, + exact: false, #[cfg(unix)] cleared: HashMap::new(), }; @@ -457,6 +462,8 @@ impl Disk { /// The gate for a command the script runs: the places it reads and writes now, and the files of /// the open documents, `documents`. pub(crate) fn gate(&self, documents: Vec) -> crate::file_access::ScriptGate { + // A save, export or open of a `File` the script names reads and writes as its `File` would. + let documents = if self.exact { Vec::new() } else { documents }; crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, also: None } } @@ -676,6 +683,35 @@ impl Disk { } } + /// The real path a save or export of the document to `path` writes, as a `File` opened for + /// writing would write it ([`Disk::target`]), or why it may not: a folder is not a file, and a + /// read-only file is not written over. + pub(crate) fn save_target(&self, path: &str) -> Result { + let real = self.target(path, true)?; + match std::fs::metadata(&real) { + Ok(m) if !m.is_file() => Err(NOT_REGULAR), + Ok(m) if m.permissions().readonly() => Err(READ_ONLY), + _ => Ok(real), + } + } + + /// The real path of the file `path` that opening it as a document reads, as a `File` reads it + /// ([`ScriptScope::locate`]), or why it may not: it is not there, it is not a regular file, or + /// the script may not read it. + pub(crate) fn open_target(&self, path: &str) -> Result { + let p = self.checked(path)?; + let real = match self.scope.locate(p) { + Ok(real) => real, + Err(ScriptRead::Missing) => return Err(NOT_FOUND), + Err(ScriptRead::Refused | ScriptRead::TooLarge) => return Err(ACCESS_DENIED), + Err(ScriptRead::Failed(_)) => return Err(READ_FAILED), + }; + if !real.is_file() { + return Err(NOT_REGULAR); + } + Ok(real) + } + /// Counts `n` more bytes written in the run, which ends past [`MAX_RUN_BYTES`]. fn charge_write(&mut self, n: usize) -> Result<(), HostError> { self.written = self.written.saturating_add(n); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index adcaefd59d..436d74cf75 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -178,6 +178,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_save_open; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs new file mode 100644 index 0000000000..809fed0ef8 --- /dev/null +++ b/crates/engine/src/tests/script_save_open.rs @@ -0,0 +1,510 @@ +//! Saving, exporting and opening documents from a script: `Document.saveAs`, `Document.exportFile`, +//! `app.open`, their option classes and `app.userInteractionLevel`, and the file grants each path +//! goes through. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +const DENIED: &str = "Script file access denied"; + +/// A fresh folder for test `name`, by its real path, with `main` for the script. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-save-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("outside")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// A session whose scripts keep their data folders in `base/settings/Script Data`. +fn session(base: &Path) -> Session { + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s +} + +/// Runs `main/main.jsx` in `base` with the text `text` in `s`. +fn run(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text.as_bytes()).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +fn logged(s: &mut Session, base: &Path, text: &str) -> Value { + run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"))["log"].clone() +} + +fn failure(s: &mut Session, base: &Path, text: &str) -> String { + run(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string() +} + +/// The script's data folder, where it may write. +fn data_folder(s: &mut Session, base: &Path) -> PathBuf { + PathBuf::from(logged(s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap()) +} + +fn quoted(p: &Path) -> String { + serde_json::to_string(&p.to_string_lossy()).unwrap() +} + +#[test] +fn save_as_export_file_and_open_write_and_read_where_the_script_may() { + let base = folder("happy"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "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\ + d.saveAs(new File(dir + '/a.svg'));\n\ + var o = new PDFSaveOptions(); vc.log([o.typename, o.compatibility, o.preserveEditability]);\n\ + o.compatibility = PDFCompatibility.ACROBAT7; o.viewAfterSaving = false; o.someOtherName = 3;\n\ + o.colorCompression = 'CompressionQuality.None';\n\ + d.saveAs(new File(dir + '/b.pdf'), o); vc.log(d.name);\n\ + var p = new ExportOptionsPNG24(); p.horizontalScale = p.verticalScale = 200; p.artBoardClipping = true;\n\ + d.exportFile(new File(dir + '/c'), ExportType.PNG24, p);\n\ + d.exportFile(new File(dir + '/e.JPG'), ExportType.JPEG);\n\ + var v = new ExportOptionsSVG(); v.compressed = true; v.coordinatePrecision = 2;\n\ + d.exportFile(new File(dir + '/f'), ExportType.SVG, v); vc.log(d.name);\n\ + var g = app.open(new File(dir + '/a.svg'));\n\ + vc.log([g.typename, app.documents.length, app.activeDocument.name === g.name, g.name]);\n\ + var u = [app.userInteractionLevel]; app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS; u.push(app.userInteractionLevel); vc.log(u);" + ), + ); + assert_eq!(out[0], json!(["PDFSaveOptions", "PDFCompatibility.ACROBAT5", true])); + assert_eq!(out[1], json!("b.pdf"), "saveAs gives the document the new file"); + assert_eq!(out[2], json!("b.pdf"), "exportFile leaves the document's file as it is"); + assert_eq!(out[3], json!(["Document", 2, true, "a.svg"])); + assert_eq!(out[4], json!(["UserInteractionLevel.DISPLAYALERTS", "UserInteractionLevel.DONTDISPLAYALERTS"])); + assert!(std::fs::read_to_string(dir.join("a.svg")).unwrap().contains(" = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != central).collect(); + boards.sort(); + assert!(central.is_file() && boards.len() == 2, "the central file and a file per artboard: {boards:?}"); + let board = boards.pop().unwrap(); + std::fs::remove_file(¢ral).unwrap(); + let mut perms = std::fs::metadata(&board).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&board, perms.clone()).unwrap(); + let e = failure(&mut s, &base, &save); + assert!(e.contains(DENIED), "{e}"); + assert!(!central.exists(), "the central file is not written when an artboard's file may not be"); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(&board, perms).unwrap(); + let _ = std::fs::remove_dir_all(base); +} + +/// Every path goes through the script's file grants, as a `File` opened for reading or writing. +#[test] +fn save_as_export_file_and_open_refuse_paths_outside_the_grants() { + let base = folder("refused"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + std::fs::write(base.join("outside/secret.svg"), "").unwrap(); + std::fs::write(base.join("settings/Script Grants.json"), "{}").unwrap(); + std::fs::write(dir.join("kept.svg"), "kept").unwrap(); + let mut perms = std::fs::metadata(dir.join("kept.svg")).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(dir.join("kept.svg"), perms).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let undo = s.active().unwrap().history.undo.len(); + let outside = quoted(&base.join("outside/x.svg")); + let grants = quoted(&base.join("settings/Script Grants.json")); + let kept = quoted(&dir.join("kept.svg")); + let secret = quoted(&base.join("outside/secret.svg")); + let cases = [ + format!("app.activeDocument.saveAs(new File({outside}));"), + format!("app.activeDocument.exportFile(new File({outside}), ExportType.PNG24);"), + format!("app.activeDocument.saveAs(new File({grants}));"), + format!("app.open(new File({secret}));"), + format!("app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS; app.activeDocument.saveAs(new File({outside}));"), + ]; + for case in &cases { + let e = failure(&mut s, &base, &format!("Folder.userData; {case}")); + assert!(e.contains(DENIED), "{case}: {e}"); + } + let e = failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({kept}));")); + assert!(e.contains("Script file is read-only"), "{e}"); + let e = failure(&mut s, &base, &format!("app.activeDocument.saveAs(new File({}));", quoted(&dir))); + assert!(e.contains("Script file") && !e.contains("ran"), "a folder is not saved over: {e}"); + assert_eq!(std::fs::read_to_string(dir.join("kept.svg")).unwrap(), "kept"); + assert_eq!(std::fs::read_to_string(base.join("settings/Script Grants.json")).unwrap(), "{}"); + assert!(!base.join("outside/x.svg").exists() && !base.join("outside/x.svg.png").exists()); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.active().unwrap().path, None, "a refused save leaves the document's file as it is"); + assert_eq!(s.active().unwrap().history.undo.len(), undo, "and adds no undo step"); + let mut perms = std::fs::metadata(dir.join("kept.svg")).unwrap().permissions(); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(dir.join("kept.svg"), perms).unwrap(); + let _ = std::fs::remove_dir_all(base); +} + +/// The file of an open document is not written or read through a script method unless the +/// script's grants take it, though `vc.run`'s commands may use it. +#[test] +fn an_open_documents_file_is_not_saved_over_without_a_grant() { + let base = folder("opendoc"); + let mut s = session(&base); + let path = base.join("outside/open.svg"); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("file.saveAs", &json!({"path": path.to_string_lossy()})).unwrap(); + let before = std::fs::read(&path).unwrap(); + let e = failure(&mut s, &base, &format!("app.activeDocument.saveAs(new File({}));", quoted(&path))); + assert!(e.contains(DENIED), "{e}"); + let e = failure(&mut s, &base, &format!("app.activeDocument.exportFile(new File({}), ExportType.SVG);", quoted(&path))); + assert!(e.contains(DENIED), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), before); + let _ = std::fs::remove_dir_all(base); +} + +/// A file `open` reads besides the one it names, here an SVG's linked image, is read only where +/// the script's grants allow, though it is an open document's file. +#[test] +fn open_reads_linked_files_only_where_the_script_may() { + let base = folder("linked"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let linked = base.join("outside/linked.svg"); + std::fs::write(&linked, "").unwrap(); + s.execute("document.open", &json!({"path": linked.to_string_lossy()})).unwrap(); + assert!(s.active().unwrap().path.is_some(), "the linked file is an open document's file"); + let href = linked.to_string_lossy().replace('\\', "/"); + std::fs::write( + dir.join("page.svg"), + format!(""), + ) + .unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&dir.join("page.svg")))); + assert_eq!(s.documents().len(), 2); + let ims = |s: &Session| { + let mut out = vec![]; + s.active().unwrap().doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + out.push((im.width, im.height, im.link.as_ref().map(|l| (l.modified.is_some(), l.hash.is_some())))); + } + }); + out + }; + let kinds = |s: &Session| { + let mut out = vec![]; + s.active().unwrap().doc.walk(|n| out.push(format!("{:?}", n.kind).chars().take(12).collect::())); + out + }; + assert_eq!(ims(&s), vec![(64, 64, Some((false, false)))], "the linked file is a placeholder: {:?}", kinds(&s)); + // Opened by the app, a copy of the file reads its image. + std::fs::copy(dir.join("page.svg"), dir.join("copy.svg")).unwrap(); + s.execute("document.open", &json!({"path": dir.join("copy.svg").to_string_lossy()})).unwrap(); + assert!(ims(&s).is_empty() && kinds(&s).iter().any(|k| k.starts_with("Path")), "{:?}", kinds(&s)); + let _ = std::fs::remove_dir_all(base); +} + +/// An SVG export with `embedRasterImages` false writes the document's embedded image beside the +/// SVG, and when that file may not be written, the SVG is not written either. +#[test] +fn an_svg_export_writes_nothing_when_one_of_its_files_is_refused() { + let base = folder("svgimages"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let pic = base.join("outside/pic.png"); + std::fs::write(&pic, super::links::png(2, 2, [10, 200, 30])).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": false})).unwrap(); + let export = + format!("Folder.userData; app.activeDocument.exportFile(new File({}), ExportType.SVG, new ExportOptionsSVG());", quoted(&dir.join("a.svg"))); + logged(&mut s, &base, &export); + let svg = dir.join("a.svg"); + let mut images: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != svg).collect(); + assert_eq!(images.len(), 1, "the embedded image is written beside the SVG: {images:?}"); + let image = images.remove(0); + std::fs::remove_file(&svg).unwrap(); + let mut perms = std::fs::metadata(&image).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&image, perms.clone()).unwrap(); + let e = failure(&mut s, &base, &export); + assert!(e.contains(DENIED), "{e}"); + assert!(!svg.exists(), "the SVG is not written when its image may not be"); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(&image, perms).unwrap(); + let _ = std::fs::remove_dir_all(base); +} + +/// A link inside a granted folder that leads out of it is followed and refused. +#[cfg(unix)] +#[test] +fn a_link_out_of_the_granted_folder_is_refused() { + let base = folder("link"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + std::os::unix::fs::symlink(base.join("outside"), dir.join("away")).unwrap(); + std::os::unix::fs::symlink(base.join("outside/target.svg"), dir.join("file.svg")).unwrap(); + std::fs::write(base.join("outside/read.svg"), "").unwrap(); + std::os::unix::fs::symlink(base.join("outside/read.svg"), dir.join("read.svg")).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for name in ["away/x.svg", "file.svg"] { + let e = failure(&mut s, &base, &format!("app.activeDocument.saveAs(new File({}));", quoted(&dir.join(name)))); + assert!(e.contains(DENIED), "{name}: {e}"); + } + let e = failure(&mut s, &base, &format!("app.open(new File({}));", quoted(&dir.join("read.svg")))); + assert!(e.contains(DENIED), "{e}"); + assert!(std::fs::read_dir(base.join("outside")).unwrap().count() == 1, "nothing is written outside"); + assert_eq!(s.documents().len(), 1); + let _ = std::fs::remove_dir_all(base); +} + +/// Bad arguments throw before anything is written or opened. +#[test] +fn bad_arguments_are_refused_with_an_error() { + let base = folder("bad"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let f = format!("new File({})", quoted(&dir.join("x.svg"))); + let huge = "a".repeat(5000); + let cases: Vec<(String, &str)> = vec![ + ("app.activeDocument.saveAs('x.svg');".into(), "saveAs needs a File"), + (format!("app.activeDocument.saveAs({{'\\u0000fileRef': {}}});", quoted(&dir.join("x.svg"))), "is not plain data"), + (format!("app.activeDocument.saveAs({f}, {{typename: 'Nope'}});"), "saveAs options must be"), + (format!("app.activeDocument.saveAs({f}, new ExportOptionsSVG());"), "saveAs options must be"), + (format!("var o = new IllustratorSaveOptions(); o.compressed = 'yes'; app.activeDocument.saveAs({f}, o);"), "must be true or false"), + ( + format!("var o = new IllustratorSaveOptions(); o.compatibility = Compatibility.ILLUSTRATOR8; app.activeDocument.saveAs({f}, o);"), + "is not available yet", + ), + ( + format!("var o = new PDFSaveOptions(); o.trimMarks = true; app.activeDocument.saveAs({f}, o);"), + "PDFSaveOptions.trimMarks is not available yet", + ), + ( + format!("var o = new PDFSaveOptions(); o.colorCompression = 'Unrelated.None'; app.activeDocument.saveAs({f}, o);"), + "PDFSaveOptions.colorCompression is not available yet", + ), + (format!("var o = new PDFSaveOptions(); o.pDFPreset = '{huge}'; app.activeDocument.saveAs({f}, o);"), "too long"), + (format!("var o = new EPSSaveOptions(); o.postScript = 'LEVEL2'; app.activeDocument.saveAs({f}, o);"), "EPSPostScriptLevelEnum"), + (format!("app.activeDocument.exportFile({f}, 'PNG24');"), "ExportType"), + (format!("app.activeDocument.exportFile({f}, ExportType.FLASH);"), "is not available yet"), + (format!("app.activeDocument.exportFile({f}, ExportType.PNG24, new ExportOptionsJPEG());"), "ExportOptionsPNG24"), + ( + format!( + "var p = new ExportOptionsPNG24(); p.horizontalScale = p.verticalScale = 1e9; app.activeDocument.exportFile({f}, ExportType.PNG24, p);" + ), + "at most", + ), + ( + format!("var p = new ExportOptionsPNG24(); p.horizontalScale = 50; app.activeDocument.exportFile({f}, ExportType.PNG24, p);"), + "not available yet", + ), + ( + format!("var p = new ExportOptionsJPEG(); p.qualitySetting = 101; app.activeDocument.exportFile({f}, ExportType.JPEG, p);"), + "from 0 to 100", + ), + (format!("app.activeDocument.exportFile({f}, ExportType.GIF, {{}});"), "not available yet"), + (format!("app.open({f}, 'RGB');"), "DocumentColorSpace"), + (format!("app.open({f}, undefined, {{pageToOpen: 0}});"), "from 1"), + (format!("app.open({f}, undefined, {{pDFCropToBox: 'art'}});"), "PDFBoxType"), + (format!("app.open({f}, undefined, 5);"), "PDFFileOptions"), + ("app.userInteractionLevel = 'quiet';".into(), "UserInteractionLevel"), + (format!("app.open({});", quoted(&dir.join("x.svg"))), "open needs a File"), + ]; + for (case, wanted) in &cases { + let e = failure(&mut s, &base, &format!("Folder.userData; {case}")); + assert!(e.contains(wanted), "{case}: {e}"); + } + let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&dir.join("missing.svg")))); + assert!(e.contains(crate::script::files::NOT_FOUND), "{e}"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing was written"); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.active().unwrap().path, None); + let _ = std::fs::remove_dir_all(base); +} + +/// Only a `File` the `File` class made names a file. An object made from `File.prototype` and a +/// plain object throw a `TypeError`, and a `File` whose hidden path property a script set keeps its +/// own path, so nothing is written or opened at the path the script put there. +#[test] +fn a_forged_file_is_refused() { + let base = folder("forged"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + std::fs::write(dir.join("real.svg"), "").unwrap(); + std::fs::write(base.join("outside/secret.svg"), "").unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let (x, real) = (quoted(&dir.join("x.svg")), quoted(&dir.join("real.svg"))); + let (out, secret) = (quoted(&base.join("outside/x.svg")), quoted(&base.join("outside/secret.svg"))); + let calls = |f: &str, read: &str| { + [format!("app.activeDocument.saveAs({f});"), format!("app.activeDocument.exportFile({f}, ExportType.SVG);"), format!("app.open({read});")] + }; + for made in ["Object.create(File.prototype)", "{}"] { + let make = |p: &str| format!("(function () {{ var f = {made}; f.__vcPath = {p}; return f; }})()"); + for case in calls(&make(&x), &make(&real)) { + let text = format!("Folder.userData; try {{ {case} vc.log('ran'); }} catch (e) {{ vc.log([e.name, e.message]); }}"); + let log = logged(&mut s, &base, &text); + assert_eq!(log[0][0], json!("TypeError"), "{case}: {log}"); + assert!(log[0][1].as_str().unwrap().contains("needs a File"), "{case}: {log}"); + } + } + let moved = |from: &str, to: &str| format!("(function () {{ var f = new File({from}); f.__vcPath = {to}; return f; }})()"); + for case in calls(&moved(&out, &x), &moved(&secret, &real)) { + let e = failure(&mut s, &base, &format!("Folder.userData; {case}")); + assert!(e.contains(DENIED), "{case}: {e}"); + } + assert!(!dir.join("x.svg").exists() && !dir.join("x.svg.svg").exists(), "nothing is written at the forged path"); + assert!(std::fs::read_dir(base.join("outside")).unwrap().count() == 1); + assert_eq!(s.documents().len(), 1, "nothing is opened"); + assert_eq!(s.active().unwrap().path, None); + let _ = std::fs::remove_dir_all(base); +} + +/// A document from an earlier run is stale, and saving it throws. +#[test] +fn a_stale_document_is_not_saved() { + let base = folder("stale"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + run(&mut s, &base, "#targetengine keep\nvar held = app.activeDocument;").unwrap(); + let e = failure(&mut s, &base, &format!("#targetengine keep\nFolder.userData; held.saveAs(new File({}));", quoted(&dir.join("x.svg")))); + assert!(e.contains("Stale document"), "{e}"); + assert!(!dir.join("x.svg").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// `open` applies the page and crop box of its options to a PDF. +#[test] +fn open_takes_the_page_and_crop_box_of_its_options() { + let base = folder("pdf"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + let pdf = dir.join("two.pdf"); + s.execute("file.saveAs", &json!({"path": pdf.to_string_lossy(), "format": "pdf"})).unwrap(); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var g = app.open(new File({}), DocumentColorSpace.CMYK, {{pageToOpen: 2, pDFCropToBox: PDFBoxType.PDFMEDIABOX}});\n\ + vc.log(g.documentColorSpace);", + quoted(&pdf) + ), + ); + assert_eq!(out, json!(["DocumentColorSpace.CMYK"])); + let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 3}});", quoted(&pdf))); + assert!(!e.is_empty(), "a page the file does not have"); + assert_eq!(s.documents().len(), 2); + assert_eq!(s.active().unwrap().doc.artboards.len(), 1, "one page"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index c962bf9679..e46fd9f77d 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -7,8 +7,10 @@ //! `File` and `new Folder(path)` always a `Folder`, while `File(path)` gives a `Folder` when the //! host's `stat` says the path is a folder, and `Folder(path)` a `File` when it is a file. Two //! objects for one path are different objects. An object keeps its path in the host's platform -//! form, its `error` text, the id of the file it has open (or -1), the encoding set before `open` -//! and its line feed, in properties that are not enumerable; every name the getters give comes from +//! form in an internal slot that only the classes' own methods set ([`Class::FsEntry`]), so an +//! object a script makes with `Object.create(File.prototype)` is not a `File`. It keeps its `error` +//! text, the id of the file it has open (or -1), the encoding set before `open` and its line feed +//! in properties that are not enumerable; every name the getters give comes from //! the host's `parse` of that path. `Folder.current` is kept in the realm and starts at the host's //! `current`. //! @@ -47,7 +49,57 @@ impl Classes { } } -const PATH: &str = "__vcPath"; +/// The one key of the [`crate::Data`] object that stands for a `File` given to a member of a host +/// class ([`crate::HostClass`]), with the file's path in the host's platform form as its value. A +/// plain object a script made that carries the key is refused. +pub const FILE_REF_KEY: &str = "\u{0}fileRef"; + +/// The path of the `File` that `d` stands for ([`FILE_REF_KEY`]). +pub fn file_ref_path(d: &crate::Data) -> Option<&str> { + let crate::Data::Object(items) = d else { return None }; + match items.as_slice() { + [(k, crate::Data::String(path))] if k == FILE_REF_KEY => Some(path), + _ => None, + } +} + +impl Interp { + /// The [`crate::Data`] for `id` when it is a `File` the `File` class made (its prototype is + /// `File.prototype` and it holds its path in its [`Class::FsEntry`]), as [`file_ref_path`] reads + /// it; `None` for any other object, one made with `Object.create(File.prototype)` included. + pub(crate) fn file_ref_of(&self, id: ObjId) -> JsResult> { + let Some(c) = &self.files else { return Ok(None) }; + let o = self.object(id)?; + if o.proto != Some(c.file_proto) { + return Ok(None); + } + Ok(match &o.class { + Class::FsEntry(s) => Some(crate::Data::Object(vec![(FILE_REF_KEY.to_string(), crate::Data::String(s.to_rust_string()))])), + _ => None, + }) + } +} + +/// The path of `o` when the `File` or `Folder` class made it. +fn own_path(i: &Interp, o: ObjId) -> JsResult> { + Ok(match &i.object(o)?.class { + Class::FsEntry(s) => Some(Value::String(s.clone())), + _ => None, + }) +} + +/// Sets the path of the `File` or `Folder` `o` to `fs`, a path the host gave. +fn set_path(i: &mut Interp, o: ObjId, fs: Value) -> JsResult<()> { + let Value::String(s) = fs else { return Err(i.type_error("File: the host gave no path")) }; + i.rooted(&[Value::Object(o), Value::String(s.clone())], |i| i.reserve_heap(string_bytes(s.len())))?; + if let Some(ob) = i.heap.object_mut(o) + && let Class::FsEntry(path) = &mut ob.class + { + *path = s; + } + Ok(()) +} + const ERROR: &str = "__vcError"; const HANDLE: &str = "__vcHandle"; const RUN: &str = "__vcRun"; @@ -103,7 +155,7 @@ fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> /// `Folder`. fn this_path(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, Value)> { if let Some(o) = this.as_object() - && let path @ Value::String(_) = slot(i, o, PATH)? + && let Some(path) = own_path(i, o)? { return Ok((o, path)); } @@ -114,7 +166,7 @@ fn this_path(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, Value /// `Folder`, or `String(x)`, which may hold URI escapes. fn path_text(i: &mut Interp, x: &Value) -> JsResult<(Value, bool)> { if let Some(o) = x.as_object() - && let path @ Value::String(_) = slot(i, o, PATH)? + && let Some(path) = own_path(i, o)? { return Ok((path, true)); } @@ -143,12 +195,12 @@ fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult JsResult { + let Value::String(path) = fs.clone() else { return Err(i.type_error("File: the host gave no path")) }; let line_feed = host_value(i, "lineFeed")?; - i.rooted(&[fs.clone(), line_feed.clone()], |i| { - i.reserve_heap(OBJECT_BYTES + 6 * PROP_BYTES)?; - let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + i.rooted(&[fs, line_feed.clone()], |i| { + i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES + string_bytes(path.len()))?; + let o = i.heap.alloc_object(Object::new(Class::FsEntry(path.clone()), Some(proto))); i.rooted(&[Value::Object(o)], |i| { - set_slot(i, o, PATH, fs.clone())?; set_slot(i, o, ERROR, Value::str(""))?; set_slot(i, o, HANDLE, Value::Number(-1.0))?; set_slot(i, o, RUN, Value::Number(-1.0))?; @@ -393,7 +445,7 @@ fn change_path(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult } let p = parse(i, &arg(args, 0))?; let fs = i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))?; - set_slot(i, o, PATH, fs)?; + set_path(i, o, fs)?; Ok(Value::Bool(true)) } @@ -482,7 +534,7 @@ fn rename(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult), /// An object of a class a host defined ([`crate::host_classes`]). Host(crate::host_classes::HostObj), + /// A `File` or `Folder` ([`crate::file_classes`]) and its path in the host's platform form, + /// which only the classes' own methods set. + FsEntry(Str), } /// What an XML value is. @@ -314,7 +317,7 @@ impl Class { Class::XmlFilter(_) => "Object", Class::Math => "Math", Class::Json => "JSON", - Class::Ordinary | Class::ForIn(_) | Class::Host(_) => "Object", + Class::Ordinary | Class::ForIn(_) | Class::Host(_) | Class::FsEntry(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", Class::Error(_) => "Error", @@ -648,7 +651,7 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u extra = BOUND_ARG_BYTES * args.len(); } Class::Arguments(map) => work.push(map.env.0), - Class::String(s) => strings.add(s), + Class::String(s) | Class::FsEntry(s) => strings.add(s), Class::RegExp(re) => { if strings.seen.insert(Rc::as_ptr(re) as *const () as usize) { strings.bytes += re.heap_bytes(); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index f34c9cff8e..a639dbd0cb 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -261,13 +261,21 @@ impl Interp { if r.ancestors.len() >= r.limits.depth { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } + // A `File` reads as its path ([`crate::FILE_REF_KEY`]). + if r.hosted + && let Some(file) = self.file_ref_of(id)? + { + let len = crate::file_ref_path(&file).map_or(0, str::len); + self.charge_reading(r, len.saturating_mul(3).saturating_add(2))?; + return Ok(file); + } let shape = match &self.object(id)?.class { Class::Host(_) if r.hosted => { return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())); } Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")), Class::Array { length, .. } => Shape::Array(*length), - Class::Ordinary => { + Class::Ordinary | Class::FsEntry(_) => { let o = self.object(id)?; if o.props.len() > r.limits.entries { return Err(self.data_error(r, ErrorType::Range, "has too many entries")); @@ -313,7 +321,7 @@ impl Interp { self.use_fuel()?; self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?; let name = String::from_utf16_lossy(&k); - if r.hosted && name == crate::HOST_REF_KEY { + if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY) { return Err(self.data_error(r, ErrorType::Type, "is not plain data")); } r.path.push(Step::Name(k)); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1d7af9e4fb..45f6aa61e4 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -81,6 +81,7 @@ pub use ast::{ }; pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; +pub use file_classes::{FILE_REF_KEY, file_ref_path}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..5e020a2116 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6607,6 +6607,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file could not be written No s’ha pogut escriure el fitxer de l’script @msg Script file dialogs need a person to answer them Els diàlegs de fitxers de l’script necessiten una persona que els respongui @msg Script file is not open for writing El fitxer de l’script no està obert per escriure-hi +@msg Script file is read-only El fitxer de l’script és només de lectura @msg Script file name is already in use El nom del fitxer de l’script ja està en ús @msg Script file name must be a name without a folder El nom del fitxer de l’script ha de ser un nom sense carpeta @msg Script file permission can be kept only for a script run from a file El permís de fitxers només es pot conservar per a un script executat des d’un fitxer diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..a0ae87170c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5392,6 +5392,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg Script file could not be written Soubor skriptu nelze zapsat @msg Script file dialogs need a person to answer them Dialogy souborů skriptu potřebují osobu, která na ně odpoví @msg Script file is not open for writing Soubor skriptu není otevřený pro zápis +@msg Script file is read-only Soubor skriptu je jen pro čtení @msg Script file name is already in use Název souboru skriptu se už používá @msg Script file name must be a name without a folder Název souboru skriptu musí být název bez složky @msg Script file permission can be kept only for a script run from a file Oprávnění k souborům lze zachovat jen pro skript spuštěný ze souboru diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..a068797076 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -87,6 +87,7 @@ @msg Script file could not be written Scriptfilen kunne ikke skrives @msg Script file dialogs need a person to answer them Scriptets fildialoger skal besvares af en person @msg Script file is not open for writing Scriptfilen er ikke åben for skrivning +@msg Script file is read-only Scriptfilen er skrivebeskyttet @msg Script file name is already in use Scriptfilens navn er allerede i brug @msg Script file name must be a name without a folder Scriptfilens navn skal være et navn uden en mappe @msg Script file permission can be kept only for a script run from a file Filtilladelsen kan kun beholdes for et script, der køres fra en fil diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..ad2653ea36 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4968,6 +4968,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg Script file could not be written Skriptdatei konnte nicht geschrieben werden @msg Script file dialogs need a person to answer them Dateidialoge von Skripten brauchen eine Person, die sie beantwortet @msg Script file is not open for writing Skriptdatei ist nicht zum Schreiben geöffnet +@msg Script file is read-only Skriptdatei ist schreibgeschützt @msg Script file name is already in use Name der Skriptdatei wird bereits verwendet @msg Script file name must be a name without a folder Name der Skriptdatei muss ein Name ohne Ordner sein @msg Script file permission can be kept only for a script run from a file Dateiberechtigung kann nur für ein Skript behalten werden, das aus einer Datei ausgeführt wird diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..3ead7c9a10 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2805,6 +2805,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg Script file could not be written Δεν ήταν δυνατή η εγγραφή του αρχείου του σεναρίου @msg Script file dialogs need a person to answer them Τα παράθυρα διαλόγου αρχείων του σεναρίου χρειάζονται ένα άτομο για να απαντήσει @msg Script file is not open for writing Το αρχείο του σεναρίου δεν είναι ανοιχτό για εγγραφή +@msg Script file is read-only Το αρχείο του σεναρίου είναι μόνο για ανάγνωση @msg Script file name is already in use Το όνομα του αρχείου του σεναρίου χρησιμοποιείται ήδη @msg Script file name must be a name without a folder Το όνομα του αρχείου του σεναρίου πρέπει να είναι όνομα χωρίς φάκελο @msg Script file permission can be kept only for a script run from a file Η άδεια αρχείων μπορεί να διατηρηθεί μόνο για σενάριο που εκτελείται από αρχείο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..8003e265c2 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5079,6 +5079,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg Script file could not be written No se pudo escribir el archivo del script @msg Script file dialogs need a person to answer them Los cuadros de diálogo de archivo del script necesitan que una persona los responda @msg Script file is not open for writing El archivo del script no está abierto para escritura +@msg Script file is read-only El archivo del script es de solo lectura @msg Script file name is already in use El nombre del archivo del script ya está en uso @msg Script file name must be a name without a folder El nombre del archivo del script debe ser un nombre sin carpeta @msg Script file permission can be kept only for a script run from a file El permiso de archivos solo se puede conservar para un script ejecutado desde un archivo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..d8933598d0 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5320,6 +5320,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg Script file could not be written Komentosarjan tiedostoa ei voitu kirjoittaa @msg Script file dialogs need a person to answer them Komentosarjan tiedostovalintaikkunoihin tarvitaan vastaava henkilö @msg Script file is not open for writing Komentosarjan tiedosto ei ole auki kirjoittamista varten +@msg Script file is read-only Komentosarjan tiedosto on vain luku -tilassa @msg Script file name is already in use Komentosarjan tiedoston nimi on jo käytössä @msg Script file name must be a name without a folder Komentosarjan tiedoston nimen on oltava nimi ilman kansiota @msg Script file permission can be kept only for a script run from a file Tiedostolupa voidaan säilyttää vain tiedostosta suoritetulle komentosarjalle diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..70e88ea0de 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5038,6 +5038,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg Script file could not be written Le fichier du script n’a pas pu être écrit @msg Script file dialogs need a person to answer them Les boîtes de dialogue de fichiers du script ont besoin d’une personne pour y répondre @msg Script file is not open for writing Le fichier du script n’est pas ouvert en écriture +@msg Script file is read-only Le fichier du script est en lecture seule @msg Script file name is already in use Le nom du fichier du script est déjà utilisé @msg Script file name must be a name without a folder Le nom du fichier du script doit être un nom sans dossier @msg Script file permission can be kept only for a script run from a file L’autorisation d’accès aux fichiers ne peut être conservée que pour un script exécuté depuis un fichier diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..d12d3d8a3b 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7754,6 +7754,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg Script file could not be written स्क्रिप्ट फ़ाइल लिखी नहीं जा सकी @msg Script file dialogs need a person to answer them स्क्रिप्ट के फ़ाइल डायलॉग को उत्तर देने के लिए किसी व्यक्ति की ज़रूरत है @msg Script file is not open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली नहीं है +@msg Script file is read-only स्क्रिप्ट फ़ाइल केवल पढ़ने के लिए है @msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है @msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए @msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..51a731132b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5910,6 +5910,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg Script file could not be written A parancsfájl fájlját nem sikerült írni @msg Script file dialogs need a person to answer them A parancsfájl fájlpárbeszédpaneleire egy személynek kell válaszolnia @msg Script file is not open for writing A parancsfájl fájlja nincs írásra megnyitva +@msg Script file is read-only A parancsfájl fájlja csak olvasható @msg Script file name is already in use A parancsfájl fájljának neve már használatban van @msg Script file name must be a name without a folder A parancsfájl fájljának neve mappa nélküli név kell legyen @msg Script file permission can be kept only for a script run from a file A fájlengedély csak fájlból futtatott parancsfájlnál tartható meg diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..7e041bfecb 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8748,6 +8748,7 @@ breakText Glyphs Glif @msg Script file could not be written File skrip tidak dapat ditulis @msg Script file dialogs need a person to answer them Dialog file skrip memerlukan orang untuk menjawabnya @msg Script file is not open for writing File skrip tidak dibuka untuk ditulis +@msg Script file is read-only File skrip hanya dapat dibaca @msg Script file name is already in use Nama file skrip sudah digunakan @msg Script file name must be a name without a folder Nama file skrip harus berupa nama tanpa folder @msg Script file permission can be kept only for a script run from a file Izin file skrip hanya dapat disimpan untuk skrip yang dijalankan dari file diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..cc67a9be3a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5106,6 +5106,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file could not be written Impossibile scrivere il file dello script @msg Script file dialogs need a person to answer them Le finestre di dialogo dei file dello script richiedono una persona che risponda @msg Script file is not open for writing Il file dello script non è aperto in scrittura +@msg Script file is read-only Il file dello script è di sola lettura @msg Script file name is already in use Il nome del file dello script è già in uso @msg Script file name must be a name without a folder Il nome del file dello script deve essere un nome senza cartella @msg Script file permission can be kept only for a script run from a file Il permesso sui file può essere mantenuto solo per uno script eseguito da un file diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..2bd2dad0b2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5941,6 +5941,7 @@ liquify-list-end {0}, {1} {0}、{1} @msg Script file could not be written スクリプトのファイルを書き込めませんでした @msg Script file dialogs need a person to answer them スクリプトのファイルダイアログには応答する人が必要です @msg Script file is not open for writing スクリプトのファイルが書き込み用に開かれていません +@msg Script file is read-only スクリプトのファイルは読み取り専用です @msg Script file name is already in use スクリプトのファイル名はすでに使用されています @msg Script file name must be a name without a folder スクリプトのファイル名はフォルダーを含まない名前にしてください @msg Script file permission can be kept only for a script run from a file ファイルの許可を保持できるのは、ファイルから実行したスクリプトだけです diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..6625e82912 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8602,6 +8602,7 @@ liquify-list-end {0}, {1} {0} და {1} @msg Script file could not be written სკრიპტის ფაილის ჩაწერა ვერ მოხერხდა @msg Script file dialogs need a person to answer them სკრიპტის ფაილის დიალოგებს სჭირდება ადამიანი, რომელიც უპასუხებს @msg Script file is not open for writing სკრიპტის ფაილი ჩასაწერად გახსნილი არ არის +@msg Script file is read-only სკრიპტის ფაილი მხოლოდ წასაკითხია @msg Script file name is already in use სკრიპტის ფაილის სახელი უკვე გამოიყენება @msg Script file name must be a name without a folder სკრიპტის ფაილის სახელი უნდა იყოს სახელი საქაღალდის გარეშე @msg Script file permission can be kept only for a script run from a file ფაილების ნებართვის შენახვა შესაძლებელია მხოლოდ ფაილიდან გაშვებული სკრიპტისთვის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..6cc76d1ef5 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5870,6 +5870,7 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg Script file could not be written 스크립트 파일을 쓸 수 없습니다 @msg Script file dialogs need a person to answer them 스크립트 파일 대화 상자에는 응답할 사람이 필요합니다 @msg Script file is not open for writing 스크립트 파일이 쓰기용으로 열려 있지 않습니다 +@msg Script file is read-only 스크립트 파일이 읽기 전용입니다 @msg Script file name is already in use 스크립트 파일 이름이 이미 사용 중입니다 @msg Script file name must be a name without a folder 스크립트 파일 이름은 폴더 없는 이름이어야 합니다 @msg Script file permission can be kept only for a script run from a file 파일 권한은 파일에서 실행한 스크립트에만 유지할 수 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..9cec4dc19c 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -89,6 +89,7 @@ @msg Script file could not be written Het scriptbestand kon niet worden geschreven @msg Script file dialogs need a person to answer them Dialoogvensters voor scriptbestanden moeten door een persoon worden beantwoord @msg Script file is not open for writing Het scriptbestand is niet geopend voor schrijven +@msg Script file is read-only Het scriptbestand is alleen-lezen @msg Script file name is already in use De naam van het scriptbestand is al in gebruik @msg Script file name must be a name without a folder De naam van het scriptbestand moet een naam zonder map zijn @msg Script file permission can be kept only for a script run from a file Toestemming voor scriptbestanden kan alleen worden bewaard voor een script dat vanuit een bestand wordt uitgevoerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..82f4003b2e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5211,6 +5211,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file could not be written Nie można zapisać pliku skryptu @msg Script file dialogs need a person to answer them Okna dialogowe plików skryptu wymagają osoby, która na nie odpowie @msg Script file is not open for writing Plik skryptu nie jest otwarty do zapisu +@msg Script file is read-only Plik skryptu jest tylko do odczytu @msg Script file name is already in use Nazwa pliku skryptu jest już używana @msg Script file name must be a name without a folder Nazwa pliku skryptu musi być nazwą bez folderu @msg Script file permission can be kept only for a script run from a file Uprawnienie do plików można zachować tylko dla skryptu uruchomionego z pliku diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..99e822eb99 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6250,6 +6250,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file could not be written Não foi possível gravar o arquivo do script @msg Script file dialogs need a person to answer them As caixas de diálogo de arquivo do script precisam de uma pessoa para respondê-las @msg Script file is not open for writing O arquivo do script não está aberto para gravação +@msg Script file is read-only O arquivo do script é somente leitura @msg Script file name is already in use O nome do arquivo do script já está em uso @msg Script file name must be a name without a folder O nome do arquivo do script deve ser um nome sem pasta @msg Script file permission can be kept only for a script run from a file A permissão de arquivos só pode ser mantida para um script executado a partir de um arquivo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..132428a948 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5101,6 +5101,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg Script file could not be written Не удалось записать файл скрипта @msg Script file dialogs need a person to answer them Для ответа на файловые диалоги скрипта нужен человек @msg Script file is not open for writing Файл скрипта не открыт для записи +@msg Script file is read-only Файл скрипта доступен только для чтения @msg Script file name is already in use Имя файла скрипта уже используется @msg Script file name must be a name without a folder Имя файла скрипта должно быть именем без папки @msg Script file permission can be kept only for a script run from a file Разрешение на файлы можно сохранить только для скрипта, запущенного из файла diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..3398eaf74f 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4977,6 +4977,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg Script file could not be written Skriptets fil kunde inte skrivas @msg Script file dialogs need a person to answer them Skriptets fildialoger behöver en person som svarar på dem @msg Script file is not open for writing Skriptets fil är inte öppen för skrivning +@msg Script file is read-only Skriptets fil är skrivskyddad @msg Script file name is already in use Namnet på skriptets fil används redan @msg Script file name must be a name without a folder Namnet på skriptets fil måste vara ett namn utan mapp @msg Script file permission can be kept only for a script run from a file Filbehörighet kan bara behållas för ett skript som körs från en fil diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..b70ea0e97e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4813,6 +4813,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg Script file could not be written Betiğin dosyası yazılamadı @msg Script file dialogs need a person to answer them Betiğin dosya iletişim kutularının yanıtlanması için bir kişi gerekir @msg Script file is not open for writing Betiğin dosyası yazmak için açık değil +@msg Script file is read-only Betiğin dosyası salt okunur @msg Script file name is already in use Betiğin dosya adı zaten kullanılıyor @msg Script file name must be a name without a folder Betiğin dosya adı klasör içermeyen bir ad olmalıdır @msg Script file permission can be kept only for a script run from a file Dosya izni yalnızca bir dosyadan çalıştırılan betik için saklanabilir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..9dabba9916 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5090,6 +5090,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg Script file could not be written Не вдалося записати файл скрипту @msg Script file dialogs need a person to answer them Для відповіді на файлові діалоги скрипту потрібна людина @msg Script file is not open for writing Файл скрипту не відкрито для запису +@msg Script file is read-only Файл скрипту доступний лише для читання @msg Script file name is already in use Ім’я файлу скрипту вже використовується @msg Script file name must be a name without a folder Ім’я файлу скрипту має бути іменем без папки @msg Script file permission can be kept only for a script run from a file Дозвіл на файли можна зберегти лише для скрипту, запущеного з файлу diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..cc9ec45896 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5600,6 +5600,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg Script file could not be written Không thể ghi tệp của tập lệnh @msg Script file dialogs need a person to answer them Hộp thoại tệp của tập lệnh cần một người trả lời @msg Script file is not open for writing Tệp của tập lệnh chưa được mở để ghi +@msg Script file is read-only Tệp của tập lệnh ở chế độ chỉ đọc @msg Script file name is already in use Tên tệp của tập lệnh đã được sử dụng @msg Script file name must be a name without a folder Tên tệp của tập lệnh phải là một tên không có thư mục @msg Script file permission can be kept only for a script run from a file Chỉ có thể giữ quyền truy cập tệp cho tập lệnh chạy từ một tệp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..11e409f42e 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5597,6 +5597,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file could not be written 无法写入脚本的文件 @msg Script file dialogs need a person to answer them 脚本的文件对话框需要有人回答 @msg Script file is not open for writing 脚本的文件未以写入方式打开 +@msg Script file is read-only 脚本的文件为只读 @msg Script file name is already in use 脚本的文件名已被使用 @msg Script file name must be a name without a folder 脚本的文件名必须是不含文件夹的名称 @msg Script file permission can be kept only for a script run from a file 只有从文件运行的脚本才能保留文件权限 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..287c85cfeb 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2952,6 +2952,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file could not be written 無法寫入指令碼的檔案 @msg Script file dialogs need a person to answer them 指令碼的檔案對話框需要有人回應 @msg Script file is not open for writing 指令碼的檔案未以寫入方式開啟 +@msg Script file is read-only 指令碼的檔案為唯讀 @msg Script file name is already in use 指令碼的檔案名稱已在使用中 @msg Script file name must be a name without a folder 指令碼的檔案名稱必須是不含資料夾的名稱 @msg Script file permission can be kept only for a script run from a file 只有從檔案執行的指令碼才能保留檔案權限 diff --git a/docs/mcp.md b/docs/mcp.md index 9bc2be8efc..3ead9da179 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2680,6 +2680,42 @@ app through the global object `vc`, and writes to the Script Console and runs ot `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. +- `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. + `Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is. + `app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document` + (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/). + `file` is a `File`. `new IllustratorSaveOptions()`, `new EPSSaveOptions()` and `new PDFSaveOptions()` pick the + format (https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, + https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/); + without options the path's extension picks it. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and + `exportFile` as `PNG24`, `JPEG` or `SVG` use the defaults a new options object of that class holds. `saveAs` maps `compressed`, `pdfCompatible`, `embedICCProfile` and + `compatibility` (`ILLUSTRATOR17` and `ILLUSTRATOR19`) of `.ai`; `cmykPostScript`, `includeDocumentThumbnails`, + `postScript`, `preview`, `overprint` and `compatibility` of EPS; and `pDFPreset`, `compatibility` (`ACROBAT4` to + `ACROBAT8` as PDF 1.3 to 1.7), `artboardRange`, `preserveEditability`, `acrobatLayers` and `compressArt` of PDF. + `exportType` is an `ExportType`: `PNG24`, `JPEG` and `SVG` take `new ExportOptionsPNG24()`, `new ExportOptionsJPEG()` + and `new ExportOptionsSVG()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, + https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/), + with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, more than 0 and at + most 776.19; 100 writes one pixel per point whatever the raster effects resolution), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and + `coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and + `includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s + `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with + `pageToOpen` and `pDFCropToBox`. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of + each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, + `EPSPostScriptLevelEnum`, `PDFOverprint` and `UserInteractionLevel` hold strings such as `"ExportType.PNG24"`. + VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the + command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open + document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is + read-only`; and the files a command reads or writes besides the one named, such as an SVG's linked files, are + read and written only where the script's folders allow. `userInteractionLevel` does not change what a command + does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the + format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with + `compressed`), and writes 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. A listed option that is not mapped is accepted at its help page's default, and any other value throws + an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`; properties the help + pages do not list are left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default + keeps the preset's value. A bad value throws an error before anything is written. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..0f5208319d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,6 +1025,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: 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`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents 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/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.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 d14830b6b7f1060c9f0eceb9dc3cbe83c3d601a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:23:24 -0800 Subject: [PATCH 05/69] Scripts: saveAs and exportFile refuse a file open for writing and scales under 1% A save or export to a file that a File object holds open for writing throws "Script file is open for writing", and a command the script runs does not write such a file besides the one named (an SVG's images), so the bytes the File writes at the end of the run do not replace the output. horizontalScale and verticalScale take 1 to 776.19, since a raster export writes at least 0.01 pixels per point. The script checker reports a document's saveAs and exportFile as file writes, and the host name check lists the save, export and open names, option classes and enumerations. --- crates/engine/src/file_access.rs | 26 ++++++-- crates/engine/src/script/dom/save_open.rs | 7 +- crates/engine/src/script/files.rs | 14 ++-- crates/engine/src/tests/script_save_open.rs | 66 ++++++++++++++++++- .../tests/it/script_host_vs_scriptcheck.rs | 29 ++++++-- crates/scriptcheck/src/analyze/features.rs | 12 +++- crates/scriptcheck/src/catalog.rs | 3 + crates/scriptcheck/src/tests.rs | 28 ++++++++ crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 11 ++-- 34 files changed, 198 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 4769146ad8..afab0e95b0 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -284,6 +284,9 @@ pub(crate) struct ScriptGate { pub(crate) write: ScriptScope, /// The paths of the open documents' files, as the documents hold them. pub(crate) documents: Vec, + /// The real paths of the files the script's `File` objects hold open for writing, which a + /// command does not write: the run's end would write the objects' bytes over them. + pub(crate) held: Vec, /// Another gate a path must pass as well ([`ScopeHandle::within_current`]). pub(crate) also: Option>, } @@ -312,7 +315,8 @@ impl ScriptGate { }; // A read-only file is not written over, also where a rename could replace it. let read_only = matches!(access, Access::Write) && std::fs::metadata(&real).is_ok_and(|m| m.is_file() && m.permissions().readonly()); - !read_only && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real))) + let held = matches!(access, Access::Write) && self.held.contains(&real); + !read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real))) }); if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } } @@ -920,8 +924,13 @@ mod tests { #[test] fn a_narrowed_scope_keeps_the_script_gates_of_both() { let (base, _) = folders("narrowed-gate"); - let gate = - |dir: &str| ScriptGate { read: ScriptScope::of_folder(&base.join(dir)), write: ScriptScope::default(), documents: vec![], also: None }; + let gate = |dir: &str| ScriptGate { + read: ScriptScope::of_folder(&base.join(dir)), + write: ScriptScope::default(), + documents: vec![], + held: vec![], + also: None, + }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); let reads = |saved: ScopeHandle, gate_here: Option| { let narrowed = match gate_here { @@ -944,7 +953,8 @@ mod tests { #[test] fn a_scope_narrowed_several_times_keeps_every_gate() { let (base, _) = folders("narrowed-thrice"); - let gate = |dir: &Path| ScriptGate { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], also: None }; + let gate = + |dir: &Path| ScriptGate { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], held: vec![], also: None }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); let narrow = |saved: ScopeHandle, g: ScriptGate| with_script_gate(g, || saved.within_current()); let reads = |h: &ScopeHandle| h.clone().run(|| (check_read(&inside).is_ok(), check_read(&other).is_ok())); @@ -964,7 +974,13 @@ mod tests { let (base, _) = folders("gate-read-only"); let out = base.join("out/kept.svg"); std::fs::write(&out, "").unwrap(); - let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::of_folder(&base.join("out")), documents: vec![], also: None }; + let gate = ScriptGate { + read: ScriptScope::default(), + write: ScriptScope::of_folder(&base.join("out")), + documents: vec![], + held: vec![], + also: None, + }; let (kept, fresh) = (s(out.clone()), s(base.join("out/new.svg"))); let check = |p: &str| with_script_gate(gate.clone(), || (check_write(p).is_ok(), check_read(p).is_ok())); assert_eq!(check(&kept), (true, true)); diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index ebdebc4c10..c76ae0f44e 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -48,6 +48,9 @@ use super::{ /// The most a scale factor of an export takes, in percent. pub const MAX_SCALE_PERCENT: f64 = 776.19; +/// The least a scale factor of a raster export takes, in percent: `document.export` writes at least +/// 0.01 pixels per point. +pub const MIN_SCALE_PERCENT: f64 = 1.0; /// What the run keeps for these members: whether `userInteractionLevel` is `DONTDISPLAYALERTS`. #[derive(Default)] @@ -363,8 +366,8 @@ fn raster_map(class: &str, name: &str, d: &Data, p: &mut Map) -> Data::Number(n) if n.is_finite() => *n, _ => return Err(HostError::Type(format!("{what} must be a finite number"))), }; - if n <= 0.0 || n > MAX_SCALE_PERCENT { - return Err(HostError::Range(format!("{what} must be more than 0 and at most 776.19"))); + if !(MIN_SCALE_PERCENT..=MAX_SCALE_PERCENT).contains(&n) { + return Err(HostError::Range(format!("{what} must be at least 1 and at most 776.19"))); } let key = if name == "horizontalScale" { "_h" } else { "_v" }; p.insert(key.into(), json!(n)); diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 40b1fe0465..7886210567 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -116,6 +116,7 @@ pub(crate) const NOT_WRITABLE: &str = "Script file is not open for writing"; pub(crate) const UNENCODABLE: &str = "Script file cannot encode the text"; pub(crate) const WRITE_FAILED: &str = "Script file could not be written"; pub(crate) const READ_ONLY: &str = "Script file is read-only"; +pub(crate) const OPEN_FOR_WRITING: &str = "Script file is open for writing"; pub(crate) const NOT_EMPTY: &str = "Script folder is not empty"; pub(crate) const NAME_TAKEN: &str = "Script file name is already in use"; pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder"; @@ -460,11 +461,12 @@ impl Disk { } /// The gate for a command the script runs: the places it reads and writes now, and the files of - /// the open documents, `documents`. + /// the open documents, `documents`, but not the files its `File` objects hold open for writing. pub(crate) fn gate(&self, documents: Vec) -> crate::file_access::ScriptGate { // A save, export or open of a `File` the script names reads and writes as its `File` would. let documents = if self.exact { Vec::new() } else { documents }; - crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, also: None } + let held = self.open.values().filter_map(|o| o.target.clone()).collect(); + crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, held, also: None } } /// The files written since this was last asked, to name in the report. @@ -684,10 +686,14 @@ impl Disk { } /// The real path a save or export of the document to `path` writes, as a `File` opened for - /// writing would write it ([`Disk::target`]), or why it may not: a folder is not a file, and a - /// read-only file is not written over. + /// writing would write it ([`Disk::target`]), or why it may not: a folder is not a file, a + /// read-only file is not written over, and neither is a file a `File` object holds open for + /// writing, whose bytes the run's end would write over the saved file. pub(crate) fn save_target(&self, path: &str) -> Result { let real = self.target(path, true)?; + if self.open.values().any(|o| o.target.as_deref() == Some(real.as_path())) { + return Err(OPEN_FOR_WRITING); + } match std::fs::metadata(&real) { Ok(m) if !m.is_file() => Err(NOT_REGULAR), Ok(m) if m.permissions().readonly() => Err(READ_ONLY), diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 809fed0ef8..8518f14365 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -271,6 +271,32 @@ fn an_open_documents_file_is_not_saved_over_without_a_grant() { let _ = std::fs::remove_dir_all(base); } +/// A save or export to a file a `File` object holds open for writing throws, so the object's bytes +/// written at the end of the run do not replace the saved document. +#[test] +fn a_file_open_for_writing_is_not_saved_over() { + let base = folder("openhandle"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for (name, call) in + [("a.svg", "app.activeDocument.saveAs(new File(p));"), ("b.png", "app.activeDocument.exportFile(new File(p), ExportType.PNG24);")] + { + let p = quoted(&dir.join(name)); + let log = logged( + &mut s, + &base, + &format!( + "Folder.userData; var p = {p}, w = new File(p); w.open('w'); w.write('pending');\ntry {{ {call} vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}" + ), + ); + assert!(log[0].as_str().unwrap().contains(crate::script::files::OPEN_FOR_WRITING), "{name}: {log}"); + assert_eq!(std::fs::read_to_string(dir.join(name)).unwrap(), "pending", "{name}: the File's own bytes"); + assert_eq!(s.active().unwrap().path, None, "{name}: the document's file is unchanged"); + } + let _ = std::fs::remove_dir_all(base); +} + /// A file `open` reads besides the one it names, here an SVG's linked image, is read only where /// the script's grants allow, though it is an open document's file. #[test] @@ -282,7 +308,7 @@ fn open_reads_linked_files_only_where_the_script_may() { std::fs::write(&linked, "").unwrap(); s.execute("document.open", &json!({"path": linked.to_string_lossy()})).unwrap(); assert!(s.active().unwrap().path.is_some(), "the linked file is an open document's file"); - let href = linked.to_string_lossy().replace('\\', "/"); + let href = linked.to_string_lossy().replace('\\', "/").replace('&', "&").replace('<', "<").replace('\'', "'"); std::fs::write( dir.join("page.svg"), format!(""), @@ -343,6 +369,38 @@ fn an_svg_export_writes_nothing_when_one_of_its_files_is_refused() { let _ = std::fs::remove_dir_all(base); } +/// An export does not write a file it writes besides the one named, here an SVG's image, while a +/// `File` object holds it open for writing, and so writes nothing. +#[test] +fn an_svg_export_does_not_write_an_image_a_file_holds_open() { + let base = folder("svgheld"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let pic = base.join("outside/pic.png"); + std::fs::write(&pic, super::links::png(2, 2, [10, 200, 30])).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": false})).unwrap(); + let svg = dir.join("a.svg"); + let export = format!("app.activeDocument.exportFile(new File({}), ExportType.SVG, new ExportOptionsSVG());", quoted(&svg)); + logged(&mut s, &base, &format!("Folder.userData; {export}")); + let mut images: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != svg).collect(); + assert_eq!(images.len(), 1, "the embedded image is written beside the SVG: {images:?}"); + let image = images.remove(0); + std::fs::remove_file(&svg).unwrap(); + let log = logged( + &mut s, + &base, + &format!( + "Folder.userData; var w = new File({}); w.open('w'); w.write('pending');\ntry {{ {export} vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}", + quoted(&image) + ), + ); + assert!(log[0].as_str().unwrap().contains(DENIED), "{log}"); + assert!(!svg.exists(), "the SVG is not written when its image may not be"); + assert_eq!(std::fs::read_to_string(&image).unwrap(), "pending", "the File's own bytes"); + let _ = std::fs::remove_dir_all(base); +} + /// A link inside a granted folder that leads out of it is followed and refused. #[cfg(unix)] #[test] @@ -404,6 +462,12 @@ fn bad_arguments_are_refused_with_an_error() { ), "at most", ), + ( + format!( + "var p = new ExportOptionsPNG24(); p.horizontalScale = p.verticalScale = 0.5; app.activeDocument.exportFile({f}, ExportType.PNG24, p);" + ), + "at least 1", + ), ( format!("var p = new ExportOptionsPNG24(); p.horizontalScale = 50; app.activeDocument.exportFile({f}, ExportType.PNG24, p);"), "not available yet", diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ef7c97e951..26b476a0b6 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -37,12 +37,14 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"), ("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"), ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), + ("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"), + ("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"), ]; /// 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.close` throws "not available yet". `app.open` reads the file it is given. const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), @@ -81,7 +83,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + open selection typename userInteractionLevel userInteractionLevel=", ), ("Documents.", "prototype"), ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), @@ -90,7 +92,7 @@ const INSIDE: &[(&str, &str)] = &[ "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ + rulerUnits selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ views views= width", ), ("Layer.", "prototype"), @@ -121,12 +123,27 @@ const INSIDE: &[(&str, &str)] = &[ ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), + // The enumerations of saving, exporting and opening. + ("", "Compatibility EPSPostScriptLevelEnum EPSPreview ExportType PDFBoxType PDFCompatibility PDFOverprint UserInteractionLevel"), + ( + "Compatibility.", + "ILLUSTRATOR10 ILLUSTRATOR11 ILLUSTRATOR12 ILLUSTRATOR13 ILLUSTRATOR14 ILLUSTRATOR15 ILLUSTRATOR16 ILLUSTRATOR17 \ + ILLUSTRATOR19 ILLUSTRATOR8 ILLUSTRATOR9 JAPANESEVERSION3", + ), + ("EPSPostScriptLevelEnum.", "LEVEL2 LEVEL3"), + ("EPSPreview.", "BWTIFF COLORTIFF None TRANSPARENTCOLORTIFF"), + ("ExportType.", "AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"), + ("PDFBoxType.", "PDFARTBOX PDFBLEEDBOX PDFBOUNDINGBOX PDFCROPBOX PDFMEDIABOX PDFTRIMBOX"), + ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), + ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), + ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), ]; -/// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset` -/// and the page item types. +/// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset`, +/// the page item types and the save and export option classes. const BARE_CLASSES: &str = "BlendItem CompoundPathItem DocumentPreset EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ - PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; + PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 \ + ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 7bf8c9d203..354a0540aa 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -287,6 +287,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `(` after a name: a call. fn call(&mut self, line: Option) { let [h0, h1, h2, h3] = self.h; + // `doc['saveAs'](f)`: a document method named by a string literal in brackets. + if is(h0, "]") + && is(h2, "[") + && let Some(name) = h1.filter(|s| s.kind == T::Str) + && catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str()) + { + self.acc.feature(FeatureId::FileWrite, line); + self.acc.outside(OutsideId::FilesWritten, line, None); + return; + } let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return }; let n = callee.text; if is(h1, ".") { @@ -301,7 +311,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.acc.feature(FeatureId::FileDialog, line); } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { self.acc.feature(FeatureId::FileRead, line); - } else if file && catalog::FILE_WRITES.contains(&n) { + } else if (file && catalog::FILE_WRITES.contains(&n)) || catalog::DOM_FILE_WRITES.contains(&n) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); } else if n == catalog::EXECUTE { diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 6f25fe6df3..ee5b63dfb2 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -72,6 +72,9 @@ pub(crate) const REFLECT: &str = "reflect"; // The roots of the document model: https://ai-scripting.docsforadobe.dev/jsobjref/Application/ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"]; +// Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ +pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "saveAs"]; + // Application methods that page doesn't list, named in public forum posts: // https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand, // doScript, loadAction, unloadAction) and diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index cf71cefc0f..12e5527811 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -530,6 +530,34 @@ fn the_scripts_own_platform_names_are_not_the_platforms() { assert_eq!(r.outside.iter().map(|o| o.id).collect::>(), ["filesWritten"]); } +/// A document's `saveAs` and `exportFile` write the file they are given; `app.open` only reads one. +#[test] +fn save_as_and_export_file_write_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var d = app.open(f);\n", + "d.saveAs(f);\n", + "app.activeDocument.exportFile(f, ExportType.PNG24);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); +} + +/// `saveAs` and `exportFile` called with their names as string literals in brackets write the file +/// too; reading the method without calling it does not. +#[test] +fn save_as_and_export_file_in_brackets_write_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "app.activeDocument['open'](f);\n", + "app.activeDocument[\"saveAs\"](f);\n", + "var d = app.activeDocument; d['exportFile'] (f, ExportType.SVG);\n", + "var n = d['saveAs'];\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 5e020a2116..4cb24ffa76 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6608,6 +6608,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file dialogs need a person to answer them Els diàlegs de fitxers de l’script necessiten una persona que els respongui @msg Script file is not open for writing El fitxer de l’script no està obert per escriure-hi @msg Script file is read-only El fitxer de l’script és només de lectura +@msg Script file is open for writing El fitxer de l’script està obert per escriure-hi @msg Script file name is already in use El nom del fitxer de l’script ja està en ús @msg Script file name must be a name without a folder El nom del fitxer de l’script ha de ser un nom sense carpeta @msg Script file permission can be kept only for a script run from a file El permís de fitxers només es pot conservar per a un script executat des d’un fitxer diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a0ae87170c..4ac10d6ac7 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5393,6 +5393,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg Script file dialogs need a person to answer them Dialogy souborů skriptu potřebují osobu, která na ně odpoví @msg Script file is not open for writing Soubor skriptu není otevřený pro zápis @msg Script file is read-only Soubor skriptu je jen pro čtení +@msg Script file is open for writing Soubor skriptu je otevřený pro zápis @msg Script file name is already in use Název souboru skriptu se už používá @msg Script file name must be a name without a folder Název souboru skriptu musí být název bez složky @msg Script file permission can be kept only for a script run from a file Oprávnění k souborům lze zachovat jen pro skript spuštěný ze souboru diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index a068797076..5aab6605f6 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -88,6 +88,7 @@ @msg Script file dialogs need a person to answer them Scriptets fildialoger skal besvares af en person @msg Script file is not open for writing Scriptfilen er ikke åben for skrivning @msg Script file is read-only Scriptfilen er skrivebeskyttet +@msg Script file is open for writing Scriptfilen er åben for skrivning @msg Script file name is already in use Scriptfilens navn er allerede i brug @msg Script file name must be a name without a folder Scriptfilens navn skal være et navn uden en mappe @msg Script file permission can be kept only for a script run from a file Filtilladelsen kan kun beholdes for et script, der køres fra en fil diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index ad2653ea36..a0872671f8 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4969,6 +4969,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg Script file dialogs need a person to answer them Dateidialoge von Skripten brauchen eine Person, die sie beantwortet @msg Script file is not open for writing Skriptdatei ist nicht zum Schreiben geöffnet @msg Script file is read-only Skriptdatei ist schreibgeschützt +@msg Script file is open for writing Skriptdatei ist zum Schreiben geöffnet @msg Script file name is already in use Name der Skriptdatei wird bereits verwendet @msg Script file name must be a name without a folder Name der Skriptdatei muss ein Name ohne Ordner sein @msg Script file permission can be kept only for a script run from a file Dateiberechtigung kann nur für ein Skript behalten werden, das aus einer Datei ausgeführt wird diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 3ead7c9a10..db00e18a27 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2806,6 +2806,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg Script file dialogs need a person to answer them Τα παράθυρα διαλόγου αρχείων του σεναρίου χρειάζονται ένα άτομο για να απαντήσει @msg Script file is not open for writing Το αρχείο του σεναρίου δεν είναι ανοιχτό για εγγραφή @msg Script file is read-only Το αρχείο του σεναρίου είναι μόνο για ανάγνωση +@msg Script file is open for writing Το αρχείο του σεναρίου είναι ανοιχτό για εγγραφή @msg Script file name is already in use Το όνομα του αρχείου του σεναρίου χρησιμοποιείται ήδη @msg Script file name must be a name without a folder Το όνομα του αρχείου του σεναρίου πρέπει να είναι όνομα χωρίς φάκελο @msg Script file permission can be kept only for a script run from a file Η άδεια αρχείων μπορεί να διατηρηθεί μόνο για σενάριο που εκτελείται από αρχείο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 8003e265c2..28dd4a176c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5080,6 +5080,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg Script file dialogs need a person to answer them Los cuadros de diálogo de archivo del script necesitan que una persona los responda @msg Script file is not open for writing El archivo del script no está abierto para escritura @msg Script file is read-only El archivo del script es de solo lectura +@msg Script file is open for writing El archivo del script está abierto para escritura @msg Script file name is already in use El nombre del archivo del script ya está en uso @msg Script file name must be a name without a folder El nombre del archivo del script debe ser un nombre sin carpeta @msg Script file permission can be kept only for a script run from a file El permiso de archivos solo se puede conservar para un script ejecutado desde un archivo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d8933598d0..a56f4feca6 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5321,6 +5321,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg Script file dialogs need a person to answer them Komentosarjan tiedostovalintaikkunoihin tarvitaan vastaava henkilö @msg Script file is not open for writing Komentosarjan tiedosto ei ole auki kirjoittamista varten @msg Script file is read-only Komentosarjan tiedosto on vain luku -tilassa +@msg Script file is open for writing Komentosarjan tiedosto on auki kirjoittamista varten @msg Script file name is already in use Komentosarjan tiedoston nimi on jo käytössä @msg Script file name must be a name without a folder Komentosarjan tiedoston nimen on oltava nimi ilman kansiota @msg Script file permission can be kept only for a script run from a file Tiedostolupa voidaan säilyttää vain tiedostosta suoritetulle komentosarjalle diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 70e88ea0de..52ce992d66 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5039,6 +5039,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg Script file dialogs need a person to answer them Les boîtes de dialogue de fichiers du script ont besoin d’une personne pour y répondre @msg Script file is not open for writing Le fichier du script n’est pas ouvert en écriture @msg Script file is read-only Le fichier du script est en lecture seule +@msg Script file is open for writing Le fichier du script est ouvert en écriture @msg Script file name is already in use Le nom du fichier du script est déjà utilisé @msg Script file name must be a name without a folder Le nom du fichier du script doit être un nom sans dossier @msg Script file permission can be kept only for a script run from a file L’autorisation d’accès aux fichiers ne peut être conservée que pour un script exécuté depuis un fichier diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index d12d3d8a3b..111037fda0 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7755,6 +7755,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg Script file dialogs need a person to answer them स्क्रिप्ट के फ़ाइल डायलॉग को उत्तर देने के लिए किसी व्यक्ति की ज़रूरत है @msg Script file is not open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली नहीं है @msg Script file is read-only स्क्रिप्ट फ़ाइल केवल पढ़ने के लिए है +@msg Script file is open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली है @msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है @msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए @msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 51a731132b..78093bf132 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5911,6 +5911,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg Script file dialogs need a person to answer them A parancsfájl fájlpárbeszédpaneleire egy személynek kell válaszolnia @msg Script file is not open for writing A parancsfájl fájlja nincs írásra megnyitva @msg Script file is read-only A parancsfájl fájlja csak olvasható +@msg Script file is open for writing A parancsfájl fájlja írásra meg van nyitva @msg Script file name is already in use A parancsfájl fájljának neve már használatban van @msg Script file name must be a name without a folder A parancsfájl fájljának neve mappa nélküli név kell legyen @msg Script file permission can be kept only for a script run from a file A fájlengedély csak fájlból futtatott parancsfájlnál tartható meg diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 7e041bfecb..5badf608d7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8749,6 +8749,7 @@ breakText Glyphs Glif @msg Script file dialogs need a person to answer them Dialog file skrip memerlukan orang untuk menjawabnya @msg Script file is not open for writing File skrip tidak dibuka untuk ditulis @msg Script file is read-only File skrip hanya dapat dibaca +@msg Script file is open for writing File skrip sedang dibuka untuk ditulis @msg Script file name is already in use Nama file skrip sudah digunakan @msg Script file name must be a name without a folder Nama file skrip harus berupa nama tanpa folder @msg Script file permission can be kept only for a script run from a file Izin file skrip hanya dapat disimpan untuk skrip yang dijalankan dari file diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index cc67a9be3a..9b6018956e 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5107,6 +5107,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file dialogs need a person to answer them Le finestre di dialogo dei file dello script richiedono una persona che risponda @msg Script file is not open for writing Il file dello script non è aperto in scrittura @msg Script file is read-only Il file dello script è di sola lettura +@msg Script file is open for writing Il file dello script è aperto in scrittura @msg Script file name is already in use Il nome del file dello script è già in uso @msg Script file name must be a name without a folder Il nome del file dello script deve essere un nome senza cartella @msg Script file permission can be kept only for a script run from a file Il permesso sui file può essere mantenuto solo per uno script eseguito da un file diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 2bd2dad0b2..348f7aa3f3 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5942,6 +5942,7 @@ liquify-list-end {0}, {1} {0}、{1} @msg Script file dialogs need a person to answer them スクリプトのファイルダイアログには応答する人が必要です @msg Script file is not open for writing スクリプトのファイルが書き込み用に開かれていません @msg Script file is read-only スクリプトのファイルは読み取り専用です +@msg Script file is open for writing スクリプトのファイルが書き込み用に開かれています @msg Script file name is already in use スクリプトのファイル名はすでに使用されています @msg Script file name must be a name without a folder スクリプトのファイル名はフォルダーを含まない名前にしてください @msg Script file permission can be kept only for a script run from a file ファイルの許可を保持できるのは、ファイルから実行したスクリプトだけです diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 6625e82912..50a7c83e6d 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8603,6 +8603,7 @@ liquify-list-end {0}, {1} {0} და {1} @msg Script file dialogs need a person to answer them სკრიპტის ფაილის დიალოგებს სჭირდება ადამიანი, რომელიც უპასუხებს @msg Script file is not open for writing სკრიპტის ფაილი ჩასაწერად გახსნილი არ არის @msg Script file is read-only სკრიპტის ფაილი მხოლოდ წასაკითხია +@msg Script file is open for writing სკრიპტის ფაილი ჩასაწერად გახსნილია @msg Script file name is already in use სკრიპტის ფაილის სახელი უკვე გამოიყენება @msg Script file name must be a name without a folder სკრიპტის ფაილის სახელი უნდა იყოს სახელი საქაღალდის გარეშე @msg Script file permission can be kept only for a script run from a file ფაილების ნებართვის შენახვა შესაძლებელია მხოლოდ ფაილიდან გაშვებული სკრიპტისთვის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 6cc76d1ef5..0db12b4e59 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5871,6 +5871,7 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg Script file dialogs need a person to answer them 스크립트 파일 대화 상자에는 응답할 사람이 필요합니다 @msg Script file is not open for writing 스크립트 파일이 쓰기용으로 열려 있지 않습니다 @msg Script file is read-only 스크립트 파일이 읽기 전용입니다 +@msg Script file is open for writing 스크립트 파일이 쓰기용으로 열려 있습니다 @msg Script file name is already in use 스크립트 파일 이름이 이미 사용 중입니다 @msg Script file name must be a name without a folder 스크립트 파일 이름은 폴더 없는 이름이어야 합니다 @msg Script file permission can be kept only for a script run from a file 파일 권한은 파일에서 실행한 스크립트에만 유지할 수 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 9cec4dc19c..929dc790fe 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -90,6 +90,7 @@ @msg Script file dialogs need a person to answer them Dialoogvensters voor scriptbestanden moeten door een persoon worden beantwoord @msg Script file is not open for writing Het scriptbestand is niet geopend voor schrijven @msg Script file is read-only Het scriptbestand is alleen-lezen +@msg Script file is open for writing Het scriptbestand is geopend voor schrijven @msg Script file name is already in use De naam van het scriptbestand is al in gebruik @msg Script file name must be a name without a folder De naam van het scriptbestand moet een naam zonder map zijn @msg Script file permission can be kept only for a script run from a file Toestemming voor scriptbestanden kan alleen worden bewaard voor een script dat vanuit een bestand wordt uitgevoerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 82f4003b2e..1f14688dd1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5212,6 +5212,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file dialogs need a person to answer them Okna dialogowe plików skryptu wymagają osoby, która na nie odpowie @msg Script file is not open for writing Plik skryptu nie jest otwarty do zapisu @msg Script file is read-only Plik skryptu jest tylko do odczytu +@msg Script file is open for writing Plik skryptu jest otwarty do zapisu @msg Script file name is already in use Nazwa pliku skryptu jest już używana @msg Script file name must be a name without a folder Nazwa pliku skryptu musi być nazwą bez folderu @msg Script file permission can be kept only for a script run from a file Uprawnienie do plików można zachować tylko dla skryptu uruchomionego z pliku diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 99e822eb99..a70f1c64a6 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6251,6 +6251,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file dialogs need a person to answer them As caixas de diálogo de arquivo do script precisam de uma pessoa para respondê-las @msg Script file is not open for writing O arquivo do script não está aberto para gravação @msg Script file is read-only O arquivo do script é somente leitura +@msg Script file is open for writing O arquivo do script está aberto para gravação @msg Script file name is already in use O nome do arquivo do script já está em uso @msg Script file name must be a name without a folder O nome do arquivo do script deve ser um nome sem pasta @msg Script file permission can be kept only for a script run from a file A permissão de arquivos só pode ser mantida para um script executado a partir de um arquivo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 132428a948..1ffaea5dab 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5102,6 +5102,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg Script file dialogs need a person to answer them Для ответа на файловые диалоги скрипта нужен человек @msg Script file is not open for writing Файл скрипта не открыт для записи @msg Script file is read-only Файл скрипта доступен только для чтения +@msg Script file is open for writing Файл скрипта открыт для записи @msg Script file name is already in use Имя файла скрипта уже используется @msg Script file name must be a name without a folder Имя файла скрипта должно быть именем без папки @msg Script file permission can be kept only for a script run from a file Разрешение на файлы можно сохранить только для скрипта, запущенного из файла diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 3398eaf74f..efb575f716 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4978,6 +4978,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg Script file dialogs need a person to answer them Skriptets fildialoger behöver en person som svarar på dem @msg Script file is not open for writing Skriptets fil är inte öppen för skrivning @msg Script file is read-only Skriptets fil är skrivskyddad +@msg Script file is open for writing Skriptets fil är öppen för skrivning @msg Script file name is already in use Namnet på skriptets fil används redan @msg Script file name must be a name without a folder Namnet på skriptets fil måste vara ett namn utan mapp @msg Script file permission can be kept only for a script run from a file Filbehörighet kan bara behållas för ett skript som körs från en fil diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index b70ea0e97e..e353434aaa 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4814,6 +4814,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg Script file dialogs need a person to answer them Betiğin dosya iletişim kutularının yanıtlanması için bir kişi gerekir @msg Script file is not open for writing Betiğin dosyası yazmak için açık değil @msg Script file is read-only Betiğin dosyası salt okunur +@msg Script file is open for writing Betiğin dosyası yazmak için açık @msg Script file name is already in use Betiğin dosya adı zaten kullanılıyor @msg Script file name must be a name without a folder Betiğin dosya adı klasör içermeyen bir ad olmalıdır @msg Script file permission can be kept only for a script run from a file Dosya izni yalnızca bir dosyadan çalıştırılan betik için saklanabilir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 9dabba9916..7e3b137acc 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5091,6 +5091,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg Script file dialogs need a person to answer them Для відповіді на файлові діалоги скрипту потрібна людина @msg Script file is not open for writing Файл скрипту не відкрито для запису @msg Script file is read-only Файл скрипту доступний лише для читання +@msg Script file is open for writing Файл скрипту відкрито для запису @msg Script file name is already in use Ім’я файлу скрипту вже використовується @msg Script file name must be a name without a folder Ім’я файлу скрипту має бути іменем без папки @msg Script file permission can be kept only for a script run from a file Дозвіл на файли можна зберегти лише для скрипту, запущеного з файлу diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index cc9ec45896..9af45922ab 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5601,6 +5601,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg Script file dialogs need a person to answer them Hộp thoại tệp của tập lệnh cần một người trả lời @msg Script file is not open for writing Tệp của tập lệnh chưa được mở để ghi @msg Script file is read-only Tệp của tập lệnh ở chế độ chỉ đọc +@msg Script file is open for writing Tệp của tập lệnh đang được mở để ghi @msg Script file name is already in use Tên tệp của tập lệnh đã được sử dụng @msg Script file name must be a name without a folder Tên tệp của tập lệnh phải là một tên không có thư mục @msg Script file permission can be kept only for a script run from a file Chỉ có thể giữ quyền truy cập tệp cho tập lệnh chạy từ một tệp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 11e409f42e..dc6577be86 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5598,6 +5598,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file dialogs need a person to answer them 脚本的文件对话框需要有人回答 @msg Script file is not open for writing 脚本的文件未以写入方式打开 @msg Script file is read-only 脚本的文件为只读 +@msg Script file is open for writing 脚本的文件已以写入方式打开 @msg Script file name is already in use 脚本的文件名已被使用 @msg Script file name must be a name without a folder 脚本的文件名必须是不含文件夹的名称 @msg Script file permission can be kept only for a script run from a file 只有从文件运行的脚本才能保留文件权限 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 287c85cfeb..a97d0185e1 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2953,6 +2953,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file dialogs need a person to answer them 指令碼的檔案對話框需要有人回應 @msg Script file is not open for writing 指令碼的檔案未以寫入方式開啟 @msg Script file is read-only 指令碼的檔案為唯讀 +@msg Script file is open for writing 指令碼的檔案已以寫入方式開啟 @msg Script file name is already in use 指令碼的檔案名稱已在使用中 @msg Script file name must be a name without a folder 指令碼的檔案名稱必須是不含資料夾的名稱 @msg Script file permission can be kept only for a script run from a file 只有從檔案執行的指令碼才能保留檔案權限 diff --git a/docs/mcp.md b/docs/mcp.md index 3ead9da179..acb6c3317f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2558,7 +2558,8 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, (`app.executeMenuCommand('…')`), each with a count and its lines, and `menuCommands.dynamic` counts the calls whose argument isn't a string literal. - `outside` lists what the script does outside the document: `filesWritten` (with the open modes used; setting a - File object's `length`, `hidden` or `readonly` counts too), `filesOpened` (files opened in other apps), `network`, + File object's `length`, `hidden` or `readonly` counts too, and so does a document's `saveAs` or `exportFile`), + `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed). - `problems` lists what would stop the script loading as written (strings, comments, regular expressions, @@ -2695,8 +2696,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `exportType` is an `ExportType`: `PNG24`, `JPEG` and `SVG` take `new ExportOptionsPNG24()`, `new ExportOptionsJPEG()` and `new ExportOptionsSVG()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/), - with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, more than 0 and at - most 776.19; 100 writes one pixel per point whatever the raster effects resolution), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and + with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, from 1 to + 776.19; 100 writes one pixel per point whatever the raster effects resolution), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and `coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and `includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with @@ -2706,7 +2707,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is - read-only`; and the files a command reads or writes besides the one named, such as an SVG's linked files, are + read-only`; a file a `File` object holds open for writing throws `Script file is open for writing` on `saveAs` + and `exportFile`, and `Script file access denied` when a command would write it besides the file named; and the + files a command reads or writes besides the one named, such as an SVG's linked files, are read and written only where the script's folders allow. `userInteractionLevel` does not change what a command does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with From f31cb42fd8ed8ceaa094d980e010883e1560ee72 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:49:59 -0800 Subject: [PATCH 06/69] Scripts: unlisted save, export and open options throw, and an object's own saveAs is not a file write - saveAs, exportFile and app.open throw " has no option " for a property their option class's help page does not list, instead of leaving it out. An undefined property is still left out, and PDFFileOptions also takes its read-only typename and parent. - The script checker no longer reports a file write for saveAs or exportFile called on a variable holding the script's own object literal that defines that method, with `.` or in brackets. It reports it again once the method is assigned or deleted, the object is indexed with a computed key, or another name may hold the object. - The read-only file test checks the open-document grant on its own, with no folder scope that also covers the file. --- crates/engine/src/file_access.rs | 7 ++- crates/engine/src/script/dom/save_open.rs | 22 +++++-- crates/engine/src/tests/script_save_open.rs | 15 ++++- crates/scriptcheck/src/analyze.rs | 54 ++++++++++++++++++ crates/scriptcheck/src/analyze/features.rs | 63 ++++++++++++++++++++- crates/scriptcheck/src/tests.rs | 51 +++++++++++++++++ docs/mcp.md | 5 +- 7 files changed, 203 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 9e05d92ce7..0eeed498e2 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -992,14 +992,17 @@ mod tests { }; let (kept, fresh) = (s(out.clone()), s(base.join("out/new.svg"))); let check = |p: &str| with_script_gate(gate.clone(), || (check_write(p).is_ok(), check_read(p).is_ok())); + // The open document's file is the only grant: no folder scope covers it. + let documents = ScriptGate { write: ScriptScope::default(), documents: vec![kept.clone()], ..gate.clone() }; + let document_write = || with_script_gate(documents.clone(), || check_write(&kept).is_ok()); assert_eq!(check(&kept), (true, true)); + assert!(document_write(), "an open document's file is written"); let mut perms = std::fs::metadata(&out).unwrap().permissions(); perms.set_readonly(true); std::fs::set_permissions(&out, perms.clone()).unwrap(); assert_eq!(check(&kept), (false, true), "a read-only file is read but not written"); assert!(check(&fresh).0, "a new file next to it is written"); - let documents = ScriptGate { documents: vec![kept.clone()], ..gate.clone() }; - assert!(!with_script_gate(documents, || check_write(&kept).is_ok()), "also when it is an open document's file"); + assert!(!document_write(), "also when it is an open document's file"); #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); std::fs::set_permissions(&out, perms).unwrap(); diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index c76ae0f44e..f54c2f3f0b 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -27,10 +27,12 @@ //! and when one of those files may not be written, none of them is. //! - An option the classes here map is applied; a listed option that is not mapped is accepted at //! the default its help page gives and throws an error that says it is not available yet at any -//! other value; a property the help pages do not list is left out. With `pDFPreset` named, a -//! `PDFSaveOptions` option still at a new object's default keeps the preset's value. +//! other value; a property the help pages do not list throws an error that names it, unless it is +//! `undefined`. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default +//! keeps the preset's value. //! - `app.open(file, documentColorSpace?, options?)` takes `options` as a `PDFFileOptions` record: -//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. +//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. Any other property +//! but `typename` and `parent` throws the same error, unless it is `undefined`. //! - `app.userInteractionLevel` starts at `UserInteractionLevel.DISPLAYALERTS` in each run. The //! commands a script runs never show a dialog, so the level does not change what they do, and it //! never allows a file the script's grants do not. @@ -131,6 +133,11 @@ fn not_available(class: &str, name: &str) -> HostError { HostError::Error(format!("{class}.{name} is not available yet")) } +/// The error a property that the help page of `class` does not list throws. +fn not_an_option(class: &str, name: &str) -> HostError { + HostError::Error(format!("{class} has no option {name}")) +} + fn whole_in(d: &Data, what: &str, lo: u64, hi: u64) -> std::result::Result { match d { Data::Number(n) => { @@ -522,7 +529,7 @@ fn options_params(class: &OptionClass, d: &Data) -> std::result::Result {} Some(_) => return Err(not_available(class.name, k)), - None => {} + None => return Err(not_an_option(class.name, k)), } } Ok(p) @@ -670,6 +677,9 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Type("open's options must be a PDFFileOptions record".into())); } for (k, v) in items { + if matches!(v, Data::Undefined) { + continue; + } match k.as_str() { "pageToOpen" => { p.insert("page".into(), json!(whole_in(v, "PDFFileOptions.pageToOpen", 1, 1_000_000)?)); @@ -686,7 +696,9 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { }; p.insert("cropTo".into(), json!(crop)); } - _ => {} + // The read-only members the help page lists. + "typename" | "parent" => {} + _ => return Err(not_an_option("PDFFileOptions", k)), } } } diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 8518f14365..9eabe077de 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -64,7 +64,7 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() { vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ d.saveAs(new File(dir + '/a.svg'));\n\ var o = new PDFSaveOptions(); vc.log([o.typename, o.compatibility, o.preserveEditability]);\n\ - o.compatibility = PDFCompatibility.ACROBAT7; o.viewAfterSaving = false; o.someOtherName = 3;\n\ + o.compatibility = PDFCompatibility.ACROBAT7; o.viewAfterSaving = false; o.pDFXStandardDescription = undefined;\n\ o.colorCompression = 'CompressionQuality.None';\n\ d.saveAs(new File(dir + '/b.pdf'), o); vc.log(d.name);\n\ var p = new ExportOptionsPNG24(); p.horizontalScale = p.verticalScale = 200; p.artBoardClipping = true;\n\ @@ -481,6 +481,12 @@ fn bad_arguments_are_refused_with_an_error() { (format!("app.open({f}, undefined, {{pageToOpen: 0}});"), "from 1"), (format!("app.open({f}, undefined, {{pDFCropToBox: 'art'}});"), "PDFBoxType"), (format!("app.open({f}, undefined, 5);"), "PDFFileOptions"), + (format!("var o = new PDFSaveOptions(); o.trimMark = true; app.activeDocument.saveAs({f}, o);"), "PDFSaveOptions has no option trimMark"), + ( + format!("var p = new ExportOptionsPNG24(); p.transparancy = false; app.activeDocument.exportFile({f}, ExportType.PNG24, p);"), + "ExportOptionsPNG24 has no option transparancy", + ), + (format!("app.open({f}, undefined, {{pageToOpne: 2}});"), "PDFFileOptions has no option pageToOpne"), ("app.userInteractionLevel = 'quiet';".into(), "UserInteractionLevel"), (format!("app.open({});", quoted(&dir.join("x.svg"))), "open needs a File"), ]; @@ -560,7 +566,7 @@ fn open_takes_the_page_and_crop_box_of_its_options() { &mut s, &base, &format!( - "Folder.userData; var g = app.open(new File({}), DocumentColorSpace.CMYK, {{pageToOpen: 2, pDFCropToBox: PDFBoxType.PDFMEDIABOX}});\n\ + "Folder.userData; var g = app.open(new File({}), DocumentColorSpace.CMYK, {{pageToOpen: 2, pDFCropToBox: PDFBoxType.PDFMEDIABOX, typename: 'PDFFileOptions', later: undefined}});\n\ vc.log(g.documentColorSpace);", quoted(&pdf) ), @@ -570,5 +576,10 @@ fn open_takes_the_page_and_crop_box_of_its_options() { assert!(!e.is_empty(), "a page the file does not have"); assert_eq!(s.documents().len(), 2); assert_eq!(s.active().unwrap().doc.artboards.len(), 1, "one page"); + // Options left undefined are left out: the file opens as it does without options. + let undefined = format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: undefined, pDFCropToBox: undefined}});", quoted(&pdf)); + logged(&mut s, &base, &undefined); + assert_eq!(s.documents().len(), 3); + assert_eq!(s.active().unwrap().doc.artboards.len(), 2, "both pages"); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 5d01cc8438..6c3177f498 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -495,6 +495,8 @@ struct Saved { shadowed: Option, /// It was a platform name the script had a meaning of its own for. own: bool, + /// What it held in [`Analyzer::writers`], 0 for nothing. + writer: u8, } /// The open brackets and their lines, up to [`crate::Limits::nesting`]; the brackets past that are @@ -566,6 +568,16 @@ struct Analyzer<'s, 'a, 'l> { maybe_files: HashSet, /// `maybe_files` ran out of room: no variable counts as holding a Folder object. maybe_files_full: bool, + /// The variables holding an object literal of the script's own that defines a method named as a + /// document method that writes a file (`{saveAs: …}`), each with a bit per method it defines (bit + /// `i` for `catalog::DOM_FILE_WRITES[i]`): a call of that method on them writes nothing. + writers: HashMap, + /// The object literals being assigned to a variable, the innermost last, each with the bracket + /// depth inside its `{`, up to [`crate::Limits::nesting`] of them. + objects: Vec<(String, usize)>, + /// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver + /// that is not such a variable. + index_receiver: u8, /// The platform names ([`platform_name`]) the script declares or assigns a meaning of its own /// for: they no longer stand for the platform's objects. own_names: HashSet, @@ -637,6 +649,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { folders: known.folders.clone(), maybe_files: known.files.difference(&known.folders).cloned().collect(), maybe_files_full: false, + writers: HashMap::new(), + objects: vec![], + index_receiver: 0, own_names: HashSet::new(), scopes: vec![], declared, @@ -742,6 +757,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.group_step(&t, started, before); self.paren_step(&t, before); self.assignment(&t, started); + self.object_key(&t); self.features(&t); self.newer(&t); self.module_check(&t); @@ -841,6 +857,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn bind(&mut self, name: String, path: String) { self.files.remove(&name); self.folders.remove(&name); + self.writers.remove(&name); if self.bound.contains_key(&name) || self.acc.room(self.bound.len()) { self.bound.insert(name, path); } @@ -850,6 +867,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn hold_file(&mut self, name: String, folder: bool) { self.bound.remove(&name); self.folders.remove(&name); + self.writers.remove(&name); if !folder && !self.maybe_files.contains(&name) { if self.acc.room(self.maybe_files.len()) { self.maybe_files.insert(name.clone()); @@ -973,6 +991,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { local: false, shadowed, own: self.own_names.contains(name), + writer: self.writers.get(name).copied().unwrap_or(0), } } @@ -1007,6 +1026,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else { self.own_names.remove(&name); } + if saved.writer != 0 { + self.writers.insert(name.clone(), saved.writer); + } else { + self.writers.remove(&name); + } if let Some(hidden) = saved.shadowed && let Some(i) = catalog::DOM_ROOTS.iter().position(|r| *r == name) && let Some(s) = self.shadowed.get_mut(i) @@ -1056,6 +1080,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.bound.remove(name); self.files.remove(name); self.folders.remove(name); + self.writers.remove(name); self.hide_root(name); } @@ -1249,6 +1274,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { local: false, shadowed: catalog::DOM_ROOTS.contains(&name).then_some(true), own: platform_name(name), + writer: 0, }; let outside = std::mem::replace(&mut c.saved, empty); if let Some(scope) = self.scopes.last_mut() { @@ -1272,6 +1298,12 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.start_value(a.name, Operand::Done(Held::File { folder: false })); } else if !a.after_new && t.is("(") { self.start_group(a.name); + } else if !a.after_new && t.is("{") { + // An object literal: its keys are read at the depth inside its `{` ([`Self::object_key`]). + self.unbind(&a.name); + if self.objects.len() < self.acc.limits.nesting { + self.objects.push((a.name, self.depth())); + } } else { self.unbind(&a.name); } @@ -1310,6 +1342,28 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// `t` in an object literal assigned to a variable: a `:` directly inside its braces after a key + /// that names a document method writing a file (`{saveAs: …}`, `{'exportFile': …}`) makes the + /// variable one of [`Analyzer::writers`]. A closing brace ends the literals it closes. + fn object_key(&mut self, t: &Sig<'s>) { + let depth = self.depth(); + while self.objects.pop_if(|(_, d)| *d > depth).is_some() {} + if !t.is(":") { + return; + } + let [h0, h1, ..] = self.h; + let Some(name) = self.objects.last().filter(|(_, d)| *d == depth).map(|(n, _)| n.clone()) else { return }; + let key = match h0 { + Some(k) if k.kind == T::Ident => Cow::Borrowed(k.text), + Some(k) if k.kind == T::Str => Cow::Owned(unquote(k.text, 32)), + _ => return, + }; + let Some(i) = catalog::DOM_FILE_WRITES.iter().position(|m| *m == key.as_ref()) else { return }; + if (is(h1, "{") || is(h1, ",")) && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { + *self.writers.entry(name).or_insert(0) |= 1 << i; + } + } + /// The variable that `t` changes to a number or a string, nothing the check follows, and whether /// the change waits for the value on the right. `name += …` and the other compound assignments /// (ECMA-262 3rd edition, section 11.13.2) store their result after that value is read, so the diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 7eb89a1fbe..d17a580560 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -84,6 +84,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } } + self.writer_use(t); match t.kind { T::Ident => self.name(t, line), T::Punct => self.punct(t, line), @@ -272,6 +273,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let name = h0.map(|s| unquote(s.text, 16)).unwrap_or_default(); self.setter(&name, h2, h3, line); } + // `local['saveAs']`: what the object before the bracket defines, for a call that may follow. + "[" => self.index_receiver = self.writer_bits(h0, h1), "(" => self.call(line), // `Name.prototype["+"] = …` defines an operator. "=" => { @@ -292,8 +295,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // `doc['saveAs'](f)`: a document method named by a string literal in brackets. if is(h0, "]") && is(h2, "[") - && let Some(name) = h1.filter(|s| s.kind == T::Str) - && catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str()) + && let Some(method) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32)) + && catalog::DOM_FILE_WRITES.contains(&method.as_str()) + && !Self::defines(self.index_receiver, &method) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); @@ -313,7 +317,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.acc.feature(FeatureId::FileDialog, line); } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { self.acc.feature(FeatureId::FileRead, line); - } else if (file && catalog::FILE_WRITES.contains(&n)) || catalog::DOM_FILE_WRITES.contains(&n) { + } else if (file && catalog::FILE_WRITES.contains(&n)) + || (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3), n)) + { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); } else if n == catalog::EXECUTE { @@ -336,6 +342,57 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// The methods that `receiver`, which `before` comes before, defines when it is a variable holding + /// an object literal of the script's own ([`Analyzer::writers`]), not a property of the same name; + /// 0 for anything else. A receiver the check does not follow may be a document. + fn writer_bits(&self, receiver: Option>, before: Option>) -> u8 { + match receiver { + Some(r) if r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0), + _ => 0, + } + } + + /// A variable of [`Analyzer::writers`] used before `t` in any way but a member (`local.name`, + /// `local['name']`) or an assignment to it ([`Analyzer::assignment`]), or whose `saveAs` or + /// `exportFile` is assigned: another name may hold its object, or its methods may change, so its + /// own methods are no longer known (`var b = local`, `f(local)`, `local.saveAs = w`, + /// `local[k] = w`, `delete local.saveAs`). + fn writer_use(&mut self, t: &Sig<'s>) { + let [h0, h1, h2, h3] = self.h; + let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); + let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")); + let key = t.is(":") && (is(h1, "{") || is(h1, ",")); + let escaped = if word(h0, "delete") { + // `delete local…` + writer(Some(*t), h0) + } else if let Some(name) = writer(h0, h1) { + // `local` followed by anything but a member, its own assignment or an object key's `:`. + (!t.is(".") && !t.is("[") && !t.is("=") && !key).then_some(name) + } else if is(h1, ".") && changes && h0.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&m.text)) { + // `local.saveAs = …` + writer(h2, h3) + } else if is(h0, "[") { + // `local[k]` with a key that is not a string literal. + writer(h1, h2).filter(|_| t.kind != T::Str) + } else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) { + // `local['name' + k]`. + writer(h2, h3).filter(|_| !t.is("]")) + } else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) { + // `local['saveAs'] = …` + writer(h3, None) + } else { + None + }; + if let Some(name) = escaped { + self.writers.remove(name); + } + } + + /// Whether `bits` ([`Self::writer_bits`]) has `method`: the receiver's own `method` is called. + fn defines(bits: u8, method: &str) -> bool { + catalog::DOM_FILE_WRITES.iter().position(|m| *m == method).is_some_and(|i| bits & (1 << i) != 0) + } + /// Whether `receiver`, which `before` comes before, is a variable holding a File or Folder object /// (not a property of the same name), or a File or Folder object made in place or held in /// grouping parentheses ([`Sig::file`]). diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index e985fa3d0f..9148f0e93f 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -558,6 +558,57 @@ fn save_as_and_export_file_in_brackets_write_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } +/// `saveAs` and `exportFile` called on an object literal of the script's own that defines them write +/// nothing, with `.` or in brackets. On a document, on a variable the check does not follow, on one +/// assigned something else since, and for a method the literal does not define, they write the file. +#[test] +fn the_scripts_own_save_as_writes_no_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var local = {saveAs: function () {}, 'n': 1};\n", + "local.saveAs(f);\n", + "local['saveAs'](f);\n", + "app.activeDocument.saveAs(f);\n", + "local.exportFile(f);\n", + "other.saveAs(f);\n", + "local = app.activeDocument;\n", + "local.saveAs(f);\n", + "var t = {x: 1, a: ok ? saveAs : 0, 'exportFile': function () {}};\n", + "t['exportFile'](f);\n", + "t.saveAs(f);\n", + "var activeDocument = {saveAs: function () {}};\n", + "app.activeDocument['saveAs'](f);\n", + "app.activeDocument.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 6, 7, 9, 12, 14, 15][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[5, 6, 7, 9, 12, 14, 15][..])]); +} + +/// Once the script replaces or deletes such a method, indexes the object with a computed key, or +/// lets another name hold the object, its `saveAs` may write a file again. +#[test] +fn a_changed_or_shared_own_save_as_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}, b = {saveAs: function () {}}, c = {saveAs: function () {}};\n", + "var d = {saveAs: function () {}}, e = {saveAs: function () {}}, g = {saveAs: function () {}};\n", + "a.saveAs(f); b['saveAs'](f); a.n = 1; a.n;\n", + "a.saveAs = app.activeDocument.saveAs;\n", + "b['saveAs'] = w;\n", + "c[k] = w;\n", + "delete d.saveAs;\n", + "var h = e;\n", + "use(g);\n", + "a.saveAs(f);\n", + "b.saveAs(f);\n", + "c.saveAs(f);\n", + "d.saveAs(f);\n", + "e.saveAs(f);\n", + "g['saveAs'](f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16][..])); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 4e00790a15..5dd133dc00 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2726,8 +2726,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `compressed`), and writes 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. A listed option that is not mapped is accepted at its help page's default, and any other value throws - an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`; properties the help - pages do not list are left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default + an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help + pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and + `parent`), and an `undefined` one is left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default keeps the preset's value. A bad value throws an error before anything is written. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. From b82dddc71da4b3b4a9508a2add57df9665bbf1a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:54:03 -0800 Subject: [PATCH 07/69] Docs: G6 and M13 list Document.saveAs, Document.exportFile and app.open --- docs/gaps.md | 3 ++- docs/roadmap.md | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index cd23b3096c..cecbd9c4c4 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -809,7 +809,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new - documents, each document's selection and its page items. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + documents, each document's selection and its page items, and save, export and open documents with + `Document.saveAs`, `Document.exportFile` and `app.open`. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/roadmap.md b/docs/roadmap.md index 3ddf3459a4..40c4518f52 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -196,7 +196,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) | 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; the rest of the script document model (layers, artboards, paths, type 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, and save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (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) | 🟡 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), 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 3a80afcb37c0a9236ba3a7c342c734e9b98a2911 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:59:25 -0800 Subject: [PATCH 08/69] Scripts: only a function expression makes an object's saveAs its own The script checker treats a saveAs or exportFile key of the script's own object literal as the script's own method only when its value is a function expression. A key holding another value, such as a document's method, is still reported as a file write when called, and so is a key whose last value in the literal is not a function expression. --- crates/scriptcheck/src/analyze.rs | 23 ++++++++++++++++------- crates/scriptcheck/src/tests.rs | 8 ++++++-- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 6c3177f498..dae8816eb1 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -1342,24 +1342,33 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } - /// `t` in an object literal assigned to a variable: a `:` directly inside its braces after a key - /// that names a document method writing a file (`{saveAs: …}`, `{'exportFile': …}`) makes the - /// variable one of [`Analyzer::writers`]. A closing brace ends the literals it closes. + /// `t` in an object literal assigned to a variable: a function expression directly inside its + /// braces as the value of a key that names a document method writing a file + /// (`{saveAs: function …}`, `{'exportFile': function …}`) makes the variable one of + /// [`Analyzer::writers`], and any other value of that key (`{saveAs: d.saveAs}`) takes the method + /// out again. A closing brace ends the literals it closes. fn object_key(&mut self, t: &Sig<'s>) { let depth = self.depth(); while self.objects.pop_if(|(_, d)| *d > depth).is_some() {} - if !t.is(":") { + let [h0, h1, h2, _] = self.h; + if !is(h0, ":") || !(is(h2, "{") || is(h2, ",")) { return; } - let [h0, h1, ..] = self.h; let Some(name) = self.objects.last().filter(|(_, d)| *d == depth).map(|(n, _)| n.clone()) else { return }; - let key = match h0 { + let key = match h1 { Some(k) if k.kind == T::Ident => Cow::Borrowed(k.text), Some(k) if k.kind == T::Str => Cow::Owned(unquote(k.text, 32)), _ => return, }; let Some(i) = catalog::DOM_FILE_WRITES.iter().position(|m| *m == key.as_ref()) else { return }; - if (is(h1, "{") || is(h1, ",")) && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { + if !t.word("function") { + let left = self.writers.get(&name).map_or(0, |bits| bits & !(1 << i)); + if left == 0 { + self.writers.remove(&name); + } else { + self.writers.insert(name, left); + } + } else if self.writers.contains_key(&name) || self.acc.room(self.writers.len()) { *self.writers.entry(name).or_insert(0) |= 1 << i; } } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 9148f0e93f..8d6bac9fa0 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -585,7 +585,8 @@ fn the_scripts_own_save_as_writes_no_file() { } /// Once the script replaces or deletes such a method, indexes the object with a computed key, or -/// lets another name hold the object, its `saveAs` may write a file again. +/// lets another name hold the object, its `saveAs` may write a file again, and so may a `saveAs` key +/// whose last value in the literal is not a function expression. #[test] fn a_changed_or_shared_own_save_as_writes_a_file() { let r = report(concat!( @@ -605,8 +606,11 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { "d.saveAs(f);\n", "e.saveAs(f);\n", "g['saveAs'](f);\n", + "var m = {saveAs: d.saveAs}, n = {saveAs: function () {}, saveAs: d.saveAs};\n", + "m.saveAs(f);\n", + "n.saveAs(f);\n", )); - assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16][..])); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16, 18, 19][..])); } /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing From 5f444df2957c0abdad17d6b37ab7063104c7b322 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 02:48:26 -0800 Subject: [PATCH 09/69] Save: a refused file ends a save of several files after the writer refuses it When the file access in force refuses one of the files a save writes, the save gives that file to its writer for the error, as before, and then returns the error even when the writer did not refuse it, so the other files are not written. --- crates/engine/src/cmd/fileio/save.rs | 2 + crates/engine/src/tests/script_save_open.rs | 41 +++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 94187808c6..550b52f414 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1078,6 +1078,8 @@ impl SaveJob { && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) { write(p, bytes)?; + // A writer that does not check the file access writes none of the others. + return Err(super::may_write(p).err().unwrap_or_else(|| crate::EngineError::Other(format!("file access denied: {p}")))); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 9eabe077de..126c7c3947 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -207,6 +207,47 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() { let _ = std::fs::remove_dir_all(base); } +/// When the writer a save is given does not check the file access itself, a save of several files +/// still writes none of them after the refused one. +#[test] +fn a_refused_file_stops_a_save_whose_writer_does_not_check() { + use crate::cmd::fileio::{SaveMode, save_job, save_plan}; + use crate::file_access::{ScriptGate, ScriptScope, with_script_gate}; + let base = folder("unchecked"); + let dir = base.join("outside"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let params = json!({"path": dir.join("a.eps").to_string_lossy(), "format": "eps", "useArtboards": true}); + let plan = save_plan(&s, SaveMode::SaveAs, ¶ms).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::of_folder(&dir), documents: vec![], held: vec![], also: None }; + let (mut refused, mut written) = (None, vec![]); + let make_read_only = |paths: &[&str]| { + let last = paths.last().map(|p| p.to_string()).unwrap(); + std::fs::write(&last, b"").unwrap(); + let mut perms = std::fs::metadata(&last).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&last, perms).unwrap(); + refused = Some(last); + None + }; + let r = with_script_gate(gate, || { + job.write_unless(make_read_only, |p, _| { + written.push(p.to_string()); + Ok(()) + }) + }); + assert!(r.is_err(), "{r:?}"); + let refused = refused.unwrap(); + assert_eq!(written, std::slice::from_ref(&refused), "only the refused file went to the writer"); + let mut perms = std::fs::metadata(&refused).unwrap().permissions(); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(&refused, perms).unwrap(); + let _ = std::fs::remove_dir_all(base); +} + /// Every path goes through the script's file grants, as a `File` opened for reading or writing. #[test] fn save_as_export_file_and_open_refuse_paths_outside_the_grants() { From c4edd76fc8b929b5dd86ddfb29d01e3197dc1d27 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:00:50 -0800 Subject: [PATCH 10/69] Scripts: only a whole var value makes an object's saveAs the script's own The checker treats `x.saveAs(f)` as the script's own method only when `x` was declared by a `var` statement, directly in a function body or the global code, whose first name takes an object literal with a `saveAs` or `exportFile` function as its whole value. The name counts from the end of the statement. - A literal given in a branch (`if (c) var e = {...}`), one the value goes on from (`{...} && doc`), one given by an assignment or to a later name of the statement, and a call inside the literal keep reporting the write. - A function that gives an outer variable another value removes the exemption after the function body. --- crates/scriptcheck/src/analyze.rs | 76 +++++++++++++++++++++++-------- crates/scriptcheck/src/tests.rs | 35 ++++++++++++-- 2 files changed, 88 insertions(+), 23 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index dae8816eb1..9056752744 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -266,6 +266,20 @@ struct Assign { after_new: bool, } +/// `name = {`: an object literal assigned to a variable. +struct ObjectValue { + name: String, + /// The bracket depth inside its `{`. + depth: usize, + /// The document methods writing a file that it defines with a function expression, a bit each + /// ([`Analyzer::writers`]). + bits: u8, + /// It is the value of the first name a `var` statement declares, and the statement is directly + /// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do` or + /// a loop's parentheses: only then does the variable hold `bits` after it. + whole: bool, +} + /// What a value the check follows holds: a member chain, or a File or Folder object (`folder` when it /// is a Folder object whatever the path names: [`Operand::file_step`]). enum Held { @@ -572,9 +586,12 @@ struct Analyzer<'s, 'a, 'l> { /// document method that writes a file (`{saveAs: …}`), each with a bit per method it defines (bit /// `i` for `catalog::DOM_FILE_WRITES[i]`): a call of that method on them writes nothing. writers: HashMap, - /// The object literals being assigned to a variable, the innermost last, each with the bracket - /// depth inside its `{`, up to [`crate::Limits::nesting`] of them. - objects: Vec<(String, usize)>, + /// The object literals being assigned to a variable, the innermost last, up to + /// [`crate::Limits::nesting`] of them. + objects: Vec, + /// An object literal whose `}` the last token was, with the methods it defines: the variable + /// holds them when the next token ends the `var` statement's value. + closed: Option<(String, u8)>, /// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver /// that is not such a variable. index_receiver: u8, @@ -651,6 +668,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { maybe_files_full: false, writers: HashMap::new(), objects: vec![], + closed: None, index_receiver: 0, own_names: HashSet::new(), scopes: vec![], @@ -1026,8 +1044,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else { self.own_names.remove(&name); } - if saved.writer != 0 { - self.writers.insert(name.clone(), saved.writer); + // An outer variable the body assigned keeps only the methods it still has: the body may have + // given it another value. + let writer = if saved.local { saved.writer } else { saved.writer & self.writers.get(&name).copied().unwrap_or(0) }; + if writer != 0 { + self.writers.insert(name.clone(), writer); } else { self.writers.remove(&name); } @@ -1301,8 +1322,15 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else if !a.after_new && t.is("{") { // An object literal: its keys are read at the depth inside its `{` ([`Self::object_key`]). self.unbind(&a.name); + let [_, _, declaration, before] = self.h; + let depth = self.depth(); + let body = self.scopes.last().map_or(0, |s| s.depth); + let starts = before.is_none() + || [";", "{", "}"].iter().any(|p| is(before, p)) + || (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !word(before, "else") && !word(before, "do")); + let whole = word(declaration, "var") && starts && depth.checked_sub(1) == Some(body); if self.objects.len() < self.acc.limits.nesting { - self.objects.push((a.name, self.depth())); + self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole }); } } else { self.unbind(&a.name); @@ -1344,32 +1372,40 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `t` in an object literal assigned to a variable: a function expression directly inside its /// braces as the value of a key that names a document method writing a file - /// (`{saveAs: function …}`, `{'exportFile': function …}`) makes the variable one of - /// [`Analyzer::writers`], and any other value of that key (`{saveAs: d.saveAs}`) takes the method - /// out again. A closing brace ends the literals it closes. + /// (`{saveAs: function …}`, `{'exportFile': function …}`) counts the method for the literal, and + /// any other value of that key (`{saveAs: d.saveAs}`) takes it out again. A closing brace ends + /// the literals it closes. The variable of a [`ObjectValue::whole`] literal joins + /// [`Analyzer::writers`] only when the token after its `}` ends the value (`;`, `,` or a line + /// break), so a call inside the literal, and a value that goes on (`{…} && d`), see the variable + /// as it was. fn object_key(&mut self, t: &Sig<'s>) { + if let Some((name, bits)) = self.closed.take() + && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) + && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) + { + self.writers.insert(name, bits); + } let depth = self.depth(); - while self.objects.pop_if(|(_, d)| *d > depth).is_some() {} + while let Some(o) = self.objects.pop_if(|o| o.depth > depth) { + if o.whole && o.bits != 0 && o.depth == depth.saturating_add(1) { + self.closed = Some((o.name, o.bits)); + } + } let [h0, h1, h2, _] = self.h; if !is(h0, ":") || !(is(h2, "{") || is(h2, ",")) { return; } - let Some(name) = self.objects.last().filter(|(_, d)| *d == depth).map(|(n, _)| n.clone()) else { return }; let key = match h1 { Some(k) if k.kind == T::Ident => Cow::Borrowed(k.text), Some(k) if k.kind == T::Str => Cow::Owned(unquote(k.text, 32)), _ => return, }; let Some(i) = catalog::DOM_FILE_WRITES.iter().position(|m| *m == key.as_ref()) else { return }; - if !t.word("function") { - let left = self.writers.get(&name).map_or(0, |bits| bits & !(1 << i)); - if left == 0 { - self.writers.remove(&name); - } else { - self.writers.insert(name, left); - } - } else if self.writers.contains_key(&name) || self.acc.room(self.writers.len()) { - *self.writers.entry(name).or_insert(0) |= 1 << i; + let Some(o) = self.objects.last_mut().filter(|o| o.depth == depth) else { return }; + if t.word("function") { + o.bits |= 1 << i; + } else { + o.bits &= !(1 << i); } } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 8d6bac9fa0..8140371f93 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -591,8 +591,8 @@ fn the_scripts_own_save_as_writes_no_file() { fn a_changed_or_shared_own_save_as_writes_a_file() { let r = report(concat!( "var f = new File(p);\n", - "var a = {saveAs: function () {}}, b = {saveAs: function () {}}, c = {saveAs: function () {}};\n", - "var d = {saveAs: function () {}}, e = {saveAs: function () {}}, g = {saveAs: function () {}};\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}}; var c = {saveAs: function () {}};\n", + "var d = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n", "a.saveAs(f); b['saveAs'](f); a.n = 1; a.n;\n", "a.saveAs = app.activeDocument.saveAs;\n", "b['saveAs'] = w;\n", @@ -606,13 +606,42 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { "d.saveAs(f);\n", "e.saveAs(f);\n", "g['saveAs'](f);\n", - "var m = {saveAs: d.saveAs}, n = {saveAs: function () {}, saveAs: d.saveAs};\n", + "var m = {saveAs: d.saveAs}; var n = {saveAs: function () {}, saveAs: d.saveAs};\n", "m.saveAs(f);\n", "n.saveAs(f);\n", )); assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16, 18, 19][..])); } +/// Only a `var` statement directly in a function body or the global code that gives its first name +/// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the +/// statement. A literal given in a branch, one the value goes on from, one given by an assignment +/// or to a later name of the statement, a call inside the literal, and a variable a function gave +/// another value keep reporting the write. +#[test] +fn only_a_whole_var_value_makes_save_as_the_scripts_own() { + let r = report(concat!( + "var f = new File(p);\n", + "var d = {saveAs: function () {}};\n", + "function choose() { d = null; d = app.activeDocument; }\n", + "d.saveAs(f);\n", + "var e = app.activeDocument;\n", + "if (flag) var e = {saveAs: function () {}};\n", + "e.saveAs(f);\n", + "if (flag) { var e2 = {saveAs: function () {}}; }\n", + "e2.saveAs(f);\n", + "var g = {saveAs: function () {}} && app.activeDocument;\n", + "g.saveAs(f);\n", + "var h = app.activeDocument;\n", + "h = {saveAs: function () {}, value: h.saveAs(f)};\n", + "var k = {saveAs: function () {}, value: k.saveAs(f)};\n", + "k.saveAs(f);\n", + "var x = 1, y = {saveAs: function () {}};\n", + "y.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..])); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] From ff4fc193f8e438256a720b52932613f179e4ab6f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:08:00 -0800 Subject: [PATCH 11/69] Scripts: a later saveAs value in brackets ends the exemption A literal such as `{saveAs: function () {}, saveAs: (doc.saveAs)}` kept the first key's exemption, because the value's opening bracket had already raised the depth when the key was read. The key is now read at the depth outside that bracket, so the later value replaces the function and `n['saveAs'](f)` is reported as a file write. --- crates/scriptcheck/src/analyze.rs | 4 +++- crates/scriptcheck/src/tests.rs | 5 ++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 9056752744..bb10272e62 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -1401,7 +1401,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { _ => return, }; let Some(i) = catalog::DOM_FILE_WRITES.iter().position(|m| *m == key.as_ref()) else { return }; - let Some(o) = self.objects.last_mut().filter(|o| o.depth == depth) else { return }; + // A value that starts with a bracket has opened it already: the key is at the depth outside it. + let at = if t.is("(") || t.is("[") || t.is("{") { depth.saturating_sub(1) } else { depth }; + let Some(o) = self.objects.last_mut().filter(|o| o.depth == at) else { return }; if t.word("function") { o.bits |= 1 << i; } else { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 8140371f93..bc03f6ab07 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -609,8 +609,11 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { "var m = {saveAs: d.saveAs}; var n = {saveAs: function () {}, saveAs: d.saveAs};\n", "m.saveAs(f);\n", "n.saveAs(f);\n", + "var q = {saveAs: function () {}, saveAs: (d.saveAs)}; var s = {saveAs: function () {}, saveAs: [w][0]};\n", + "q['saveAs'](f);\n", + "s.saveAs(f);\n", )); - assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16, 18, 19][..])); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16, 18, 19, 21, 22][..])); } /// Only a `var` statement directly in a function body or the global code that gives its first name From 9034e0d6d8b20307614dcab0b28e4d6a691a17d6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:20:43 -0800 Subject: [PATCH 12/69] Scripts: a saveAs value that goes on after the function body writes a file The script checker treats a saveAs or exportFile key of the script's own object literal as the script's own method only when the key's whole value is one function expression: `function`, an optional name, the parameters and the body, followed by `,` or the literal's closing brace. A value that goes on after the body, such as `function () {} && doc.saveAs`, a call of the function or a conditional, leaves the method reported as a file write. The variable takes the literal's methods before the token after the literal closes a function body, so a literal given to the body's own variable on the body's last line no longer hides a save on the outer variable of the same name. --- crates/scriptcheck/src/analyze.rs | 92 ++++++++++++++++++++++++------- crates/scriptcheck/src/tests.rs | 27 +++++++++ 2 files changed, 98 insertions(+), 21 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index bb10272e62..0e355d94f2 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -271,13 +271,58 @@ struct ObjectValue { name: String, /// The bracket depth inside its `{`. depth: usize, - /// The document methods writing a file that it defines with a function expression, a bit each - /// ([`Analyzer::writers`]). + /// The document methods writing a file that it defines with a single function expression as the + /// key's whole value, a bit each ([`Analyzer::writers`]). bits: u8, /// It is the value of the first name a `var` statement declares, and the statement is directly /// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do` or /// a loop's parentheses: only then does the variable hold `bits` after it. whole: bool, + /// The bit of the method whose value is being read, and how far that value has been read. + value: Option<(u8, Value)>, +} + +/// How far the value of an object literal's key that names a document method writing a file has been +/// read, by the tokens directly inside the literal's braces. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Value { + /// `function`. + Function, + /// The function expression's name. + Name, + /// The `(` of its parameters. + Params, + /// The `{` of its body: the value is the function expression when `,` or the literal's `}` comes + /// next. + Body, + /// Anything else, or anything after the body. + Other, +} + +impl ObjectValue { + /// `t`, a token directly inside the literal's braces: a `,` or the closing `}` ends the value + /// being read, and gives the literal the method only when the value is a single function + /// expression (`function () {} && d.saveAs`, `function () {}(f)` and `function () {}.call` give + /// it nothing). + fn step(&mut self, t: &Sig) { + let Some((bit, value)) = self.value else { return }; + if t.is(",") || t.is("}") { + if value == Value::Body { + self.bits |= bit; + } else { + self.bits &= !bit; + } + self.value = None; + return; + } + let next = match value { + Value::Function if t.kind == T::Ident => Value::Name, + Value::Function | Value::Name if t.is("(") => Value::Params, + Value::Params if t.is("{") => Value::Body, + _ => Value::Other, + }; + self.value = Some((bit, next)); + } } /// What a value the check follows holds: a member chain, or a File or Folder object (`folder` when it @@ -753,6 +798,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // `t` ends, holds the value, or nothing the check follows, before `t` starts a member chain or // closes a function body. self.settle_groups(&t); + self.settle_literal(&t); // A line break ends a `var` statement when it is outside the statement's brackets, and the // tokens on either side of it don't go on with the expression. if t.nl && self.var_depth == Some(self.depth()) && !goes_on_after(self.h[0]) && !goes_on_with(&t) { @@ -775,7 +821,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.group_step(&t, started, before); self.paren_step(&t, before); self.assignment(&t, started); - self.object_key(&t); + self.object_key(&t, before); self.features(&t); self.newer(&t); self.module_check(&t); @@ -1330,7 +1376,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { || (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !word(before, "else") && !word(before, "do")); let whole = word(declaration, "var") && starts && depth.checked_sub(1) == Some(body); if self.objects.len() < self.acc.limits.nesting { - self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole }); + self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole, value: None }); } } else { self.unbind(&a.name); @@ -1370,21 +1416,30 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } - /// `t` in an object literal assigned to a variable: a function expression directly inside its - /// braces as the value of a key that names a document method writing a file - /// (`{saveAs: function …}`, `{'exportFile': function …}`) counts the method for the literal, and - /// any other value of that key (`{saveAs: d.saveAs}`) takes it out again. A closing brace ends - /// the literals it closes. The variable of a [`ObjectValue::whole`] literal joins - /// [`Analyzer::writers`] only when the token after its `}` ends the value (`;`, `,` or a line - /// break), so a call inside the literal, and a value that goes on (`{…} && d`), see the variable - /// as it was. - fn object_key(&mut self, t: &Sig<'s>) { + /// The variable of the [`ObjectValue::whole`] literal whose `}` the token before `t` was joins + /// [`Analyzer::writers`] when `t` ends the value (`;`, `,` or a line break). It is read before `t` + /// closes a function body, so a literal given to the body's own variable stays inside the body. + fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { self.writers.insert(name, bits); } + } + + /// `t` in an object literal assigned to a variable, `before` the bracket depth before `t`: a single + /// function expression directly inside its braces as the whole value of a key that names a + /// document method writing a file (`{saveAs: function … {…}, …}`, `{'exportFile': function … {…}}`) + /// counts the method for the literal, and any other value of that key (`{saveAs: d.saveAs}`, + /// `{saveAs: function () {} && d.saveAs}`) takes it out again ([`ObjectValue::step`]). A closing + /// brace ends the literals it closes. The variable joins [`Analyzer::writers`] only after the + /// literal ([`Analyzer::settle_literal`]), so a call inside the literal, and a value that goes on + /// (`{…} && d`), see the variable as it was. + fn object_key(&mut self, t: &Sig<'s>, before: usize) { + if let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) { + o.step(t); + } let depth = self.depth(); while let Some(o) = self.objects.pop_if(|o| o.depth > depth) { if o.whole && o.bits != 0 && o.depth == depth.saturating_add(1) { @@ -1401,14 +1456,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { _ => return, }; let Some(i) = catalog::DOM_FILE_WRITES.iter().position(|m| *m == key.as_ref()) else { return }; - // A value that starts with a bracket has opened it already: the key is at the depth outside it. - let at = if t.is("(") || t.is("[") || t.is("{") { depth.saturating_sub(1) } else { depth }; - let Some(o) = self.objects.last_mut().filter(|o| o.depth == at) else { return }; - if t.word("function") { - o.bits |= 1 << i; - } else { - o.bits &= !(1 << i); - } + // A value that starts with a bracket has opened it already: the key is at the depth before it. + let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) else { return }; + o.value = Some((1 << i, if t.word("function") { Value::Function } else { Value::Other })); } /// The variable that `t` changes to a number or a string, nothing the check follows, and whether diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index bc03f6ab07..76d78f822b 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -645,6 +645,33 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..])); } +/// A `saveAs` key's value is a method of the script's own only when the whole value is one function +/// expression: a value that goes on after the function's body, and a literal inside another, leave +/// `saveAs` writing the file. A literal given to a function body's own variable at the end of the body +/// leaves the outer variable as it was. +#[test] +fn a_value_that_goes_on_after_the_function_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {} && app.activeDocument.saveAs};\n", + "var b = {saveAs: function () {}(f), n: 1};\n", + "var c = {saveAs: function () {} ? x : y};\n", + "var e = {saveAs: function () {}.call};\n", + "var k = {exportFile: function w(x) { return x; }, saveAs: function () {}};\n", + "var m = {o: {saveAs: function () {}}};\n", + "var q = app.activeDocument; function r() { var q = {saveAs: function () {}}\n", + "}\n", + "a.saveAs(f);\n", + "b.saveAs(f);\n", + "c.saveAs(f);\n", + "e.saveAs(f);\n", + "k.saveAs(f); k.exportFile(f);\n", + "m.saveAs(f);\n", + "q.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13, 15, 16][..])); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] From e8a0aa6ba444a89c622056f5f8d95f911556f3e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 19:01:40 -0800 Subject: [PATCH 13/69] Scripts: documents give their file, folder and saved state, close, and save several artboards - Document.fullName is a File for the document's file, and Document.path a Folder for its folder. A document without a file has a fullName of a File for its name in Folder.current and a path of "". Both throw `Script file access denied` with the document's name when the automation read roots do not allow the file. - Document.saved reads whether the document has unsaved changes. Setting it runs the new command document.setSaved, which records the document as saved or as changed without saving it and adds no undo step. - Document.close(saveOptions) closes a document without unsaved changes with any SaveOptions value. With unsaved changes, SaveOptions.DONOTSAVECHANGES closes it without them, and SaveOptions.SAVECHANGES saves them first with file.saveAs, in the format the file's extension names and after the write-access check saveAs makes, and throws for a document without a file (a converted or recovered one included). SaveOptions.PROMPTTOSAVECHANGES, the default, throws, since a script cannot show the prompt. - The script checker reports SaveOptions.SAVECHANGES under filesWritten wherever the script reads it. - A pDFPreset in square brackets, such as [Smallest File Size], names the built-in preset of the name inside them. - artboardRange takes a whole number from 1 as well as a string; any other number throws. - With saveMultipleArtboards true, a .ai or EPS save also writes each artboard of the range to a file of its own. Without it the range is not used, but text that is not a range of artboard numbers throws. Document page: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ --- crates/engine/src/cmd/edit.rs | 29 ++ crates/engine/src/script/dom.rs | 2 +- crates/engine/src/script/dom/save_open.rs | 240 +++++++++++++++- crates/engine/src/tests/script_save_open.rs | 257 ++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 18 +- crates/js/src/file_classes.rs | 31 +++ crates/js/src/host.rs | 10 +- crates/js/src/lib.rs | 2 +- crates/scriptcheck/src/analyze/features.rs | 17 ++ crates/scriptcheck/src/catalog.rs | 6 + crates/scriptcheck/src/tests.rs | 19 ++ docs/gaps.md | 3 +- docs/mcp.md | 40 ++- docs/roadmap.md | 2 +- docs/target-app-parity.md | 2 +- 15 files changed, 649 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index ccee814d90..81c201d95f 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -39,6 +39,15 @@ pub fn specs() -> Vec { has_doc, doc_move ), + cmd!( + "document.setSaved", + "Set Saved State", + [], + None, + "{index?: the document (default: the current one), saved: true or false} records the document as saved (true: Close asks nothing until the next edit) or as having unsaved changes (false), without saving it or adding an undo step; a document already in that state is left as it is", + has_doc, + doc_set_saved + ), cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → path (the document's file; null when automation read roots are in force and the file is outside them), layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect), cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node), cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find), @@ -257,6 +266,26 @@ fn doc_activate(s: &mut Session, p: &Value) -> Result { if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) } } +fn doc_set_saved(s: &mut Session, p: &Value) -> Result { + const C: &str = "document.setSaved"; + let i = opt_u64(p, C, "index")?.map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?; + let saved = match p.get("saved") { + None | Some(Value::Null) => return Err(bad(C, "missing `saved`: true or false")), + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(C, "`saved` must be true or false")), + }; + let uid = s.documents().get(i).map(|d| d.uid).ok_or_else(|| bad(C, "no such document"))?; + let st = s.document_mut(uid).ok_or_else(|| bad(C, "no such document"))?; + if st.is_dirty() == saved { + if saved { + st.mark_saved(); + } else { + st.mark_unsaved(); + } + } + ok() +} + fn doc_move(s: &mut Session, p: &Value) -> Result { let n = s.documents().len(); let from = match p.get("from") { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8e6c46e87d..e4a3e3a638 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1865,7 +1865,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("selection", property(l, doc_selection, doc_set_selection)), ]); document.extend( - ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "close"] + ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer"] .into_iter() .map(|m| later(l, "Document", m)), ); diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index f54c2f3f0b..b2c9a56378 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -1,5 +1,6 @@ //! Saving, exporting and opening documents in the script object model: `Document.saveAs`, -//! `Document.exportFile`, `app.open` and `app.userInteractionLevel`, with the option classes the +//! `Document.exportFile`, `Document.fullName`, `Document.path`, `Document.saved`, +//! `Document.close`, `app.open` and `app.userInteractionLevel`, with the option classes the //! help pages , //! , //! , @@ -29,7 +30,25 @@ //! the default its help page gives and throws an error that says it is not available yet at any //! other value; a property the help pages do not list throws an error that names it, unless it is //! `undefined`. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default -//! keeps the preset's value. +//! keeps the preset's value. A `pDFPreset` in square brackets names the built-in preset of the +//! name inside them; the default preset's name and `[PDF/X-4:2008]` name VectorCraft Default and +//! PDF/X-4:2010. +//! - `artboardRange` is a string, or a number read as `String(number)`. With +//! `saveMultipleArtboards` true, a `.ai` save also writes each artboard of the range (all when it +//! is empty) to a file of its own, `-.ai`. An EPS save of a range of two or +//! more artboards writes the file at the path and `_.eps` for each of them, and an EPS +//! save of one artboard writes only the file at the path, holding that artboard. Without +//! `saveMultipleArtboards` the range is not used, but a value that is not written as a range of +//! artboard numbers throws. +//! - `Document.path` is a `Folder` for the folder of the document's file. A document that has no +//! file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. +//! `fullName` and `path` of a document whose file the automation read roots do not allow throw +//! `Script file access denied`. Setting `Document.saved` runs `document.setSaved`. +//! - `Document.close` with unsaved changes closes without them with +//! `SaveOptions.DONOTSAVECHANGES`, and saves them to the document's file first with +//! `SaveOptions.SAVECHANGES`, which throws for a document that has no file (a converted or +//! recovered one included). `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws, since a +//! script cannot show the prompt. //! - `app.open(file, documentColorSpace?, options?)` takes `options` as a `PDFFileOptions` record: //! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. Any other property //! but `typename` and `parent` throws the same error, unless it is `undefined`. @@ -44,8 +63,8 @@ use serde_json::{Map, Value, json}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; use super::{ - Answer, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, current, doc_ref, given, method, named, num, on_doc, property, - text, this_doc, whole, + Answer, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, current, doc_ref, get, given, method, named, num, on_doc, + property, text, this_doc, whole, }; /// The most a scale factor of an export takes, in percent. @@ -86,6 +105,7 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[ ("EPSPostScriptLevelEnum", &["LEVEL2", "LEVEL3"]), ("PDFOverprint", &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"]), ("UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"]), + ("SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"]), ]; const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS"; @@ -165,9 +185,17 @@ fn compatibility(class: &str, d: &Data) -> std::result::Result<(), HostError> { } } -/// An artboard range: a string, given to the command as `range` unless it is empty. +/// An artboard range: a string, or a whole number from 1 read as `String(number)` reads it, given to +/// the command as `range` unless it is empty. Any other number throws. fn range(d: &Data, what: &str, p: &mut Map) -> std::result::Result<(), HostError> { - let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) }; + let s = match d { + Data::String(s) => s.clone(), + Data::Number(n) => { + whole(*n).filter(|n| *n >= 1).ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 1 or a range")))?; + vectorcraft_js::number_to_string(*n) + } + _ => return Err(HostError::Type(format!("{what} must be a string or a number"))), + }; if s.len() > MAX_TEXT_BYTES { return Err(HostError::Range(format!("{what} is too long"))); } @@ -189,17 +217,76 @@ fn ai_map(name: &str, d: &Data, p: &mut Map) -> std::result::Resu compatibility("IllustratorSaveOptions", d)?; None } + "artboardRange" | "saveMultipleArtboards" => return artboards_map("IllustratorSaveOptions", name, d, p), _ => return Ok(false), }; Ok(true) } +/// `artboardRange` and `saveMultipleArtboards` of a `.ai` or EPS save, as `range` and +/// [`MULTIPLE`] until [`artboard_files`] reads them together. +fn artboards_map(class: &str, name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("{class}.{name}"); + if name == "artboardRange" { + range(d, &what, p)?; + } else { + p.insert(MULTIPLE.into(), json!(boolean(d, &what)?)); + } + Ok(true) +} + +/// The key [`artboards_map`] keeps `saveMultipleArtboards` under. +const MULTIPLE: &str = "_multiple"; + +/// The params of a `.ai` (`format` `ai`) or EPS save for `saveMultipleArtboards` and +/// `artboardRange`: with `saveMultipleArtboards` true, the range (all when it is empty) goes to +/// `separateArtboards` of a `.ai` save or `useArtboards` of an EPS save, which write the artboards' +/// files; otherwise the range is not used, as the help pages say, but one that is not written as a +/// range ([`written_as_range`]) still throws. +fn artboard_files(format: &str, q: &mut Map) -> std::result::Result<(), HostError> { + let multiple = q.remove(MULTIPLE).and_then(|v| v.as_bool()).unwrap_or(false); + if !multiple { + if let Some(Value::String(r)) = q.remove("range") + && !r.trim().eq_ignore_ascii_case("all") + && !written_as_range(&r) + { + return Err(HostError::Range(format!("artboardRange `{r}` is not a range of artboard numbers"))); + } + } else if format == "ai" { + q.insert("separateArtboards".into(), json!(true)); + } else { + q.insert("useArtboards".into(), json!(true)); + } + Ok(()) +} + +/// Whether `r` is written as an artboard range, whatever artboards a document has: parts separated +/// by commas, each a number from 1, or two of them joined by `-` or `–` with either one left out +/// and the first no greater than the second. +fn written_as_range(r: &str) -> bool { + // A number of digits alone, from 1; past `u64` it counts as the largest. + let num = |t: &str| -> Option> { + let t = t.trim(); + if t.is_empty() { + return Some(None); + } + let n = t.bytes().all(|b| b.is_ascii_digit()).then(|| t.parse::().unwrap_or(u64::MAX))?; + (n >= 1).then_some(Some(n)) + }; + r.split(',').map(str::trim).filter(|p| !p.is_empty()).all(|part| match part.replace('\u{2013}', "-").split_once('-') { + Some((a, b)) => match (num(a), num(b)) { + (Some(Some(a)), Some(Some(b))) => a <= b, + (Some(a), Some(b)) => a.is_some() || b.is_some(), + _ => false, + }, + None => matches!(num(part), Some(Some(_))), + }) +} + const AI_KEPT: &[(&str, Default)] = &[ - ("artboardRange", Default::Text("")), ("embedLinkedFiles", Default::Bool(false)), ("flattenOutput", Default::Member("OutputFlattening", "PRESERVEAPPEARANCE")), ("fontSubsetThreshold", Default::Num(100.0)), - ("saveMultipleArtboards", Default::Bool(false)), ]; fn ai_starts() -> Vec<(&'static str, Data)> { @@ -236,18 +323,17 @@ fn eps_map(name: &str, d: &Data, p: &mut Map) -> std::result::Res p.insert("overprints".into(), json!(if keep { "preserve" } else { "discard" })); } "compatibility" => compatibility("EPSSaveOptions", d)?, + "artboardRange" | "saveMultipleArtboards" => return artboards_map("EPSSaveOptions", name, d, p), _ => return Ok(false), } Ok(true) } const EPS_KEPT: &[(&str, Default)] = &[ - ("artboardRange", Default::Text("")), ("compatibleGradientPrinting", Default::Bool(false)), ("embedAllFonts", Default::Bool(false)), ("embedLinkedFiles", Default::Unset), ("flattenOuput", Default::Unset), - ("saveMultipleArtboards", Default::Bool(false)), ]; fn eps_starts() -> Vec<(&'static str, Data)> { @@ -578,6 +664,29 @@ fn plain(real: std::path::PathBuf) -> String { crate::cmd::findfiles::plain(real).to_string_lossy().into_owned() } +/// The built-in preset names scripts use that VectorCraft's built-in presets name otherwise, and the +/// preset each one names here. +const PRESET_ALIASES: &[(&str, &str)] = &[ + ("Illustrator Default", vectorcraft_pdf::DEFAULT_PRESET), // brand-ok: the preset name scripts use + ("PDF/X-4:2008", "PDF/X-4:2010"), +]; + +/// A `pDFPreset` in square brackets (`[Smallest File Size]`) names the built-in preset of the name +/// inside the brackets, or the one [`PRESET_ALIASES`] gives for it. A preset the name already +/// names, a saved preset called `[Name]` included, is left as it is, and any other name is left for +/// the save to refuse. +fn builtin_preset_name(h: &Host, q: &mut Map) { + let Some(name) = q.get("preset").and_then(Value::as_str) else { return }; + let s = h.session.borrow(); + if crate::cmd::fileio::pdf::find_preset(name, &s.prefs.pdf_presets).is_some() { + return; + } + let Some(inside) = name.trim().strip_prefix('[').and_then(|n| n.strip_suffix(']')) else { return }; + let inside = PRESET_ALIASES.iter().find(|(alias, _)| alias.eq_ignore_ascii_case(inside.trim())).map_or(inside, |(_, to)| to); + let Some(builtin) = vectorcraft_pdf::builtin_preset(inside) else { return }; + q.insert("preset".into(), json!(builtin.name)); +} + /// `document.saveAs(file, options?)`: `file.saveAs` on the document, in the format the options' /// class names (`ai`, `eps`, `pdf`), or without options in the format of the path's extension. fn doc_save_as(h: &Host, a: &[Data]) -> Answer { @@ -594,7 +703,12 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { let Some((class, format)) = SAVE_CLASSES.iter().find(|(c, _)| Some(c.name) == name) else { return Err(HostError::Type("saveAs options must be IllustratorSaveOptions, EPSSaveOptions or PDFSaveOptions".into())); }; - let q = options_params(class, o)?; + let mut q = options_params(class, o)?; + if *format == "pdf" { + builtin_preset_name(h, &mut q); + } else { + artboard_files(format, &mut q)?; + } p.insert("format".into(), json!(format)); if *format == "ai" { p.extend(q); @@ -717,6 +831,101 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { Ok(doc_ref(h, st.uid)) } +/// The document's file, `None` for a document that has none, or `Script file access denied` with +/// the document's name when the automation read roots do not allow the file to be named +/// ([`crate::file_access::check_read`]), as `app.getIsFileOpen` reads them. +fn shown_file(st: &crate::DocState) -> std::result::Result, HostError> { + match st.path.as_deref() { + Some(p) if crate::file_access::check_read(p).is_err() => { + Err(HostError::Error(format!("{}: {}", super::super::files::ACCESS_DENIED, st.title()))) + } + p => Ok(p), + } +} + +/// `document.fullName`: a `File` for the document's file, or, for a document that has none, a +/// `File` for its name in `Folder.current`. +fn doc_full_name(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + super::with_doc(h, doc, |_, st| { + Ok(match shown_file(st)? { + Some(p) => vectorcraft_js::file_ref(p), + None => vectorcraft_js::file_ref(&st.title()), + }) + }) +} + +/// `document.path`: a `Folder` for the folder of the document's file, or an empty string for a +/// document that has none. +fn doc_path(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let folder = super::with_doc(h, doc, |_, st| { + Ok(shown_file(st)?.and_then(|p| { + let parent = std::path::Path::new(p).parent()?.to_string_lossy().into_owned(); + (!parent.is_empty()).then_some(parent) + })) + })?; + Ok(folder.map_or_else(|| text(""), |f| vectorcraft_js::folder_ref(&f))) +} + +/// `document.saved`: whether the document has no changes since it was opened or last saved. +fn doc_saved(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(Data::Bool(super::with_doc(h, doc, |_, st| !st.is_dirty()))) +} + +/// `document.saved = value`: `document.setSaved`, which records the document as saved or as having +/// unsaved changes without saving it. +fn doc_set_saved(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let saved = boolean(arg(a, 1), "Document.saved")?; + command(h, "document.setSaved", &json!({"index": doc.index, "saved": saved}))?; + Ok(Data::Undefined) +} + +/// The error `close` gives for a document with unsaved changes with +/// `SaveOptions.PROMPTTOSAVECHANGES`. +const UNSAVED_CHANGES: &str = + "the document has unsaved changes: save them first, or close with SaveOptions.SAVECHANGES or SaveOptions.DONOTSAVECHANGES"; + +/// The error `close(SaveOptions.SAVECHANGES)` gives for a document with unsaved changes that has +/// no file to save to. +const NO_FILE_TO_SAVE: &str = + "the document has unsaved changes and no file to save them to: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; + +/// `document.close(saveOptions?)`: `file.close` of the document. A document without unsaved +/// changes closes with any `SaveOptions`. With unsaved changes, `SaveOptions.DONOTSAVECHANGES` +/// closes it without them; `SaveOptions.SAVECHANGES` saves them to the document's file with +/// `file.saveAs` in the format its extension names, after the write-access check `saveAs` makes of +/// the path, and then closes it, and throws [`NO_FILE_TO_SAVE`] +/// for a document that has no file, a converted or recovered one included; and +/// `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws [`UNSAVED_CHANGES`], since a script +/// cannot show the prompt. +fn doc_close(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let how = match given(arg(a, 1)).filter(|d| !matches!(d, Data::Null)) { + Some(d) => member(d, "SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"], "saveOptions")?, + None => "PROMPTTOSAVECHANGES", + }; + let (dirty, file) = super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered))); + if dirty { + match how { + "DONOTSAVECHANGES" => {} + "SAVECHANGES" => { + let path = file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?; + // A refusal names the document, as `fullName` does when the read roots hide its file. + let name = super::with_doc(h, doc, |_, st| st.title()); + let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?; + let p = json!({"path": plain(real)}); + exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &p)))?; + } + _ => return Err(HostError::Error(UNSAVED_CHANGES.into())), + } + } + command(h, "file.close", &json!({"index": doc.index}))?; + Ok(Data::Undefined) +} + fn app_interaction(h: &Host, _: &[Data]) -> Answer { Ok(text(if h.dom.save_options.quiet.get() { QUIET } else { DISPLAY })) } @@ -734,7 +943,14 @@ pub(super) fn application_members(l: &Link) -> Vec<(String, HostMember)> { /// The members these add to `Document`. pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { - named(vec![("saveAs", method(l, doc_save_as)), ("exportFile", method(l, doc_export_file))]) + named(vec![ + ("saveAs", method(l, doc_save_as)), + ("exportFile", method(l, doc_export_file)), + ("fullName", get(l, doc_full_name)), + ("path", get(l, doc_path)), + ("saved", property(l, doc_saved, doc_set_saved)), + ("close", method(l, doc_close)), + ]) } /// The option classes: each `new Name()` gives a record with its `typename` and the defaults its diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 126c7c3947..4389838807 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -477,6 +477,7 @@ fn bad_arguments_are_refused_with_an_error() { let cases: Vec<(String, &str)> = vec![ ("app.activeDocument.saveAs('x.svg');".into(), "saveAs needs a File"), (format!("app.activeDocument.saveAs({{'\\u0000fileRef': {}}});", quoted(&dir.join("x.svg"))), "is not plain data"), + (format!("app.activeDocument.saveAs({{'\\u0000folderRef': {}}});", quoted(&dir)), "is not plain data"), (format!("app.activeDocument.saveAs({f}, {{typename: 'Nope'}});"), "saveAs options must be"), (format!("app.activeDocument.saveAs({f}, new ExportOptionsSVG());"), "saveAs options must be"), (format!("var o = new IllustratorSaveOptions(); o.compressed = 'yes'; app.activeDocument.saveAs({f}, o);"), "must be true or false"), @@ -624,3 +625,259 @@ fn open_takes_the_page_and_crop_box_of_its_options() { assert_eq!(s.active().unwrap().doc.artboards.len(), 2, "both pages"); let _ = std::fs::remove_dir_all(base); } + +/// `fullName` and `path` name the document's file and folder once it has one, `saved` follows its +/// changes, and `close` with `SaveOptions.DONOTSAVECHANGES` closes it. +#[test] +fn full_name_path_saved_and_close_follow_the_documents_file() { + let base = folder("fullname"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.log([d.fullName instanceof File, d.fullName.name === d.name, d.fullName.fsName === new File(d.name).fsName, d.path === '', d.saved]);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); vc.log(d.saved);\n\ + d.saveAs(new File(dir + '/a.svg'));\n\ + vc.log([d.fullName instanceof File, d.fullName.fsName, d.fullName.name, d.path instanceof Folder, d.path.fsName, d.saved]);\n\ + vc.run('shape.rectangle', {{x: 20, y: 20, width: 5, height: 5}}); vc.log(d.saved);\n\ + var e = ''; try {{ d.close(); }} catch (x) {{ e = String(x); }} vc.log([e, app.documents.length]);\n\ + var before = new File(dir + '/a.svg').length; d.close(SaveOptions.SAVECHANGES);\n\ + vc.log([app.documents.length, new File(dir + '/a.svg').length > before]);\n\ + var n = app.documents.add(DocumentColorSpace.RGB, 200, 100); vc.run('shape.rectangle', {{x: 10, y: 10, width: 5, height: 5}});\n\ + e = ''; try {{ n.close(SaveOptions.SAVECHANGES); }} catch (x) {{ e = String(x); }} vc.log([e, app.documents.length]);\n\ + n.close(SaveOptions.DONOTSAVECHANGES); vc.log(app.documents.length);" + ), + ); + assert_eq!(out[0], json!([true, true, true, true, true]), "an untouched document that has no file"); + assert_eq!(out[1], json!(false), "an edit leaves changes to save"); + let file = dir.join("a.svg"); + assert_eq!( + out[2], + json!([true, file.to_string_lossy(), "a.svg", true, dir.to_string_lossy(), true]), + "after saveAs the document's file and folder" + ); + assert_eq!(out[3], json!(false)); + assert!(out[4][0].as_str().unwrap().contains("unsaved changes"), "{}", out[4]); + assert_eq!(out[4][1], json!(1), "without SaveOptions the document stays open"); + assert_eq!(out[5], json!([0, true]), "SAVECHANGES saves the edit to the document's file and closes it"); + assert!(out[6][0].as_str().unwrap().contains("no file to save"), "{}", out[6]); + assert_eq!(out[6][1], json!(1), "SAVECHANGES without a file leaves the document open"); + assert_eq!(out[7], json!(0)); + assert!(s.documents().is_empty()); + let e = failure(&mut s, &base, "app.documents.add(); app.activeDocument.close('DONOTSAVECHANGES');"); + assert!(e.contains("SaveOptions"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A document without unsaved changes closes with `SaveOptions.SAVECHANGES` and with no argument. +#[test] +fn a_document_without_unsaved_changes_closes_with_any_save_options() { + let base = folder("closeclean"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "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}}); d.saveAs(new File(dir + '/a.svg'));\n\ + var e = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.log([d.saved, e.saved, app.documents.length]);\n\ + d.close(SaveOptions.SAVECHANGES); vc.log(app.documents.length);\n\ + e.close(); vc.log(app.documents.length);" + ), + ); + assert_eq!(out, json!([[true, true, 2], 1, 0])); + let _ = std::fs::remove_dir_all(base); +} + +/// Setting `Document.saved` records the document's saved state without saving it: `true` lets +/// `close()` close a document with edits, and `false` makes an untouched one ask. +#[test] +fn setting_saved_records_the_saved_state() { + let base = folder("setsaved"); + let mut s = session(&base); + data_folder(&mut s, &base); + let out = logged( + &mut s, + &base, + "var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {x: 10, y: 10, width: 50, height: 20});\n\ + vc.log(d.saved); d.saved = true; vc.log(d.saved); d.close(); vc.log(app.documents.length);\n\ + var e = app.documents.add(DocumentColorSpace.RGB, 200, 100); vc.log(e.saved); e.saved = false; vc.log(e.saved);\n\ + var m = ''; try { e.close(); } catch (x) { m = String(x); } vc.log([m, app.documents.length]);\n\ + m = ''; try { e.saved = 'yes'; } catch (x) { m = String(x); } vc.log(m);", + ); + assert_eq!(out[0], json!(false), "an edit leaves changes to save"); + assert_eq!(out[1], json!(true)); + assert_eq!(out[2], json!(0), "close() closes a document set as saved"); + assert_eq!(out[3], json!(true)); + assert_eq!(out[4], json!(false)); + assert!(out[5][0].as_str().unwrap().contains("unsaved changes"), "{}", out[5]); + assert_eq!(out[5][1], json!(1), "a document set as unsaved stays open"); + assert!(out[6].as_str().unwrap().contains("true or false"), "{}", out[6]); + assert!(s.active().unwrap().is_dirty(), "the state stays after the run"); + let _ = std::fs::remove_dir_all(base); +} + +/// With automation read roots that leave out the document's file, `fullName` and `path` throw +/// instead of naming another file. +#[test] +fn full_name_and_path_leave_out_a_file_outside_the_read_roots() { + let base = folder("fullnameroots"); + let mut s = session(&base); + data_folder(&mut s, &base); + let file = base.join("outside/hidden.svg"); + s.execute("file.new", &json!({})).unwrap(); + s.execute("document.save", &json!({"path": file.to_string_lossy()})).unwrap(); + let query = "var d = app.activeDocument; vc.log([d.fullName.name, d.fullName.fsName, d.path === '' ? '' : d.path.fsName]);"; + let out = logged(&mut s, &base, query); + let outside = base.join("outside"); + assert_eq!(out[0], json!(["hidden.svg", file.to_string_lossy(), outside.to_string_lossy()]), "no read roots: the whole path"); + let roots = crate::file_access::AutomationRoots::new(&[&base.join("main"), &base.join("settings")], &[&base.join("settings")]).unwrap().unwrap(); + let hidden = "var d = app.activeDocument, r = [];\n\ + try { r.push(d.fullName.fsName); } catch (e) { r.push(e.message); }\n\ + try { r.push(String(d.path)); } catch (e) { r.push(e.message); }\n\ + vc.log(r);"; + let out = crate::file_access::confine(Some(&roots), || logged(&mut s, &base, hidden)); + for m in out[0].as_array().unwrap() { + let m = m.as_str().unwrap(); + assert!(m.starts_with(DENIED) && m.ends_with("hidden.svg"), "{m}"); + assert!(!m.contains("outside"), "the folder outside the read roots is not named: {m}"); + } + let before = std::fs::read(&file).unwrap(); + let e = failure( + &mut s, + &base, + "vc.run('shape.rectangle', {x: 10, y: 10, width: 50, height: 20}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(e.contains(DENIED) && !e.contains("outside"), "SAVECHANGES does not write a file the script may not: {e}"); + assert_eq!(std::fs::read(&file).unwrap(), before, "the file is left as it was"); + assert_eq!(s.documents().len(), 1, "the document stays open"); + let _ = std::fs::remove_dir_all(base); +} + +/// A `pDFPreset` in square brackets names the built-in preset of the name inside them, and a name +/// that is not a preset either way is refused. +#[test] +fn a_bracketed_pdf_preset_names_the_built_in_preset() { + let base = folder("brackets"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "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 PDFSaveOptions(); o.pDFPreset = '[Smallest File Size]'; d.saveAs(new File(dir + '/small.pdf'), o);\n\ + o.pDFPreset = '[Illustrator Default]'; d.saveAs(new File(dir + '/default.pdf'), o);\n\ + o.pDFPreset = '[PDF/X-4:2008]'; d.saveAs(new File(dir + '/x4.pdf'), o);" + ), + ); + let small = std::fs::read(dir.join("small.pdf")).unwrap(); + assert!(String::from_utf8_lossy(&small[..200.min(small.len())]).contains("/Linearized 1"), "Smallest File Size writes a linearized file"); + assert!(dir.join("default.pdf").is_file()); + let x4 = String::from_utf8_lossy(&std::fs::read(dir.join("x4.pdf")).unwrap()).into_owned(); + assert!(x4.contains("PDF/X-4"), "the PDF/X-4 preset writes a PDF/X-4 file"); + for bad in ["[Nope]", "[Basic Default]", "[Ilustrator Default]"] { + let e = failure( + &mut s, + &base, + &format!("Folder.userData; var o = new PDFSaveOptions(); o.pDFPreset = '{bad}'; app.activeDocument.saveAs(new File({d} + '/n.pdf'), o);"), + ); + assert!(e.contains("unknown PDF preset"), "{bad}: {e}"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// A number given as `artboardRange` is read as `String(number)` reads it. +#[test] +fn a_number_artboard_range_names_that_artboard() { + let base = folder("rangenumber"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});\n\ + var o = new PDFSaveOptions(); o.artboardRange = 2; d.saveAs(new File(dir + '/two.pdf'), o);" + ), + ); + let pdf = vectorcraft_pdf::import(&std::fs::read(dir.join("two.pdf")).unwrap()).unwrap(); + assert_eq!(pdf.artboards.len(), 1, "one page"); + let r = pdf.artboards[0].rect; + assert!((r.width() - 60.0).abs() < 0.01 && (r.height() - 80.0).abs() < 0.01, "the second artboard: {r:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// With `saveMultipleArtboards`, a `.ai` or EPS save also writes a file for each artboard of +/// `artboardRange`; without it the range is not used, and only a value that is not written as a +/// range throws. +#[test] +fn save_multiple_artboards_writes_a_file_per_artboard() { + let base = folder("multiple"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let names = |sub: &str| { + let mut v: Vec = std::fs::read_dir(dir.join(sub)).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + v.sort(); + v + }; + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var names = ['ai', 'eps', 'aione', 'epsone', 'aioff'];\n\ + for (var i = 0; i < names.length; i++) new Folder(dir + '/' + names[i]).create();\n\ + var a = new IllustratorSaveOptions(); a.saveMultipleArtboards = true; d.saveAs(new File(dir + '/ai/a.ai'), a);\n\ + var e = new EPSSaveOptions(); e.saveMultipleArtboards = true; d.saveAs(new File(dir + '/eps/a.eps'), e);\n\ + a.artboardRange = '2'; d.saveAs(new File(dir + '/aione/a.ai'), a);\n\ + e.artboardRange = 2; d.saveAs(new File(dir + '/epsone/a.eps'), e);\n\ + a.saveMultipleArtboards = false; d.saveAs(new File(dir + '/aioff/a.ai'), a);" + ), + ); + assert_eq!(names("ai"), ["a-Artboard-1.ai", "a-Artboard-2.ai", "a.ai"], "the file and one for each of the two artboards"); + assert_eq!(names("eps"), ["a.eps", "a_Artboard-1.eps", "a_Artboard-2.eps"], "the central file and one for each of the two artboards"); + assert_eq!(names("aione"), ["a-Artboard-2.ai", "a.ai"], "the file and one for artboard 2"); + assert_eq!(names("epsone"), ["a.eps"], "one artboard: its file alone"); + let eps = String::from_utf8_lossy(&std::fs::read(dir.join("epsone/a.eps")).unwrap()).into_owned(); + let bbox = eps.lines().find(|l| l.starts_with("%%BoundingBox:")).unwrap_or_default(); + assert_eq!(bbox.split_whitespace().skip(1).collect::>(), ["0", "0", "60", "80"], "the file holds artboard 2: {bbox}"); + assert_eq!(names("aioff"), ["a.ai"], "without saveMultipleArtboards the range is not used"); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var a = new IllustratorSaveOptions(); a.artboardRange = 3; \ + app.activeDocument.saveAs(new File({d} + '/aioff/c.ai'), a);" + ), + ); + assert!(dir.join("aioff/c.ai").is_file(), "a range past the document's artboards is not used and does not stop the save"); + for bad in ["'abc'", "'0-'", "'3-1'", "'-'", "-1", "2.5", "0"] { + let e = failure( + &mut s, + &base, + &format!( + "Folder.userData; var a = new IllustratorSaveOptions(); a.artboardRange = {bad}; \ + app.activeDocument.saveAs(new File({d} + '/aioff/b.ai'), a);" + ), + ); + assert!(e.contains("range"), "{bad}: {e}"); + } + assert!(!dir.join("aioff/b.ai").exists(), "a bad range writes nothing"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index a0794be35c..d20c3ab3e6 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -39,12 +39,15 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), ("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"), ("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"), + ("SaveOptions.SAVECHANGES", "app.activeDocument.close(SaveOptions.SAVECHANGES);", "filesWritten"), ]; /// 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.close` throws "not available yet". `app.open` reads the file it is given. +/// documents; `Document.close` closes a document, and saves it to its own file only when it is given +/// `SaveOptions.SAVECHANGES`, which has its row above. `Document.fullName` and +/// `Document.path` only name its file and folder. `app.open` reads the file it is given. const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), @@ -98,9 +101,9 @@ const INSIDE: &[(&str, &str)] = &[ ("Document.", "prototype"), ( "Document.prototype.", - "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ - groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ + "activeLayer activeLayer= artboards artboards= close constructor convertCoordinate documentColorSpace fullName \ + groupItems groupItems= height layers layers= name pageItems parent path pathItems pathItems= rulerOrigin rulerOrigin= \ + rulerUnits saved saved= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ views views= width", ), ("Layer.", "prototype"), @@ -132,7 +135,11 @@ const INSIDE: &[(&str, &str)] = &[ ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), // The enumerations of saving, exporting and opening. - ("", "Compatibility EPSPostScriptLevelEnum EPSPreview ExportType PDFBoxType PDFCompatibility PDFOverprint UserInteractionLevel"), + ( + "", + "Compatibility EPSPostScriptLevelEnum EPSPreview ExportType PDFBoxType PDFCompatibility PDFOverprint SaveOptions \ + UserInteractionLevel", + ), ( "Compatibility.", "ILLUSTRATOR10 ILLUSTRATOR11 ILLUSTRATOR12 ILLUSTRATOR13 ILLUSTRATOR14 ILLUSTRATOR15 ILLUSTRATOR16 ILLUSTRATOR17 \ @@ -144,6 +151,7 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFBoxType.", "PDFARTBOX PDFBLEEDBOX PDFBOUNDINGBOX PDFCROPBOX PDFMEDIABOX PDFTRIMBOX"), ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), + ("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), ]; diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index f4f2064812..8083e6f46c 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -54,6 +54,11 @@ impl Classes { /// plain object a script made that carries the key is refused. pub const FILE_REF_KEY: &str = "\u{0}fileRef"; +/// The one key of the [`crate::Data`] object a host gives for a `Folder`, with the folder's path in +/// the host's platform form as its value. A plain object a script made that carries the key is +/// refused. +pub const FOLDER_REF_KEY: &str = "\u{0}folderRef"; + /// The path of the `File` that `d` stands for ([`FILE_REF_KEY`]). pub fn file_ref_path(d: &crate::Data) -> Option<&str> { let crate::Data::Object(items) = d else { return None }; @@ -63,7 +68,33 @@ pub fn file_ref_path(d: &crate::Data) -> Option<&str> { } } +/// What a host gives for a `File` at `path`, in the host's platform form: the script receives a +/// `File` object for it. +pub fn file_ref(path: &str) -> crate::Data { + crate::Data::Object(vec![(FILE_REF_KEY.to_string(), crate::Data::String(path.to_string()))]) +} + +/// What a host gives for a `Folder` at `path`, in the host's platform form: the script receives a +/// `Folder` object for it. +pub fn folder_ref(path: &str) -> crate::Data { + crate::Data::Object(vec![(FOLDER_REF_KEY.to_string(), crate::Data::String(path.to_string()))]) +} + impl Interp { + /// A new `File` (or, with `folder`, a `Folder`) for `path`, a path in the host's platform form + /// that a host gave ([`file_ref`], [`folder_ref`]). The host's `parse` reads it from + /// `Folder.current`, as it reads the path of `new File()`, so a relative path names a file there. + pub(crate) fn write_fs_ref(&mut self, path: &str, folder: bool) -> JsResult { + let c = classes(self)?; + let proto = if folder { c.folder_proto } else { c.file_proto }; + let text = Value::str(path); + let fs = self.rooted(std::slice::from_ref(&text), |i| { + let p = parse_text(i, text.clone(), true)?; + i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs")) + })?; + instance(self, proto, fs) + } + /// The [`crate::Data`] for `id` when it is a `File` the `File` class made (its prototype is /// `File.prototype` and it holds its path in its [`Class::FsEntry`]), as [`file_ref_path`] reads /// it; `None` for any other object, one made with `Object.create(File.prototype)` included. diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index a639dbd0cb..76a36d25c6 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -321,7 +321,7 @@ impl Interp { self.use_fuel()?; self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?; let name = String::from_utf16_lossy(&k); - if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY) { + if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY || name == crate::FOLDER_REF_KEY) { return Err(self.data_error(r, ErrorType::Type, "is not plain data")); } r.path.push(Step::Name(k)); @@ -345,6 +345,14 @@ impl Interp { if depth > self.data_limits.depth { return Err(self.throw(ErrorType::Range, "a host value is nested too deep")); } + // A host member's `File` or `Folder` ([`crate::file_ref`], [`crate::folder_ref`]). + if self.write_hosted + && let Data::Object(items) = &d + && let [(k, Data::String(path))] = items.as_slice() + && (k == crate::FILE_REF_KEY || k == crate::FOLDER_REF_KEY) + { + return self.write_fs_ref(path, k == crate::FOLDER_REF_KEY); + } Ok(match d { Data::Undefined => Value::Undefined, Data::Null => Value::Null, diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 45f6aa61e4..9d32e92b26 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -81,7 +81,7 @@ pub use ast::{ }; pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; -pub use file_classes::{FILE_REF_KEY, file_ref_path}; +pub use file_classes::{FILE_REF_KEY, FOLDER_REF_KEY, file_ref, file_ref_path, folder_ref}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index d17a580560..492bf4eb19 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -130,6 +130,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// `SaveOptions.SAVECHANGES` read at `line`: a `Document.close` given it saves the document to + /// its own file, and the value may reach `close` through a variable or an argument. + fn save_changes(&mut self, line: Option) { + self.acc.feature(FeatureId::FileWrite, line); + self.acc.outside(OutsideId::FilesWritten, line, None); + } + /// A File object's `length`, `hidden` or `readonly` set at `line`: the file changes. fn file_setter(&mut self, line: Option) { self.acc.feature(FeatureId::FileWrite, line); @@ -200,6 +207,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else if of(catalog::FOLDER) && catalog::FOLDER_PLACES.contains(&n) { self.acc.feature(FeatureId::FilePlaces, line); } + if n == catalog::SAVE_CHANGES { + self.save_changes(line); + } if n == catalog::ON_DRAW { self.acc.feature(FeatureId::ScriptuiDrawing, line); } @@ -419,6 +429,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if t.text.contains(catalog::ACTION_TEXT) { self.acc.feature(FeatureId::Actions, line); } + // `SaveOptions['SAVECHANGES']`, or the value written as the string `"SaveOptions.SAVECHANGES"`. + let value = unquote(t.text, 32); + if value == catalog::SAVE_CHANGES + || value.strip_prefix(catalog::SAVE_OPTIONS).and_then(|r| r.strip_prefix('.')) == Some(catalog::SAVE_CHANGES) + { + self.save_changes(line); + } let compares = h0.is_some_and(|s| s.kind == T::Punct && matches!(s.text, "==" | "===" | "!=" | "!==")); if compares && word(h1, "typename") && is(h2, ".") { let name = unquote(t.text, self.acc.limits.echo.saturating_add(1)); diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index a73dd557d6..7ed0a20efd 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -77,6 +77,12 @@ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", " // Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "saveAs"]; +// The save option of `Document.close` that saves the document to its own file: +// https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and +// https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ (SaveOptions). +pub(crate) const SAVE_CHANGES: &str = "SAVECHANGES"; +pub(crate) const SAVE_OPTIONS: &str = "SaveOptions"; + // Application methods that page doesn't list, named in public forum posts: // https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand, // doScript, loadAction, unloadAction) and diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 76d78f822b..1596b37eed 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -543,6 +543,25 @@ fn save_as_and_export_file_write_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } +/// `SaveOptions.SAVECHANGES` makes a document's `close` save it to its own file, read directly, in +/// brackets, as a string or through a variable; closing without it, and the other save options, +/// write nothing. +#[test] +fn closing_with_save_changes_writes_a_file() { + let r = report(concat!( + "app.activeDocument.close();\n", + "app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);\n", + "app.activeDocument.close(SaveOptions.PROMPTTOSAVECHANGES);\n", + "app.activeDocument.close(SaveOptions.SAVECHANGES);\n", + "var how = SaveOptions['SAVECHANGES'];\n", + "documents[0].close(how);\n", + "documents[1].close('SaveOptions.SAVECHANGES');\n", + "var w = new Window('dialog'); w.close(1);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 7][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[4, 5, 7][..])]); +} + /// `saveAs` and `exportFile` called with their names as string literals in brackets write the file /// too; reading the method without calling it does not. #[test] diff --git a/docs/gaps.md b/docs/gaps.md index cecbd9c4c4..46a4d063b5 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -810,7 +810,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's selection and its page items, and save, export and open documents with - `Document.saveAs`, `Document.exportFile` and `app.open`. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + `Document.saveAs`, `Document.exportFile` and `app.open`, read a document's `fullName`, `path` and `saved`, and + close it with `Document.close`. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index 5dd133dc00..ed7af26ab5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2562,7 +2562,8 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, - `outside` lists what the script does outside the document: `filesWritten` (with the open modes used; setting a File object's `length`, `hidden` or `readonly` counts too, on any object that may be a File object; only `new Folder(…)` and the `Folder` places such as `Folder.temp`, other than `Folder.current`, are left out; a - document's `saveAs` or `exportFile` counts too), `filesOpened` (files opened in other apps), `network`, + document's `saveAs` or `exportFile` counts too, and so does `SaveOptions.SAVECHANGES` wherever the script reads it, + since `close` given it saves the document to its file), `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed). - `problems` lists what would stop the script loading as written (strings, comments, regular expressions, @@ -2700,9 +2701,14 @@ app through the global object `vc`, and writes to the Script Console and runs ot https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/); without options the path's extension picks it. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and `exportFile` as `PNG24`, `JPEG` or `SVG` use the defaults a new options object of that class holds. `saveAs` maps `compressed`, `pdfCompatible`, `embedICCProfile` and - `compatibility` (`ILLUSTRATOR17` and `ILLUSTRATOR19`) of `.ai`; `cmykPostScript`, `includeDocumentThumbnails`, - `postScript`, `preview`, `overprint` and `compatibility` of EPS; and `pDFPreset`, `compatibility` (`ACROBAT4` to + `compatibility` (`ILLUSTRATOR17` and `ILLUSTRATOR19`), `saveMultipleArtboards` and `artboardRange` of `.ai`; + `cmykPostScript`, `includeDocumentThumbnails`, `postScript`, `preview`, `overprint`, `compatibility`, + `saveMultipleArtboards` and `artboardRange` of EPS; and `pDFPreset`, `compatibility` (`ACROBAT4` to `ACROBAT8` as PDF 1.3 to 1.7), `artboardRange`, `preserveEditability`, `acrobatLayers` and `compressArt` of PDF. + As the `.ai` and EPS help pages say, `artboardRange` is used only with `saveMultipleArtboards` true, and an + empty range means every artboard. `Document.fullName` is a `File` for the document's file, `Document.saved` is + true when the document has no unsaved changes and can be set, and `Document.close(saveOptions?)` closes the + document with the given `SaveOptions` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). `exportType` is an `ExportType`: `PNG24`, `JPEG` and `SVG` take `new ExportOptionsPNG24()`, `new ExportOptionsJPEG()` and `new ExportOptionsSVG()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/), @@ -2713,7 +2719,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with `pageToOpen` and `pDFCropToBox`. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, - `EPSPostScriptLevelEnum`, `PDFOverprint` and `UserInteractionLevel` hold strings such as `"ExportType.PNG24"`. + `EPSPostScriptLevelEnum`, `PDFOverprint`, `SaveOptions` and `UserInteractionLevel` hold strings such as + `"ExportType.PNG24"`. VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is @@ -2729,7 +2736,26 @@ app through the global object `vc`, and writes to the Script Console and runs ot an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and `parent`), and an `undefined` one is left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default - keeps the preset's value. A bad value throws an error before anything is written. + keeps the preset's value. A `pDFPreset` in square brackets, such as `[Smallest File Size]`, names the built-in + preset of the name inside them; the default preset's name in brackets names VectorCraft Default, and + `[PDF/X-4:2008]` names PDF/X-4:2010. Any other name throws `unknown PDF preset`. `artboardRange` takes + a whole number from 1 as well as a string, read as `String(number)` reads it; any other number throws. With `saveMultipleArtboards` true, a `.ai` range + (every artboard when it is empty) goes to `file.saveAs`'s `separateArtboards`, which also writes each of its + artboards to `-.ai`, and an EPS range goes to `useArtboards`, which writes + `_.eps` for each of two or more artboards beside the file at the path, and for one artboard + writes only the file at the path, holding that artboard. Without `saveMultipleArtboards`, a `.ai` or EPS + `artboardRange` is not checked against the document's artboards, but one that is not written as a range of + artboard numbers (such as `abc` or `0-`) throws. `Document.path` is a `Folder` for the folder of the document's + file. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of + `""`. `fullName` and `path` of a document whose file the automation read roots do not allow throw + `Script file access denied`. Setting `saved` runs `document.setSaved`: `true` records the document as saved + without saving it, so `close()` then closes it, and `false` records it as having unsaved changes; neither adds an + undo step. With unsaved changes, `close` closes without them with `SaveOptions.DONOTSAVECHANGES`; + `SaveOptions.SAVECHANGES` first saves them to the document's file with `file.saveAs`, in the format its extension + names and after the same write-access check of the path as `saveAs`, and throws an error + and leaves the document open when the document has no file (a converted or recovered document included); and + `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws an error and leaves the document open, since a script cannot + show the prompt. A bad value throws an error before anything is written. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -8998,7 +9024,9 @@ document. With no document open they fail with "no document open". `document.act the current one. `document.move {from?, to}` reorders open documents the way dragging a document tab along the tab strip does: `from` defaults to the current document, `to` is the destination index, documents between them shift by one, the current document stays current, and each document keeps its own view (#5663). It is an engine command, so headless and -remote `command_list` both list it. `file.close {index}` on a document other than the current one leaves the current +remote `command_list` both list it. `document.setSaved {index?, saved}` records a document as saved (`true`) or as +having unsaved changes (`false`) without saving it and without an undo step; a script's `Document.saved = value` runs +it. `file.close {index}` on a document other than the current one leaves the current document current, and its tool keeps its state; closing the current document makes the document in the next tab current, or the one before it when it was the last tab. In the desktop app a modified document comes to the front first, to ask whether to save it. diff --git a/docs/roadmap.md b/docs/roadmap.md index 40c4518f52..2ea3d51b15 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -196,7 +196,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) | 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, and save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`; the rest of the script document model (layers, artboards, paths, type 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, 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, type and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (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) | 🟡 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), 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 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 123604eaec..aaf9712151 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 - 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: 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`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents 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/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.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, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.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 3ef4b97983b1b021bcdc74617287d6adbfcd89a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 21:58:26 -0800 Subject: [PATCH 14/69] Scripts: closing with SAVECHANGES keeps the document's format, and an empty artboardRange is refused Document.close(SaveOptions.SAVECHANGES) now saves in the format the document was last saved in, so a PDF saved to a file whose extension names another format stays a PDF. An artboardRange with no parts, such as ',' or ' , ', now throws, as a range used for the save does. --- crates/engine/src/script/dom/save_open.rs | 29 ++++++++++++--------- crates/engine/src/tests/script_save_open.rs | 25 +++++++++++++++++- docs/mcp.md | 4 +-- 3 files changed, 42 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index b2c9a56378..d94122c702 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -260,8 +260,8 @@ fn artboard_files(format: &str, q: &mut Map) -> std::result::Resu Ok(()) } -/// Whether `r` is written as an artboard range, whatever artboards a document has: parts separated -/// by commas, each a number from 1, or two of them joined by `-` or `–` with either one left out +/// Whether `r` is written as an artboard range, whatever artboards a document has: one or more +/// parts separated by commas, each a number from 1, or two of them joined by `-` or `–` with either one left out /// and the first no greater than the second. fn written_as_range(r: &str) -> bool { // A number of digits alone, from 1; past `u64` it counts as the largest. @@ -273,14 +273,16 @@ fn written_as_range(r: &str) -> bool { let n = t.bytes().all(|b| b.is_ascii_digit()).then(|| t.parse::().unwrap_or(u64::MAX))?; (n >= 1).then_some(Some(n)) }; - r.split(',').map(str::trim).filter(|p| !p.is_empty()).all(|part| match part.replace('\u{2013}', "-").split_once('-') { - Some((a, b)) => match (num(a), num(b)) { - (Some(Some(a)), Some(Some(b))) => a <= b, - (Some(a), Some(b)) => a.is_some() || b.is_some(), - _ => false, - }, - None => matches!(num(part), Some(Some(_))), - }) + let mut parts = r.split(',').map(str::trim).filter(|p| !p.is_empty()).peekable(); + parts.peek().is_some() + && parts.all(|part| match part.replace('\u{2013}', "-").split_once('-') { + Some((a, b)) => match (num(a), num(b)) { + (Some(Some(a)), Some(Some(b))) => a <= b, + (Some(a), Some(b)) => a.is_some() || b.is_some(), + _ => false, + }, + None => matches!(num(part), Some(Some(_))), + }) } const AI_KEPT: &[(&str, Default)] = &[ @@ -896,7 +898,7 @@ const NO_FILE_TO_SAVE: &str = /// `document.close(saveOptions?)`: `file.close` of the document. A document without unsaved /// changes closes with any `SaveOptions`. With unsaved changes, `SaveOptions.DONOTSAVECHANGES` /// closes it without them; `SaveOptions.SAVECHANGES` saves them to the document's file with -/// `file.saveAs` in the format its extension names, after the write-access check `saveAs` makes of +/// `file.saveAs` in the format the document was last saved in, after the write-access check `saveAs` makes of /// the path, and then closes it, and throws [`NO_FILE_TO_SAVE`] /// for a document that has no file, a converted or recovered one included; and /// `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws [`UNSAVED_CHANGES`], since a script @@ -907,7 +909,8 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { Some(d) => member(d, "SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"], "saveOptions")?, None => "PROMPTTOSAVECHANGES", }; - let (dirty, file) = super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered))); + let (dirty, file, format) = + super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered), st.format)); if dirty { match how { "DONOTSAVECHANGES" => {} @@ -916,7 +919,7 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { // A refusal names the document, as `fullName` does when the read roots hide its file. let name = super::with_doc(h, doc, |_, st| st.title()); let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?; - let p = json!({"path": plain(real)}); + let p = json!({"path": plain(real), "format": format}); exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &p)))?; } _ => return Err(HostError::Error(UNSAVED_CHANGES.into())), diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 4389838807..478f68855b 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -696,6 +696,29 @@ fn a_document_without_unsaved_changes_closes_with_any_save_options() { let _ = std::fs::remove_dir_all(base); } +/// `close(SaveOptions.SAVECHANGES)` saves in the format the document was last saved in, not the +/// one its file's extension names. +#[test] +fn closing_with_save_changes_keeps_the_documents_format() { + let base = folder("closeformat"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File({d} + '/p.svg'), new PDFSaveOptions());\n\ + vc.run('shape.rectangle', {{x: 20, y: 20, width: 5, height: 5}}); d.close(SaveOptions.SAVECHANGES); vc.log(app.documents.length);" + ), + ); + let bytes = std::fs::read(dir.join("p.svg")).unwrap_or_default(); + assert!(bytes.starts_with(b"%PDF"), "the save on close keeps the PDF format"); + assert!(s.documents().is_empty()); + let _ = std::fs::remove_dir_all(base); +} + /// Setting `Document.saved` records the document's saved state without saving it: `true` lets /// `close()` close a document with edits, and `false` makes an untouched one ask. #[test] @@ -867,7 +890,7 @@ fn save_multiple_artboards_writes_a_file_per_artboard() { ), ); assert!(dir.join("aioff/c.ai").is_file(), "a range past the document's artboards is not used and does not stop the save"); - for bad in ["'abc'", "'0-'", "'3-1'", "'-'", "-1", "2.5", "0"] { + for bad in ["'abc'", "'0-'", "'3-1'", "'-'", "','", "' , '", "-1", "2.5", "0"] { let e = failure( &mut s, &base, diff --git a/docs/mcp.md b/docs/mcp.md index ed7af26ab5..c7757d4464 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2751,8 +2751,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `Script file access denied`. Setting `saved` runs `document.setSaved`: `true` records the document as saved without saving it, so `close()` then closes it, and `false` records it as having unsaved changes; neither adds an undo step. With unsaved changes, `close` closes without them with `SaveOptions.DONOTSAVECHANGES`; - `SaveOptions.SAVECHANGES` first saves them to the document's file with `file.saveAs`, in the format its extension - names and after the same write-access check of the path as `saveAs`, and throws an error + `SaveOptions.SAVECHANGES` first saves them to the document's file with `file.saveAs`, in the format the document + was last saved in and after the same write-access check of the path as `saveAs`, and throws an error and leaves the document open when the document has no file (a converted or recovered document included); and `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws an error and leaves the document open, since a script cannot show the prompt. A bad value throws an error before anything is written. From 9c12aceb6966474b23fbfbf05a02cf2f35df0cf1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 13:20:46 -0800 Subject: [PATCH 15/69] Scripts: format the merged object class list in heap.rs --- crates/js/src/heap.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index b7b0dd4a63..64f16c12a2 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -337,13 +337,9 @@ impl Class { Class::XmlFilter(_) => "Object", Class::Math => "Math", Class::Json => "JSON", - Class::Ordinary - | Class::ForIn(_) - | Class::Host(_) - | Class::FsEntry(_) - | Class::Symbol(_) - | Class::Iterator(_) - | Class::IterRecord(_) => "Object", + Class::Ordinary | Class::ForIn(_) | Class::Host(_) | Class::FsEntry(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => { + "Object" + } Class::Array { .. } => "Array", Class::Function(_) => "Function", Class::Error(_) => "Error", From e2b33969dc64d57f4edc7c012fe41dba921375dd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:48:56 -0800 Subject: [PATCH 16/69] Scripts: the plugin gate test sets held, and catalogs keep main's rows The merge with main added a ScriptGate initializer in the plugin tests that predates the held field. The two script save errors are added in English only; their translations go through craft-i18n. --- crates/engine/src/tests/plugins.rs | 1 + crates/ui-egui/src/i18n/ca.tsv | 2 -- crates/ui-egui/src/i18n/cs.tsv | 2 -- crates/ui-egui/src/i18n/da.tsv | 2 -- crates/ui-egui/src/i18n/de.tsv | 2 -- crates/ui-egui/src/i18n/el.tsv | 2 -- crates/ui-egui/src/i18n/es.tsv | 2 -- crates/ui-egui/src/i18n/fi.tsv | 2 -- crates/ui-egui/src/i18n/fr.tsv | 2 -- crates/ui-egui/src/i18n/hi.tsv | 2 -- crates/ui-egui/src/i18n/hu.tsv | 2 -- crates/ui-egui/src/i18n/id.tsv | 2 -- crates/ui-egui/src/i18n/it.tsv | 2 -- crates/ui-egui/src/i18n/ja.tsv | 2 -- crates/ui-egui/src/i18n/ka.tsv | 2 -- crates/ui-egui/src/i18n/ko.tsv | 2 -- crates/ui-egui/src/i18n/nl.tsv | 2 -- crates/ui-egui/src/i18n/pl.tsv | 2 -- crates/ui-egui/src/i18n/pt-br.tsv | 2 -- crates/ui-egui/src/i18n/ru.tsv | 2 -- crates/ui-egui/src/i18n/sv.tsv | 2 -- crates/ui-egui/src/i18n/tr.tsv | 2 -- crates/ui-egui/src/i18n/uk.tsv | 2 -- crates/ui-egui/src/i18n/vi.tsv | 2 -- crates/ui-egui/src/i18n/zh-hans.tsv | 2 -- crates/ui-egui/src/i18n/zh-hant.tsv | 2 -- 26 files changed, 1 insertion(+), 50 deletions(-) diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 0a255fb3a3..fc3586756f 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2202,6 +2202,7 @@ fn a_script_loads_no_plugin_from_outside_its_folder_through_a_name_that_is_not_t read: ScriptScope::of_folder(&inside), write: ScriptScope::default(), documents: vec![], + held: vec![], linked: Default::default(), also: None, }; diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 70b0e70d00..87f76147b6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6631,8 +6631,6 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file could not be written No s’ha pogut escriure el fitxer de l’script @msg Script file dialogs need a person to answer them Els diàlegs de fitxers de l’script necessiten una persona que els respongui @msg Script file is not open for writing El fitxer de l’script no està obert per escriure-hi -@msg Script file is read-only El fitxer de l’script és només de lectura -@msg Script file is open for writing El fitxer de l’script està obert per escriure-hi @msg Script file name is already in use El nom del fitxer de l’script ja està en ús @msg Script file name must be a name without a folder El nom del fitxer de l’script ha de ser un nom sense carpeta @msg Script file permission can be kept only for a script run from a file El permís de fitxers només es pot conservar per a un script executat des d’un fitxer diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f67e75d6f1..13129a99a0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5416,8 +5416,6 @@ liquify-list-end {0}, {1} {0} a {1} @msg Script file could not be written Soubor skriptu nelze zapsat @msg Script file dialogs need a person to answer them Dialogy souborů skriptu potřebují osobu, která na ně odpoví @msg Script file is not open for writing Soubor skriptu není otevřený pro zápis -@msg Script file is read-only Soubor skriptu je jen pro čtení -@msg Script file is open for writing Soubor skriptu je otevřený pro zápis @msg Script file name is already in use Název souboru skriptu se už používá @msg Script file name must be a name without a folder Název souboru skriptu musí být název bez složky @msg Script file permission can be kept only for a script run from a file Oprávnění k souborům lze zachovat jen pro skript spuštěný ze souboru diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 18030993dc..94df1eb83e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -88,8 +88,6 @@ @msg Script file could not be written Scriptfilen kunne ikke skrives @msg Script file dialogs need a person to answer them Scriptets fildialoger skal besvares af en person @msg Script file is not open for writing Scriptfilen er ikke åben for skrivning -@msg Script file is read-only Scriptfilen er skrivebeskyttet -@msg Script file is open for writing Scriptfilen er åben for skrivning @msg Script file name is already in use Scriptfilens navn er allerede i brug @msg Script file name must be a name without a folder Scriptfilens navn skal være et navn uden en mappe @msg Script file permission can be kept only for a script run from a file Filtilladelsen kan kun beholdes for et script, der køres fra en fil diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 61ccfe0721..0fb57437c4 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4995,8 +4995,6 @@ liquify-list-end {0}, {1} {0} und {1} @msg Script file could not be written Skriptdatei konnte nicht geschrieben werden @msg Script file dialogs need a person to answer them Dateidialoge von Skripten brauchen eine Person, die sie beantwortet @msg Script file is not open for writing Skriptdatei ist nicht zum Schreiben geöffnet -@msg Script file is read-only Skriptdatei ist schreibgeschützt -@msg Script file is open for writing Skriptdatei ist zum Schreiben geöffnet @msg Script file name is already in use Name der Skriptdatei wird bereits verwendet @msg Script file name must be a name without a folder Name der Skriptdatei muss ein Name ohne Ordner sein @msg Script file permission can be kept only for a script run from a file Dateiberechtigung kann nur für ein Skript behalten werden, das aus einer Datei ausgeführt wird diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index dcbd2fd5c3..3bd10eceb1 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2825,8 +2825,6 @@ liquify-list-end {0}, {1} {0} και {1} @msg Script file could not be written Δεν ήταν δυνατή η εγγραφή του αρχείου του σεναρίου @msg Script file dialogs need a person to answer them Τα παράθυρα διαλόγου αρχείων του σεναρίου χρειάζονται ένα άτομο για να απαντήσει @msg Script file is not open for writing Το αρχείο του σεναρίου δεν είναι ανοιχτό για εγγραφή -@msg Script file is read-only Το αρχείο του σεναρίου είναι μόνο για ανάγνωση -@msg Script file is open for writing Το αρχείο του σεναρίου είναι ανοιχτό για εγγραφή @msg Script file name is already in use Το όνομα του αρχείου του σεναρίου χρησιμοποιείται ήδη @msg Script file name must be a name without a folder Το όνομα του αρχείου του σεναρίου πρέπει να είναι όνομα χωρίς φάκελο @msg Script file permission can be kept only for a script run from a file Η άδεια αρχείων μπορεί να διατηρηθεί μόνο για σενάριο που εκτελείται από αρχείο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 37e1a3bd42..7e71c1c191 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5103,8 +5103,6 @@ liquify-list-end {0}, {1} {0}, {1} @msg Script file could not be written No se pudo escribir el archivo del script @msg Script file dialogs need a person to answer them Los cuadros de diálogo de archivo del script necesitan que una persona los responda @msg Script file is not open for writing El archivo del script no está abierto para escritura -@msg Script file is read-only El archivo del script es de solo lectura -@msg Script file is open for writing El archivo del script está abierto para escritura @msg Script file name is already in use El nombre del archivo del script ya está en uso @msg Script file name must be a name without a folder El nombre del archivo del script debe ser un nombre sin carpeta @msg Script file permission can be kept only for a script run from a file El permiso de archivos solo se puede conservar para un script ejecutado desde un archivo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 064d7d6da9..cc6e0d2fd2 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5344,8 +5344,6 @@ liquify-list-end {0}, {1} {0} ja {1} @msg Script file could not be written Komentosarjan tiedostoa ei voitu kirjoittaa @msg Script file dialogs need a person to answer them Komentosarjan tiedostovalintaikkunoihin tarvitaan vastaava henkilö @msg Script file is not open for writing Komentosarjan tiedosto ei ole auki kirjoittamista varten -@msg Script file is read-only Komentosarjan tiedosto on vain luku -tilassa -@msg Script file is open for writing Komentosarjan tiedosto on auki kirjoittamista varten @msg Script file name is already in use Komentosarjan tiedoston nimi on jo käytössä @msg Script file name must be a name without a folder Komentosarjan tiedoston nimen on oltava nimi ilman kansiota @msg Script file permission can be kept only for a script run from a file Tiedostolupa voidaan säilyttää vain tiedostosta suoritetulle komentosarjalle diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3afc56aa93..6bcf110355 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5062,8 +5062,6 @@ liquify-list-end {0}, {1} {0} et {1} @msg Script file could not be written Le fichier du script n’a pas pu être écrit @msg Script file dialogs need a person to answer them Les boîtes de dialogue de fichiers du script ont besoin d’une personne pour y répondre @msg Script file is not open for writing Le fichier du script n’est pas ouvert en écriture -@msg Script file is read-only Le fichier du script est en lecture seule -@msg Script file is open for writing Le fichier du script est ouvert en écriture @msg Script file name is already in use Le nom du fichier du script est déjà utilisé @msg Script file name must be a name without a folder Le nom du fichier du script doit être un nom sans dossier @msg Script file permission can be kept only for a script run from a file L’autorisation d’accès aux fichiers ne peut être conservée que pour un script exécuté depuis un fichier diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 567cf5740c..986e007efc 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7793,8 +7793,6 @@ liquify-list-end {0}, {1} {0} और {1} @msg Script file could not be written स्क्रिप्ट फ़ाइल लिखी नहीं जा सकी @msg Script file dialogs need a person to answer them स्क्रिप्ट के फ़ाइल डायलॉग को उत्तर देने के लिए किसी व्यक्ति की ज़रूरत है @msg Script file is not open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली नहीं है -@msg Script file is read-only स्क्रिप्ट फ़ाइल केवल पढ़ने के लिए है -@msg Script file is open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली है @msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है @msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए @msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index d7b576514a..ec8a60deaf 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5937,8 +5937,6 @@ liquify-list-end {0}, {1} {0} és {1} @msg Script file could not be written A parancsfájl fájlját nem sikerült írni @msg Script file dialogs need a person to answer them A parancsfájl fájlpárbeszédpaneleire egy személynek kell válaszolnia @msg Script file is not open for writing A parancsfájl fájlja nincs írásra megnyitva -@msg Script file is read-only A parancsfájl fájlja csak olvasható -@msg Script file is open for writing A parancsfájl fájlja írásra meg van nyitva @msg Script file name is already in use A parancsfájl fájljának neve már használatban van @msg Script file name must be a name without a folder A parancsfájl fájljának neve mappa nélküli név kell legyen @msg Script file permission can be kept only for a script run from a file A fájlengedély csak fájlból futtatott parancsfájlnál tartható meg diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 8445293d26..3b3069e023 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8815,8 +8815,6 @@ breakText Glyphs Glif @msg Script file could not be written File skrip tidak dapat ditulis @msg Script file dialogs need a person to answer them Dialog file skrip memerlukan orang untuk menjawabnya @msg Script file is not open for writing File skrip tidak dibuka untuk ditulis -@msg Script file is read-only File skrip hanya dapat dibaca -@msg Script file is open for writing File skrip sedang dibuka untuk ditulis @msg Script file name is already in use Nama file skrip sudah digunakan @msg Script file name must be a name without a folder Nama file skrip harus berupa nama tanpa folder @msg Script file permission can be kept only for a script run from a file Izin file skrip hanya dapat disimpan untuk skrip yang dijalankan dari file diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 94715f0eff..8e7959999c 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5133,8 +5133,6 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file could not be written Impossibile scrivere il file dello script @msg Script file dialogs need a person to answer them Le finestre di dialogo dei file dello script richiedono una persona che risponda @msg Script file is not open for writing Il file dello script non è aperto in scrittura -@msg Script file is read-only Il file dello script è di sola lettura -@msg Script file is open for writing Il file dello script è aperto in scrittura @msg Script file name is already in use Il nome del file dello script è già in uso @msg Script file name must be a name without a folder Il nome del file dello script deve essere un nome senza cartella @msg Script file permission can be kept only for a script run from a file Il permesso sui file può essere mantenuto solo per uno script eseguito da un file diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c6e123c242..d14fc0f723 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5968,8 +5968,6 @@ liquify-list-end {0}, {1} {0}、{1} @msg Script file could not be written スクリプトのファイルを書き込めませんでした @msg Script file dialogs need a person to answer them スクリプトのファイルダイアログには応答する人が必要です @msg Script file is not open for writing スクリプトのファイルが書き込み用に開かれていません -@msg Script file is read-only スクリプトのファイルは読み取り専用です -@msg Script file is open for writing スクリプトのファイルが書き込み用に開かれています @msg Script file name is already in use スクリプトのファイル名はすでに使用されています @msg Script file name must be a name without a folder スクリプトのファイル名はフォルダーを含まない名前にしてください @msg Script file permission can be kept only for a script run from a file ファイルの許可を保持できるのは、ファイルから実行したスクリプトだけです diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 47cabd5226..1991d156eb 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8638,8 +8638,6 @@ liquify-list-end {0}, {1} {0} და {1} @msg Script file could not be written სკრიპტის ფაილის ჩაწერა ვერ მოხერხდა @msg Script file dialogs need a person to answer them სკრიპტის ფაილის დიალოგებს სჭირდება ადამიანი, რომელიც უპასუხებს @msg Script file is not open for writing სკრიპტის ფაილი ჩასაწერად გახსნილი არ არის -@msg Script file is read-only სკრიპტის ფაილი მხოლოდ წასაკითხია -@msg Script file is open for writing სკრიპტის ფაილი ჩასაწერად გახსნილია @msg Script file name is already in use სკრიპტის ფაილის სახელი უკვე გამოიყენება @msg Script file name must be a name without a folder სკრიპტის ფაილის სახელი უნდა იყოს სახელი საქაღალდის გარეშე @msg Script file permission can be kept only for a script run from a file ფაილების ნებართვის შენახვა შესაძლებელია მხოლოდ ფაილიდან გაშვებული სკრიპტისთვის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0e2f433152..005f8284ea 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5897,8 +5897,6 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg Script file could not be written 스크립트 파일을 쓸 수 없습니다 @msg Script file dialogs need a person to answer them 스크립트 파일 대화 상자에는 응답할 사람이 필요합니다 @msg Script file is not open for writing 스크립트 파일이 쓰기용으로 열려 있지 않습니다 -@msg Script file is read-only 스크립트 파일이 읽기 전용입니다 -@msg Script file is open for writing 스크립트 파일이 쓰기용으로 열려 있습니다 @msg Script file name is already in use 스크립트 파일 이름이 이미 사용 중입니다 @msg Script file name must be a name without a folder 스크립트 파일 이름은 폴더 없는 이름이어야 합니다 @msg Script file permission can be kept only for a script run from a file 파일 권한은 파일에서 실행한 스크립트에만 유지할 수 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index e9293a7be3..731173eea6 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -90,8 +90,6 @@ @msg Script file could not be written Het scriptbestand kon niet worden geschreven @msg Script file dialogs need a person to answer them Dialoogvensters voor scriptbestanden moeten door een persoon worden beantwoord @msg Script file is not open for writing Het scriptbestand is niet geopend voor schrijven -@msg Script file is read-only Het scriptbestand is alleen-lezen -@msg Script file is open for writing Het scriptbestand is geopend voor schrijven @msg Script file name is already in use De naam van het scriptbestand is al in gebruik @msg Script file name must be a name without a folder De naam van het scriptbestand moet een naam zonder map zijn @msg Script file permission can be kept only for a script run from a file Toestemming voor scriptbestanden kan alleen worden bewaard voor een script dat vanuit een bestand wordt uitgevoerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index e97c78e081..9152459071 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5235,8 +5235,6 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file could not be written Nie można zapisać pliku skryptu @msg Script file dialogs need a person to answer them Okna dialogowe plików skryptu wymagają osoby, która na nie odpowie @msg Script file is not open for writing Plik skryptu nie jest otwarty do zapisu -@msg Script file is read-only Plik skryptu jest tylko do odczytu -@msg Script file is open for writing Plik skryptu jest otwarty do zapisu @msg Script file name is already in use Nazwa pliku skryptu jest już używana @msg Script file name must be a name without a folder Nazwa pliku skryptu musi być nazwą bez folderu @msg Script file permission can be kept only for a script run from a file Uprawnienie do plików można zachować tylko dla skryptu uruchomionego z pliku diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 87f2ac800b..b49b217c8f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6280,8 +6280,6 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file could not be written Não foi possível gravar o arquivo do script @msg Script file dialogs need a person to answer them As caixas de diálogo de arquivo do script precisam de uma pessoa para respondê-las @msg Script file is not open for writing O arquivo do script não está aberto para gravação -@msg Script file is read-only O arquivo do script é somente leitura -@msg Script file is open for writing O arquivo do script está aberto para gravação @msg Script file name is already in use O nome do arquivo do script já está em uso @msg Script file name must be a name without a folder O nome do arquivo do script deve ser um nome sem pasta @msg Script file permission can be kept only for a script run from a file A permissão de arquivos só pode ser mantida para um script executado a partir de um arquivo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index decd022096..eec9216b69 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5128,8 +5128,6 @@ liquify-list-end {0}, {1} {0} и {1} @msg Script file could not be written Не удалось записать файл скрипта @msg Script file dialogs need a person to answer them Для ответа на файловые диалоги скрипта нужен человек @msg Script file is not open for writing Файл скрипта не открыт для записи -@msg Script file is read-only Файл скрипта доступен только для чтения -@msg Script file is open for writing Файл скрипта открыт для записи @msg Script file name is already in use Имя файла скрипта уже используется @msg Script file name must be a name without a folder Имя файла скрипта должно быть именем без папки @msg Script file permission can be kept only for a script run from a file Разрешение на файлы можно сохранить только для скрипта, запущенного из файла diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index f014e5d79e..a4184199a4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5001,8 +5001,6 @@ liquify-list-end {0}, {1} {0} och {1} @msg Script file could not be written Skriptets fil kunde inte skrivas @msg Script file dialogs need a person to answer them Skriptets fildialoger behöver en person som svarar på dem @msg Script file is not open for writing Skriptets fil är inte öppen för skrivning -@msg Script file is read-only Skriptets fil är skrivskyddad -@msg Script file is open for writing Skriptets fil är öppen för skrivning @msg Script file name is already in use Namnet på skriptets fil används redan @msg Script file name must be a name without a folder Namnet på skriptets fil måste vara ett namn utan mapp @msg Script file permission can be kept only for a script run from a file Filbehörighet kan bara behållas för ett skript som körs från en fil diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 78997530b9..6f1d616aca 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4831,8 +4831,6 @@ liquify-list-end {0}, {1} {0} ve {1} @msg Script file could not be written Betiğin dosyası yazılamadı @msg Script file dialogs need a person to answer them Betiğin dosya iletişim kutularının yanıtlanması için bir kişi gerekir @msg Script file is not open for writing Betiğin dosyası yazmak için açık değil -@msg Script file is read-only Betiğin dosyası salt okunur -@msg Script file is open for writing Betiğin dosyası yazmak için açık @msg Script file name is already in use Betiğin dosya adı zaten kullanılıyor @msg Script file name must be a name without a folder Betiğin dosya adı klasör içermeyen bir ad olmalıdır @msg Script file permission can be kept only for a script run from a file Dosya izni yalnızca bir dosyadan çalıştırılan betik için saklanabilir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f13fd4a094..89c20c44a5 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5117,8 +5117,6 @@ liquify-list-end {0}, {1} {0} і {1} @msg Script file could not be written Не вдалося записати файл скрипту @msg Script file dialogs need a person to answer them Для відповіді на файлові діалоги скрипту потрібна людина @msg Script file is not open for writing Файл скрипту не відкрито для запису -@msg Script file is read-only Файл скрипту доступний лише для читання -@msg Script file is open for writing Файл скрипту відкрито для запису @msg Script file name is already in use Ім’я файлу скрипту вже використовується @msg Script file name must be a name without a folder Ім’я файлу скрипту має бути іменем без папки @msg Script file permission can be kept only for a script run from a file Дозвіл на файли можна зберегти лише для скрипту, запущеного з файлу diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 407e46823f..d358d49544 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5627,8 +5627,6 @@ liquify-list-end {0}, {1} {0} và {1} @msg Script file could not be written Không thể ghi tệp của tập lệnh @msg Script file dialogs need a person to answer them Hộp thoại tệp của tập lệnh cần một người trả lời @msg Script file is not open for writing Tệp của tập lệnh chưa được mở để ghi -@msg Script file is read-only Tệp của tập lệnh ở chế độ chỉ đọc -@msg Script file is open for writing Tệp của tập lệnh đang được mở để ghi @msg Script file name is already in use Tên tệp của tập lệnh đã được sử dụng @msg Script file name must be a name without a folder Tên tệp của tập lệnh phải là một tên không có thư mục @msg Script file permission can be kept only for a script run from a file Chỉ có thể giữ quyền truy cập tệp cho tập lệnh chạy từ một tệp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 3c2d9eedda..c48a32148a 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5624,8 +5624,6 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file could not be written 无法写入脚本的文件 @msg Script file dialogs need a person to answer them 脚本的文件对话框需要有人回答 @msg Script file is not open for writing 脚本的文件未以写入方式打开 -@msg Script file is read-only 脚本的文件为只读 -@msg Script file is open for writing 脚本的文件已以写入方式打开 @msg Script file name is already in use 脚本的文件名已被使用 @msg Script file name must be a name without a folder 脚本的文件名必须是不含文件夹的名称 @msg Script file permission can be kept only for a script run from a file 只有从文件运行的脚本才能保留文件权限 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d79d239334..58c451afd6 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2968,8 +2968,6 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file could not be written 無法寫入指令碼的檔案 @msg Script file dialogs need a person to answer them 指令碼的檔案對話框需要有人回應 @msg Script file is not open for writing 指令碼的檔案未以寫入方式開啟 -@msg Script file is read-only 指令碼的檔案為唯讀 -@msg Script file is open for writing 指令碼的檔案已以寫入方式開啟 @msg Script file name is already in use 指令碼的檔案名稱已在使用中 @msg Script file name must be a name without a folder 指令碼的檔案名稱必須是不含資料夾的名稱 @msg Script file permission can be kept only for a script run from a file 只有從檔案執行的指令碼才能保留檔案權限 From 39c5e98a3ef9eeb0174af54c19ca11d068438bc1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 03:15:09 -0800 Subject: [PATCH 17/69] Scripts: refuse unsafe close saves and refused multi-file writes up front - A save of several files whose file access refuses one of them returns the refusal before any file goes to the writer, so a writer that does not check the file access writes nothing. - close(SaveOptions.SAVECHANGES) throws before writing, and leaves the document open, when the document's last save named some of its artboards, since saving with those options again could leave changes out of the file. - The script check no longer treats an object literal's saveAs or exportFile as the script's own when a function body assigns the variable without declaring it, or when the script assigns it as a property of this (the global object in global code and in a function called without a receiver). - The close-with-SAVECHANGES format test reads the saved PDF and checks that it holds the change made after the first save. - docs/mcp.md limits the "none of them is written" sentence for SVG linked images to refusals found before the first write, and documents the new close refusal. --- crates/engine/src/cmd/fileio/save.rs | 11 +++--- crates/engine/src/script/dom/save_open.rs | 26 +++++++++++-- crates/engine/src/tests/script_save_open.rs | 43 ++++++++++++++++++++- crates/scriptcheck/src/analyze.rs | 39 +++++++++++++++++++ crates/scriptcheck/src/analyze/features.rs | 17 +++++++- crates/scriptcheck/src/tests.rs | 40 +++++++++++++++++++ docs/mcp.md | 6 ++- 7 files changed, 168 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index cf00d4194a..7c185352a0 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1071,15 +1071,14 @@ impl SaveJob { return Ok(stopped); } // Every path is checked against the file access in force before the first file is - // written. A refused file goes to `write` first, which refuses it with the error the - // caller gives (naming the path as the caller does), so none of the files is written. + // written. A refused file is not handed to `write`, so a writer that does not check the + // file access writes none of the files; the error is the file access's own refusal, as + // the writers that check it give. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) + && let Some(refused) = files.iter().find_map(|(p, _)| super::may_write(p).err()) { - write(p, bytes)?; - // A writer that does not check the file access writes none of the others. - return Err(super::may_write(p).err().unwrap_or_else(|| crate::EngineError::Other(format!("file access denied: {p}")))); + return Err(refused); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 6400b32f73..8d282ce7bb 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -896,12 +896,29 @@ const UNSAVED_CHANGES: &str = const NO_FILE_TO_SAVE: &str = "the document has unsaved changes and no file to save them to: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; +/// The error `close(SaveOptions.SAVECHANGES)` gives for a document with unsaved changes whose +/// last save named some of its artboards: saving with those options again could leave changes out. +const SAVES_SOME_ARTBOARDS: &str = + "the document was last saved with some of its artboards named: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; + +/// Whether the options `st` was last saved with name artboards (`artboard`, `artboards`, or a +/// `range` other than all of them), so that a save with them may write only some of the artboards. +fn picks_artboards(st: &crate::doc_state::DocState) -> bool { + let options = crate::cmd::fileio::remembered_save_options(st); + crate::cmd::fileio::ARTBOARD_PARAMS.iter().any(|k| match options.get(*k) { + None | Some(Value::Null) => false, + Some(Value::String(r)) if *k == "range" => !(r.trim().is_empty() || r.trim().eq_ignore_ascii_case("all")), + Some(_) => true, + }) +} + /// `document.close(saveOptions?)`: `file.close` of the document. A document without unsaved /// changes closes with any `SaveOptions`. With unsaved changes, `SaveOptions.DONOTSAVECHANGES` /// closes it without them; `SaveOptions.SAVECHANGES` saves them to the document's file with /// `file.saveAs` in the format the document was last saved in, after the write-access check `saveAs` makes of /// the path, and then closes it, and throws [`NO_FILE_TO_SAVE`] -/// for a document that has no file, a converted or recovered one included; and +/// for a document that has no file, a converted or recovered one included, and +/// [`SAVES_SOME_ARTBOARDS`] before writing when the document's last save named some of its artboards; and /// `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws [`UNSAVED_CHANGES`], since a script /// cannot show the prompt. fn doc_close(h: &Host, a: &[Data]) -> Answer { @@ -910,13 +927,16 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { Some(d) => member(d, "SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"], "saveOptions")?, None => "PROMPTTOSAVECHANGES", }; - let (dirty, file, format) = - super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered), st.format)); + let (dirty, file, format, picked) = + super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered), st.format, picks_artboards(st))); if dirty { match how { "DONOTSAVECHANGES" => {} "SAVECHANGES" => { let path = file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?; + if picked { + return Err(HostError::Error(SAVES_SOME_ARTBOARDS.into())); + } // A refusal names the document, as `fullName` does when the read roots hide its file. let name = super::with_doc(h, doc, |_, st| st.title()); let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?; diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index a3f937a244..9ce5c2f820 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -208,7 +208,7 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() { } /// When the writer a save is given does not check the file access itself, a save of several files -/// still writes none of them after the refused one. +/// whose file access refuses one of them hands none of them to the writer. #[test] fn a_refused_file_stops_a_save_whose_writer_does_not_check() { use crate::cmd::fileio::{SaveMode, save_job, save_plan}; @@ -247,7 +247,7 @@ fn a_refused_file_stops_a_save_whose_writer_does_not_check() { }); assert!(r.is_err(), "{r:?}"); let refused = refused.unwrap(); - assert_eq!(written, std::slice::from_ref(&refused), "only the refused file went to the writer"); + assert_eq!(written, Vec::::new(), "no file went to the writer, the refused one ({refused}) included"); let mut perms = std::fs::metadata(&refused).unwrap().permissions(); #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); @@ -722,10 +722,49 @@ fn closing_with_save_changes_keeps_the_documents_format() { ); let bytes = std::fs::read(dir.join("p.svg")).unwrap_or_default(); assert!(bytes.starts_with(b"%PDF"), "the save on close keeps the PDF format"); + let pdf = vectorcraft_pdf::import(&bytes).unwrap(); + let mut sizes = vec![]; + for l in &pdf.layers { + l.walk(&mut |n| sizes.extend(n.geometric_bounds().map(|b| (b.width(), b.height())))); + } + let near = |(w, h): (f64, f64), (x, y): (f64, f64)| (w - x).abs() < 0.01 && (h - y).abs() < 0.01; + assert!(sizes.iter().any(|&s| near(s, (5.0, 5.0))), "the file holds the rectangle drawn after the first save: {sizes:?}"); + assert!(sizes.iter().any(|&s| near(s, (50.0, 20.0))), "and the first one: {sizes:?}"); assert!(s.documents().is_empty()); let _ = std::fs::remove_dir_all(base); } +/// `close(SaveOptions.SAVECHANGES)` on a document whose last save named some of its artboards +/// throws before writing and leaves the document open, so no change is left out of its file. +#[test] +fn closing_with_save_changes_refuses_a_save_of_some_artboards() { + let base = folder("closerange"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});\n\ + var o = new PDFSaveOptions(); o.artboardRange = '2'; d.saveAs(new File({d} + '/r.pdf'), o);\n\ + vc.run('shape.rectangle', {{x: 20, y: 20, width: 5, height: 5}});\n\ + var e = ''; try {{ d.close(SaveOptions.SAVECHANGES); }} catch (x) {{ e = String(x); }} vc.log([e, app.documents.length]);" + ), + ); + assert!(out[0][0].as_str().unwrap().contains("some of its artboards"), "{}", out[0]); + assert_eq!(out[0][1], json!(1), "the document stays open"); + let pdf = vectorcraft_pdf::import(&std::fs::read(dir.join("r.pdf")).unwrap()).unwrap(); + let mut drawn = 0; + for l in &pdf.layers { + l.walk(&mut |n| drawn += usize::from(n.geometric_bounds().is_some_and(|b| (b.width() - 5.0).abs() < 0.01))); + } + assert_eq!(drawn, 0, "the file is left as the first save wrote it"); + assert!(s.active().unwrap().is_dirty(), "the change is still unsaved"); + let _ = std::fs::remove_dir_all(base); +} + /// Setting `Document.saved` records the document's saved state without saving it: `true` lets /// `close()` close a document with edits, and `false` makes an untouched one ask. #[test] diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 8765501507..7a596f5633 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -647,6 +647,12 @@ struct Analyzer<'s, 'a, 'l> { /// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver /// that is not such a variable. index_receiver: u8, + /// The variables that may get another value when code read elsewhere runs: assigned inside a + /// function body that does not declare them, or as a property of `this` ([`Analyzer::reassigned_later`]). + /// None of them joins [`Analyzer::writers`]. + later: HashSet, + /// `later` ran out of room: no variable joins [`Analyzer::writers`]. + later_full: bool, /// This file or what the scan started with gives names values the analysis doesn't read /// ([`Declared::unsure`]): no object counts as a Folder object whatever the path names. unsure: bool, @@ -727,6 +733,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { objects: vec![], closed: None, index_receiver: 0, + later: HashSet::new(), + later_full: false, unsure: known.unsure || declared.unsure, own_names: HashSet::new(), scopes: vec![], @@ -1417,9 +1425,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // A name after `.`, `..`, `.@`, `::` or `@` is a property's or an attribute's; any other // name before `=` is a variable, at the start of a statement or inside an expression. if !member_mark(h1) && !is(h1, "@") { + if !self.scopes.is_empty() && !self.declared_in_body(name.text) { + self.reassigned_later(name.text); + } self.assign = Some(Assign { name: name.text.to_string(), after_new: false }); } } + if let Some((name, _)) = self.updated(t) + && !self.scopes.is_empty() + && !self.declared_in_body(name) + { + self.reassigned_later(name); + } match self.updated(t) { // The value on the right is read at this depth, and the name holds nothing the check // follows once that value ends ([`Analyzer::settle_groups`]). @@ -1435,12 +1452,34 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) + && !self.later_full + && !self.later.contains(&name) && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { self.writers.insert(name, bits); } } + /// `name` may get another value when code read elsewhere runs: a function body assigns it without + /// declaring it, and the function may be called before or after any line, or it is assigned as a + /// property of `this`. Its object literal's methods are no longer known, now or later. + fn reassigned_later(&mut self, name: &str) { + self.writers.remove(name); + if !self.later.contains(name) { + if self.acc.room(self.later.len()) { + self.later.insert(name.to_string()); + } else { + self.later_full = true; + } + } + } + + /// Whether `name` is declared in a function body this token is inside (`var name`, `function + /// name`, a parameter). + fn declared_in_body(&self, name: &str) -> bool { + self.scopes.iter().any(|s| s.saved.get(name).is_some_and(|v| v.local)) + } + /// `t` in an object literal assigned to a variable, `before` the bracket depth before `t`: a single /// function expression directly inside its braces as the whole value of a key that names a /// document method writing a file (`{saveAs: function … {…}, …}`, `{'exportFile': function … {…}}`) diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 48303c173e..9a99338da4 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -376,9 +376,24 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `local[k] = w`, `delete local.saveAs`). fn writer_use(&mut self, t: &Sig<'s>) { let [h0, h1, h2, h3] = self.h; - let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")); let key = t.is(":") && (is(h1, "{") || is(h1, ",")); + // `this.local = …` or `this['local'] = …`: `this` is the global object in the global code and in a + // function called without a receiver (ECMA-262 3rd edition, sections 10.2.1 and 10.2.3), so the + // global variable of that name may get another value. + if changes { + let global = if is(h1, ".") && word(h2, "this") { + h0.filter(|s| s.kind == T::Ident).map(|s| s.text.to_string()) + } else if is(h0, "]") && is(h2, "[") && word(h3, "this") { + h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 64)) + } else { + None + }; + if let Some(name) = global { + self.reassigned_later(&name); + } + } + let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); let escaped = if word(h0, "delete") { // `delete local…` writer(Some(*t), h0) diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 1524d4d7ae..422679f803 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -664,6 +664,46 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..])); } +/// A function body read before the literal that assigns its variable without declaring it may run +/// after the literal, so the literal's `saveAs` keeps reporting the write; a body that declares the +/// name assigns its own variable. +#[test] +fn a_function_read_earlier_that_assigns_the_variable_keeps_save_as_writing() { + let r = report(concat!( + "var f = new File(p);\n", + "function choose() { d = app.activeDocument; }\n", + "var d = {saveAs: function () {}};\n", + "choose(); d.saveAs(f);\n", + "function bump() { e++; }\n", + "var e = {saveAs: function () {}};\n", + "e.saveAs(f);\n", + "function own() { var g; g = app.activeDocument; }\n", + "var g = {saveAs: function () {}};\n", + "g.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..])); +} + +/// Assigning a property of `this`, the global object in the global code and in a function called +/// without a receiver, may give the global variable of that name another value, before or after +/// its literal. +#[test] +fn assigning_a_property_of_this_keeps_save_as_writing() { + let r = report(concat!( + "var f = new File(p);\n", + "var d = {saveAs: function () {}};\n", + "this.d = app.activeDocument;\n", + "d.saveAs(f);\n", + "function swap() { this['e'] = app.activeDocument; }\n", + "var e = {saveAs: function () {}};\n", + "swap(); e.saveAs(f);\n", + "var g = {saveAs: function () {}};\n", + "this.other = 1;\n", + "g.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..])); +} + /// A `saveAs` key's value is a method of the script's own only when the whole value is one function /// expression: a value that goes on after the function's body, and a literal inside another, leave /// `saveAs` writing the file. A literal given to a function body's own variable at the end of the body diff --git a/docs/mcp.md b/docs/mcp.md index 5c2c05d8fe..c3794b55b4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2935,7 +2935,8 @@ other files through `$`: format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with `compressed`), and writes 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. A listed option that is not mapped is accepted at its help page's default, and any other value throws + when the script's folders refuse one of those files, none of them is written; a write that fails once the + first file is in place leaves the files written before it. A listed option that is not mapped is accepted at its help page's default, and any other value throws an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and `parent`), and an `undefined` one is left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default @@ -2956,7 +2957,8 @@ other files through `$`: undo step. With unsaved changes, `close` closes without them with `SaveOptions.DONOTSAVECHANGES`; `SaveOptions.SAVECHANGES` first saves them to the document's file with `file.saveAs`, in the format the document was last saved in and after the same write-access check of the path as `saveAs`, and throws an error - and leaves the document open when the document has no file (a converted or recovered document included); and + and leaves the document open when the document has no file (a converted or recovered document included) or when + its last save named some of its artboards, without writing anything; and `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws an error and leaves the document open, since a script cannot show the prompt. A bad value throws an error before anything is written. - `PageItem.tags` and `Document.tags` are `Tags` collections (https://ai-scripting.docsforadobe.dev/jsobjref/Tags/) From 043650d79453475332245a48cc49ff5055e5a583 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 21:21:56 -0800 Subject: [PATCH 18/69] Scripts: tighten save, open and close edge cases - saveAs picks the encoder from the requested name, so a link to a file of another format writes the format the name asks for. - fullName, path and close(SaveOptions.SAVECHANGES) resolve a relative saved path against the working directory. - close(SAVECHANGES) accepts an artboard range that covers every artboard and keeps the document open when the save would drop artboards. - app.open keeps the requested file name, rejects a file over 128 MiB before reading it, applies the requested color space to plug-in imports, and rejects PDF options for files that are not PDF content; null PDF options keep their defaults. - Explicit null options throw; assigning the current Document.saved value runs no command; Document.path reflects as Folder or string. - An implicit multi-file save names no refused path in its error. - The script checker counts SAVECHANGES only on SaveOptions and keeps write warnings for receivers that evaluated code can rebind. --- crates/engine/src/cmd/fileio.rs | 3 + crates/engine/src/cmd/fileio/access.rs | 31 +- crates/engine/src/cmd/fileio/load.rs | 8 +- crates/engine/src/cmd/fileio/save.rs | 10 +- crates/engine/src/cmd/fileio/svg.rs | 2 +- crates/engine/src/script/dom.rs | 4 +- crates/engine/src/script/dom/save_open.rs | 80 +++-- crates/engine/src/tests/script_save_open.rs | 351 ++++++++++++++++++++ crates/engine/tests/plugin_import.rs | 33 ++ crates/scriptcheck/src/analyze.rs | 4 +- crates/scriptcheck/src/analyze/features.rs | 17 +- crates/scriptcheck/src/tests.rs | 52 +++ docs/mcp.md | 15 +- 13 files changed, 563 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 5f66067142..51d7590f35 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -125,6 +125,7 @@ pub use screens::{ builtin_presets as screen_export_builtin_presets, first_file as screen_first_file, preset_list as screen_export_preset_list, preset_rows as screen_preset_rows, }; +pub(crate) use svg::lost_artboards_warning as svg_lost_artboards_warning; pub use svg::options_map as svg_options; /// Atomic file writes (a temporary file renamed over the target: a failed write never damages the /// file it replaces), for the apps' own writers too. @@ -141,6 +142,8 @@ mod formats; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) use access::{SCRIPT_OPEN_MAX_BYTES, SCRIPT_OPEN_TOO_LARGE}; pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder}; pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with}; diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 8ca1fedcd7..84b8bc1a4f 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -267,14 +267,43 @@ pub(crate) fn may_write(path: &str) -> Result<()> { crate::file_access::check_write(path).map_err(EngineError::Other) } +/// The most a file read during a script command holds, the limit an importer reads. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX_INPUT_BYTES; +/// The error of a file past [`SCRIPT_OPEN_MAX_BYTES`]. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB"; + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_file(path: &str) -> Result> { + use std::io::Read; may_read(path)?; // A device or pipe may never end: only a regular file is read to its end. if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() { return Err(EngineError::Other(format!("{path}: not a file"))); } - std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}"))) + if crate::file_access::in_script_command() { + let max = SCRIPT_OPEN_MAX_BYTES; + let read = || -> std::io::Result> { + let file = std::fs::File::open(path)?; + let meta = file.metadata()?; + if !meta.is_file() { + return Err(std::io::Error::other("not a file")); + } + if meta.len() > max as u64 { + return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE)); + } + let mut bytes = Vec::new(); + file.take(max as u64 + 1).read_to_end(&mut bytes)?; + if bytes.len() > max { + return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE)); + } + Ok(bytes) + }; + read().map_err(|e| EngineError::Other(format!("{path}: {e}"))) + } else { + std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}"))) + } } /// The first `max` bytes of the file at `path` (all of it when it is shorter). Anything but a diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 4f11935db0..e426bd5a23 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -818,7 +818,7 @@ pub fn read_for_open_asking( (linked_pages(name, bytes, path.as_deref(), &opts)?, None) } else { match super::importer::pick(name, bytes, p)? { - Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, None), + Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, opts.color_mode), // The color mode `p` asks for converts the colors after the policies did, through the // profiles the document keeps. None => (load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?, opts.color_mode), @@ -1096,6 +1096,12 @@ pub(super) fn open(s: &mut Session, p: &Value) -> Result { source(p, "document.open")? } }; + if crate::file_access::in_script_command() && ["page", "cropTo"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + let pdf = detect(src.name, &src.bytes).is_some_and(|f| matches!(f.id, "pdf" | "ai" | "ait")) && !vectorcraft_pdf::is_postscript(&src.bytes); + if !pdf { + return Err(bad("document.open", "PDF open options require a PDF file")); + } + } // A relative path is the file in the working directory: its folder is where relative links // are found (a bare file name has no folder of its own). let path = src.path.map(super::absolute_path); diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 7c185352a0..af84199414 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -602,6 +602,7 @@ pub struct SaveJob { stamped: Option, /// The artboards also saved to files of their own (`separateArtboards`). boards: Vec, + redact_paths: bool, } /// Writes the file at a path with what the filler it is given writes into it @@ -963,7 +964,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option 1 - && let Some(refused) = files.iter().find_map(|(p, _)| super::may_write(p).err()) + && let Some(refused) = files + .iter() + .find_map(|(p, _)| super::may_write(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e })) { return Err(refused); } @@ -1240,9 +1243,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8]) /// A save command: plan, then write with the file system (a native file as it is encoded). pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result { let plan = save_plan(s, mode, p)?; - let job = save_job(s, plan)?; + let mut job = save_job(s, plan)?; let uid = s.doc()?.uid; let given = str_param(p, "path").is_some_and(|g| !g.is_empty()); + job.redact_paths = !given; // Without a path, the files written are the document's own file and those beside it. let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) }) diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index 066c6fc63f..e5ecc858dc 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -172,7 +172,7 @@ pub(super) fn drawn<'a>(doc: &'a Document, p: &Value) -> Option Option { +pub(crate) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> Option { let n = doc.artboards.len(); let preserved = plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing); (n > 1 && !preserved).then(|| { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index f50dbad41d..6cbf460954 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2751,9 +2751,7 @@ fn classes(link: &Link) -> Vec { ("toString", method(l, doc_to_string), returns("string", &[])), ]); document.extend( - ["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer"] - .into_iter() - .map(|m| later(l, "Document", m)), + ["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m)), ); document.extend(save_open::document_members(l)); document.extend(variables::document_members(l)); diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 8654d46d7e..bf49aae883 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -43,7 +43,8 @@ //! - `Document.path` is a `Folder` for the folder of the document's file. A document that has no //! file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. //! `fullName` and `path` of a document whose file the automation read roots do not allow throw -//! `Script file access denied`. Setting `Document.saved` runs `document.setSaved`. +//! `Script file access denied`. Changing `Document.saved` runs `document.setSaved`. +//! Assigning its current value runs no command. //! - `Document.close` with unsaved changes closes without them with //! `SaveOptions.DONOTSAVECHANGES`, and saves them to the document's file first with //! `SaveOptions.SAVECHANGES`, which throws for a document that has no file (a converted or @@ -52,6 +53,9 @@ //! - `app.open(file, documentColorSpace?, options?)` takes `options` as a `PDFFileOptions` record: //! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. Any other property //! but `typename` and `parent` throws the same error, unless it is `undefined`. +//! Page and crop options require PDF content, including PDF-compatible `.ai` and `.ait` files. +//! Built-in file reads by script commands reject files over 8 MiB and cap the read at 8 MiB plus one byte. +//! - Optional arguments use defaults when omitted or `undefined`; explicit `null` throws a type error. //! - `app.userInteractionLevel` starts at `UserInteractionLevel.DISPLAYALERTS` in each run. The //! commands a script runs never show a dialog, so the level does not change what they do, and it //! never allows a file the script's grants do not. @@ -696,7 +700,7 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; let path = file_path(arg(a, 1), "saveAs")?; let mut p = Map::new(); - let given_options = given(arg(a, 2)).filter(|d| !matches!(d, Data::Null)); + let given_options = given(arg(a, 2)); // Without options, a path ending in `.ai`, `.eps` or `.pdf` takes the defaults a new options // object of that format's class holds. let extension = path.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).map(|(_, e)| e.to_ascii_lowercase()); @@ -718,6 +722,9 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { } else if !q.is_empty() { p.insert("options".into(), Value::Object(q)); } + } else { + let format = crate::cmd::fileio::format_for_name(path).map_or_else(|| super::with_doc(h, doc, |_, st| st.format), |f| f.id); + p.insert("format".into(), json!(format)); } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); @@ -742,7 +749,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { let path = file_path(arg(a, 1), "exportFile")?; let kind = export_kind(arg(a, 2))?; // Without options, an export takes the defaults a new options object of its class holds. - let mut p = match given(arg(a, 3)).filter(|d| !matches!(d, Data::Null)) { + let mut p = match given(arg(a, 3)) { None => match kind.options { Some(class) => options_params(class, &fresh(class))?, None => Map::new(), @@ -784,11 +791,11 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { fn app_open(h: &Host, a: &[Data]) -> Answer { let path = file_path(arg(a, 1), "open")?; let mut p = Map::new(); - if let Some(d) = given(arg(a, 2)).filter(|d| !matches!(d, Data::Null)) { + if let Some(d) = given(arg(a, 2)) { let mode = if member(d, "DocumentColorSpace", &["CMYK", "RGB"], "documentColorSpace")? == "RGB" { "rgb" } else { "cmyk" }; p.insert("colorMode".into(), json!(mode)); } - if let Some(o) = given(arg(a, 3)).filter(|d| !matches!(d, Data::Null)) { + if let Some(o) = given(arg(a, 3)) { let Data::Object(items) = o else { return Err(HostError::Type("open's options must be a PDFFileOptions record".into())) }; if typename(o).is_some_and(|t| t != "PDFFileOptions") { return Err(HostError::Type("open's options must be a PDFFileOptions record".into())); @@ -819,8 +826,11 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { } } } - let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; - p.insert("path".into(), json!(plain(real))); + if p.contains_key("cropTo") { + p.insert("editingData".into(), json!(false)); + } + h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; + p.insert("path".into(), json!(plain(std::path::PathBuf::from(path)))); let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?; let index = match &r { Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { @@ -837,12 +847,23 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { /// The document's file, `None` for a document that has none, or `Script file access denied` with /// the document's name when the automation read roots do not allow the file to be named /// ([`crate::file_access::check_read`]), as `app.getIsFileOpen` reads them. -fn shown_file(st: &crate::DocState) -> std::result::Result, HostError> { - match st.path.as_deref() { +fn shown_file(st: &crate::DocState) -> std::result::Result, HostError> { + let path = st.path.as_deref().map(absolute_file).transpose()?; + match path.as_deref() { Some(p) if crate::file_access::check_read(p).is_err() => { Err(HostError::Error(format!("{}: {}", super::super::files::ACCESS_DENIED, st.title()))) } - p => Ok(p), + _ => Ok(path), + } +} + +fn absolute_file(path: &str) -> std::result::Result { + let path = std::path::Path::new(path); + if path.is_absolute() { + Ok(path.to_string_lossy().into_owned()) + } else { + let cwd = std::env::current_dir().map_err(|e| HostError::Error(e.to_string()))?; + Ok(cwd.join(path).to_string_lossy().into_owned()) } } @@ -852,7 +873,7 @@ fn doc_full_name(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; super::with_doc(h, doc, |_, st| { Ok(match shown_file(st)? { - Some(p) => vectorcraft_js::file_ref(p), + Some(p) => vectorcraft_js::file_ref(&p), None => vectorcraft_js::file_ref(&st.title()), }) }) @@ -864,7 +885,7 @@ fn doc_path(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; let folder = super::with_doc(h, doc, |_, st| { Ok(shown_file(st)?.and_then(|p| { - let parent = std::path::Path::new(p).parent()?.to_string_lossy().into_owned(); + let parent = std::path::Path::new(&p).parent()?.to_string_lossy().into_owned(); (!parent.is_empty()).then_some(parent) })) })?; @@ -882,6 +903,9 @@ fn doc_saved(h: &Host, a: &[Data]) -> Answer { fn doc_set_saved(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; let saved = boolean(arg(a, 1), "Document.saved")?; + if saved == super::with_doc(h, doc, |_, st| !st.is_dirty()) { + return Ok(Data::Undefined); + } command(h, "document.setSaved", &json!({"index": doc.index, "saved": saved}))?; Ok(Data::Undefined) } @@ -897,19 +921,23 @@ const NO_FILE_TO_SAVE: &str = "the document has unsaved changes and no file to save them to: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; /// The error `close(SaveOptions.SAVECHANGES)` gives for a document with unsaved changes whose -/// last save named some of its artboards: saving with those options again could leave changes out. +/// save would keep only some of its artboards. const SAVES_SOME_ARTBOARDS: &str = - "the document was last saved with some of its artboards named: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; + "the save would keep only some of its artboards: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; -/// Whether the options `st` was last saved with name artboards (`artboard`, `artboards`, or a -/// `range` other than all of them), so that a save with them may write only some of the artboards. +/// Whether saving `st` with its remembered options would omit artboards. fn picks_artboards(st: &crate::doc_state::DocState) -> bool { - let options = crate::cmd::fileio::remembered_save_options(st); - crate::cmd::fileio::ARTBOARD_PARAMS.iter().any(|k| match options.get(*k) { - None | Some(Value::Null) => false, - Some(Value::String(r)) if *k == "range" => !(r.trim().is_empty() || r.trim().eq_ignore_ascii_case("all")), - Some(_) => true, - }) + let options = Value::Object(crate::cmd::fileio::remembered_save_options(st)); + if matches!(st.format, "svg" | "svgz") && crate::cmd::fileio::svg_lost_artboards_warning(&st.doc, &options, st.format).is_some() { + return true; + } + let count = st.doc.artboards.len(); + let pick = serde_json::from_value::(options); + match pick.map_err(|e| e.to_string()).and_then(|p| p.resolve(count)) { + Ok(None) => false, + Ok(Some(indices)) => (0..count).any(|i| !indices.contains(&i)), + Err(_) => true, + } } /// `document.close(saveOptions?)`: `file.close` of the document. A document without unsaved @@ -918,12 +946,12 @@ fn picks_artboards(st: &crate::doc_state::DocState) -> bool { /// `file.saveAs` in the format the document was last saved in, after the write-access check `saveAs` makes of /// the path, and then closes it, and throws [`NO_FILE_TO_SAVE`] /// for a document that has no file, a converted or recovered one included, and -/// [`SAVES_SOME_ARTBOARDS`] before writing when the document's last save named some of its artboards; and +/// [`SAVES_SOME_ARTBOARDS`] before writing when the save would omit artboards; and /// `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws [`UNSAVED_CHANGES`], since a script /// cannot show the prompt. fn doc_close(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; - let how = match given(arg(a, 1)).filter(|d| !matches!(d, Data::Null)) { + let how = match given(arg(a, 1)) { Some(d) => member(d, "SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"], "saveOptions")?, None => "PROMPTTOSAVECHANGES", }; @@ -933,7 +961,7 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { match how { "DONOTSAVECHANGES" => {} "SAVECHANGES" => { - let path = file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?; + let path = absolute_file(&file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?)?; if picked { return Err(HostError::Error(SAVES_SOME_ARTBOARDS.into())); } @@ -974,7 +1002,7 @@ pub(super) fn document_members(l: &Link) -> Vec { ("saveAs", method(l, doc_save_as), returns("undefined", &[("saveIn", "File"), ("options", "*")])), ("exportFile", method(l, doc_export_file), returns("undefined", &[("exportFile", "File"), ("exportFormat", "ExportType"), ("options", "*")])), ("fullName", get(l, doc_full_name), typed("File")), - ("path", get(l, doc_path), typed("File")), + ("path", get(l, doc_path), typed("Folder|string")), ("saved", property(l, doc_saved, doc_set_saved), typed("boolean")), ("close", method(l, doc_close), returns("undefined", &[("saveOptions", "SaveOptions")])), ]) diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 9ce5c2f820..8c09da874c 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -93,6 +93,92 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn relative_saved_paths_use_the_process_working_directory() { + let cwd = crate::cmd::findfiles::plain(std::fs::canonicalize(std::env::current_dir().unwrap()).unwrap()); + let relative_base = PathBuf::from(format!("vc-script-relative-save-{}", std::process::id())); + let base = cwd.join(&relative_base); + std::fs::create_dir_all(base.join("main")).unwrap(); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let file = dir.join("relative.svg"); + let relative = file.strip_prefix(&cwd).unwrap(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("file.saveAs", &json!({"path": relative.to_string_lossy()})).unwrap(); + let before = std::fs::read(&file).unwrap(); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; Folder.current = new Folder({main}); var d = app.activeDocument;\n\ + vc.log([d.fullName.fsName === new File({file}).fsName, d.path.fsName === new Folder({dir}).fsName]);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + d.close(SaveOptions.SAVECHANGES); vc.log(app.documents.length);", + main = quoted(&base.join("main")), + file = quoted(&file), + dir = quoted(&dir), + ), + ); + assert_eq!(out, json!([[true, true], 0])); + assert_ne!(std::fs::read(&file).unwrap(), before); + let _ = std::fs::remove_dir_all(base); +} + +#[cfg(unix)] +#[test] +fn save_as_uses_the_link_name_extension_for_the_encoder() { + let base = folder("linkformat"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let target = dir.join("drawing.vectorcraft"); + std::fs::write(&target, b"").unwrap(); + std::os::unix::fs::symlink(&target, dir.join("drawing.svg")).unwrap(); + s.execute("file.new", &json!({})).unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("drawing.svg")))); + assert!(std::fs::read_to_string(&target).unwrap().contains("").unwrap(); + std::os::unix::fs::symlink(&target, &link).unwrap(); + let out = logged(&mut s, &base, &format!("Folder.userData; var d = app.open(new File({})); vc.log([d.name, d.fullName.name]);", quoted(&link))); + assert_eq!(out, json!([["drawing.svg", "drawing.svg"]])); + assert_eq!(s.active().unwrap().format, "svg"); + let _ = std::fs::remove_dir_all(base); +} + /// Without options, a save or export writes what an untouched new options object of its class gives. #[test] fn omitted_options_are_a_new_options_objects_defaults() { @@ -633,6 +719,121 @@ fn open_takes_the_page_and_crop_box_of_its_options() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn crop_only_options_apply_to_an_editable_pdf() { + let base = folder("pdfcroponly"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let pdf = dir.join("editable.pdf"); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + s.execute( + "file.saveAs", + &json!({"path": pdf.to_string_lossy(), "preserveEditing": true, + "bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}), + ) + .unwrap(); + assert!(vectorcraft_pdf::editing(&std::fs::read(&pdf).unwrap()).is_some_and(|e| e.intact)); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&pdf))); + let original = s.active().unwrap().doc.artboards[0].rect; + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pDFCropToBox: PDFBoxType.PDFMEDIABOX}});", quoted(&pdf))); + let cropped = s.active().unwrap().doc.artboards[0].rect; + assert!(cropped.width() > original.width() && cropped.height() > original.height()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_document_open_rejects_files_over_the_read_limit() { + let base = folder("openreadlimit"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let file = dir.join("large.svg"); + std::fs::write(&file, b"").unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&file))); + let count = s.documents().len(); + std::fs::OpenOptions::new().write(true).open(&file).unwrap().set_len(crate::cmd::fileio::SCRIPT_OPEN_MAX_BYTES as u64 + 1).unwrap(); + let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&file))); + assert!(e.contains(crate::cmd::fileio::SCRIPT_OPEN_TOO_LARGE), "{e}"); + assert_eq!(s.documents().len(), count); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn pdf_open_options_reject_other_detected_formats() { + let base = folder("pdfoptionsformat"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let native = dir.join("native.pdf"); + s.execute("file.saveAs", &json!({"path": native.to_string_lossy(), "format": "vectorcraft"})).unwrap(); + let svg = dir.join("drawing.pdf"); + std::fs::write(&svg, b"").unwrap(); + let count = s.documents().len(); + let uid = s.active().unwrap().uid; + for file in [&native, &svg] { + for options in ["{pageToOpen: 2}", "{pDFCropToBox: PDFBoxType.PDFMEDIABOX}"] { + let script = format!("Folder.userData; app.open(new File({}), undefined, {options});", quoted(file)); + let e = failure(&mut s, &base, &script); + assert!(e.contains("PDF open options require a PDF file"), "{e}"); + assert_eq!(s.documents().len(), count); + assert_eq!(s.active().unwrap().uid, uid); + } + } + let pdf = dir.join("actual.svg"); + s.execute("file.saveCopy", &json!({"path": pdf.to_string_lossy(), "format": "pdf"})).unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 1}});", quoted(&pdf))); + assert_eq!(s.documents().len(), count + 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_document_open_treats_null_pdf_options_as_omitted() { + let base = folder("nullpdfdefaults"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({})).unwrap(); + for extension in ["svg", "vectorcraft"] { + let file = dir.join(format!("drawing.{extension}")); + s.execute("file.saveAs", &json!({"path": file.to_string_lossy()})).unwrap(); + for options in ["page: null", "cropTo: null", "page: null, cropTo: null"] { + let count = s.documents().len(); + logged(&mut s, &base, &format!("Folder.userData; vc.run('document.open', {{path: {}, {options}}});", quoted(&file))); + assert_eq!(s.documents().len(), count + 1, "{extension}: {options}"); + assert_eq!(s.active().unwrap().doc.artboards.len(), 1); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn explicit_null_options_do_not_save_export_open_or_close() { + let base = folder("nulloptions"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let file = dir.join("existing.svg"); + let original = b""; + std::fs::write(&file, original).unwrap(); + let f = format!("new File({})", quoted(&file)); + for call in [ + format!("app.activeDocument.saveAs({f}, null);"), + format!("app.activeDocument.exportFile({f}, ExportType.SVG, null);"), + format!("app.open({f}, null);"), + format!("app.open({f}, undefined, null);"), + "app.activeDocument.close(null);".into(), + ] { + let e = failure(&mut s, &base, &format!("Folder.userData; {call}")); + assert!(e.contains("TypeError"), "{call}: {e}"); + assert_eq!(std::fs::read(&file).unwrap(), original, "{call}"); + assert_eq!(s.documents().len(), 1, "{call}"); + assert!(!s.active().unwrap().is_dirty(), "{call}"); + } + logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs({f}, undefined);")); + assert_ne!(std::fs::read(&file).unwrap(), original); + logged(&mut s, &base, "Folder.userData; app.activeDocument.close(undefined);"); + assert!(s.documents().is_empty()); + let _ = std::fs::remove_dir_all(base); +} + /// `fullName` and `path` name the document's file and folder once it has one, `saved` follows its /// changes, and `close` with `SaveOptions.DONOTSAVECHANGES` closes it. #[test] @@ -765,6 +966,109 @@ fn closing_with_save_changes_refuses_a_save_of_some_artboards() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn closing_with_save_changes_accepts_a_range_covering_all_current_artboards() { + let base = folder("closefullrange"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + for (name, range, boards) in [("one", "1", 1), ("two", "1-2", 2)] { + let file = dir.join(format!("{name}.pdf")); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": boards})).unwrap(); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.activeDocument, o = new PDFSaveOptions(); o.artboardRange = '{range}';\n\ + d.saveAs(new File({}), o);", + quoted(&file), + ), + ); + let before = std::fs::read(&file).unwrap(); + logged( + &mut s, + &base, + "Folder.userData; vc.run('shape.rectangle', {x: 10, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(s.documents().is_empty()); + assert_ne!(std::fs::read(&file).unwrap(), before); + } + s.execute("file.new", &json!({})).unwrap(); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PDFSaveOptions(); o.artboardRange = '1'; app.activeDocument.saveAs(new File({}), o);\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});", + quoted(&dir.join("grown.pdf")), + ), + ); + let before = std::fs::read(dir.join("grown.pdf")).unwrap(); + let e = failure(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.SAVECHANGES);"); + assert!(e.contains("some of its artboards"), "{e}"); + assert_eq!(s.documents().len(), 1); + assert_eq!(std::fs::read(dir.join("grown.pdf")).unwrap(), before); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn closing_with_save_changes_refuses_svg_artboard_loss_before_writing() { + let base = folder("closesvgboards"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + for extension in ["svg", "svgz"] { + for preserve in [false, true] { + let file = dir.join(format!("drawing-{preserve}.{extension}")); + let path = quoted(&file); + let save = if preserve { + format!("vc.run('file.saveAs', {{path: {path}, preserveEditing: true}});") + } else { + format!("d.saveAs(new File({path}));") + }; + logged(&mut s, &base, &format!("Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 100, 50); {save}")); + let before = std::fs::read(&file).unwrap(); + logged(&mut s, &base, "Folder.userData; vc.run('artboard.new', {x: 300, y: 0, width: 60, height: 80});"); + let uid = s.active().unwrap().uid; + if preserve { + logged(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.SAVECHANGES);"); + assert!(s.documents().is_empty()); + assert_ne!(std::fs::read(&file).unwrap(), before); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}));")); + assert_eq!(s.active().unwrap().doc.artboards.len(), 2); + } else { + let e = failure(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.SAVECHANGES);"); + assert!(e.contains("some of its artboards"), "{extension}: {e}"); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.active().unwrap().uid, uid); + assert_eq!(s.active().unwrap().doc.artboards.len(), 2); + assert!(s.active().unwrap().is_dirty()); + assert_eq!(std::fs::read(&file).unwrap(), before); + } + logged(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);"); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn document_path_reflection_describes_folders_and_unsaved_strings() { + let base = folder("pathreflection"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add();\n\ + vc.log([d.reflect.find('path').dataType, d.path === '']);\n\ + d.saveAs(new File({})); vc.log([d.reflect.find('path').dataType, d.path instanceof Folder ? 'Folder' : typeof d.path]);\n\ + vc.log([d.path instanceof Folder, d.path.fsName]);", + quoted(&dir.join("saved.svg")), + ), + ); + assert_eq!(out, json!([["Folder|string", true], ["Folder|string", "Folder"], [true, dir.to_string_lossy()]])); + let _ = std::fs::remove_dir_all(base); +} + /// Setting `Document.saved` records the document's saved state without saving it: `true` lets /// `close()` close a document with edits, and `false` makes an untouched one ask. #[test] @@ -794,6 +1098,24 @@ fn setting_saved_records_the_saved_state() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn unchanged_saved_assignments_do_not_record_commands() { + let base = folder("savednoop"); + let mut s = session(&base); + let out = logged( + &mut s, + &base, + "var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + d.saved = d.saved; d.saved = true; vc.log(d.saved);\n\ + d.saved = false; d.saved = d.saved; d.saved = false; vc.log(d.saved);\n\ + d.saved = true; d.saved = d.saved; vc.log(d.saved);", + ); + assert_eq!(out, json!([true, false, true])); + let changes: Vec<_> = s.journal.iter().filter(|(id, _)| id == "document.setSaved").map(|(_, p)| p["saved"].clone()).collect(); + assert_eq!(changes, [json!(false), json!(true)]); + let _ = std::fs::remove_dir_all(base); +} + /// With automation read roots that leave out the document's file, `fullName` and `path` throw /// instead of naming another file. #[test] @@ -831,6 +1153,35 @@ fn full_name_and_path_leave_out_a_file_outside_the_read_roots() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn implicit_multifile_save_redacts_preflight_refusals_before_writing() { + let base = folder("savepreflight"); + let mut s = session(&base); + let hidden = base.join("private-save-directory"); + std::fs::create_dir_all(&hidden).unwrap(); + let path = hidden.join("drawing.vectorcraft"); + s.execute("file.new", &json!({"artboards": 2})).unwrap(); + let saved = s.execute("document.save", &json!({"path": path.to_string_lossy(), "separateArtboards": true})).unwrap(); + let files: Vec<_> = saved["files"].as_array().unwrap().iter().map(|p| PathBuf::from(p.as_str().unwrap())).collect(); + assert!(files.len() > 1); + let before: Vec<_> = files.iter().map(|p| std::fs::read(p).unwrap()).collect(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 5, "height": 5})).unwrap(); + let main = base.join("main"); + let roots = crate::file_access::AutomationRoots::new(&[&main], &[&main]).unwrap().unwrap(); + let e = crate::file_access::confine(Some(&roots), || s.execute("document.save", &json!({}))).unwrap_err().to_string(); + assert!(e.contains("automation path rejected"), "{e}"); + assert!(!e.contains("private-save-directory"), "{e}"); + assert!(!e.contains(path.to_string_lossy().as_ref()), "{e}"); + assert!(s.active().unwrap().is_dirty()); + for (file, bytes) in files.iter().zip(before) { + assert_eq!(std::fs::read(file).unwrap(), bytes); + } + let explicit = + crate::file_access::confine(Some(&roots), || s.execute("document.save", &json!({"path": path.to_string_lossy()}))).unwrap_err().to_string(); + assert!(explicit.contains(path.to_string_lossy().as_ref()), "{explicit}"); + let _ = std::fs::remove_dir_all(base); +} + /// A `pDFPreset` in square brackets names the built-in preset of the name inside them, and a name /// that is not a preset either way is refused. #[test] diff --git a/crates/engine/tests/plugin_import.rs b/crates/engine/tests/plugin_import.rs index 11a42a6f90..1327e57208 100644 --- a/crates/engine/tests/plugin_import.rs +++ b/crates/engine/tests/plugin_import.rs @@ -88,6 +88,39 @@ fn path_of(p: &std::path::Path) -> String { p.to_string_lossy().into_owned() } +#[test] +fn scripted_open_converts_importer_output_to_the_requested_color_space() { + let mut s = Session::new(); + install(&mut s, &tpl::returning(&tpl::importer("test.scriptcolorspace", r#"["tscmyk"]"#, "{}"), RECT)); + let dir = tmp_dir("scriptcolorspace"); + s.attach_script_data(dir.join("settings/Script Data")); + let file = dir.join("drawing.tscmyk"); + std::fs::write(&file, b"importer input").unwrap(); + let script = dir.join("main.jsx"); + let path = serde_json::to_string(&file.to_string_lossy()).unwrap(); + for (argument, mode) in [ + ("", vectorcraft_doc::ColorMode::Rgb), + (", DocumentColorSpace.CMYK", vectorcraft_doc::ColorMode::Cmyk), + (", DocumentColorSpace.RGB", vectorcraft_doc::ColorMode::Rgb), + ] { + std::fs::write(&script, format!("Folder.userData; var d = app.open(new File({path}){argument}); vc.log(d.documentColorSpace);")).unwrap(); + let count = s.documents().len(); + let out = s.execute("script.run", &json!({"path": script.to_string_lossy()})).unwrap(); + assert_eq!(s.documents().len(), count + 1); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.color_mode, mode, "{argument}: {out}"); + let color = doc.layers[0].children().unwrap()[0].appearance.fill_paint().color().unwrap(); + if mode == vectorcraft_doc::ColorMode::Cmyk { + assert!(matches!(color, vectorcraft_color::Color::Cmyk { .. }), "{color:?}"); + assert_eq!(out["log"], json!(["DocumentColorSpace.CMYK"])); + } else { + assert!(matches!(color, vectorcraft_color::Color::Rgb { .. }), "{color:?}"); + assert_eq!(out["log"], json!(["DocumentColorSpace.RGB"])); + } + } + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn an_importer_adds_a_read_only_format_while_it_is_installed() { let mut s = Session::new(); diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 7a596f5633..4ad90a30a8 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -1474,10 +1474,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } - /// Whether `name` is declared in a function body this token is inside (`var name`, `function + /// Whether `name` is declared in the innermost function body (`var name`, `function /// name`, a parameter). fn declared_in_body(&self, name: &str) -> bool { - self.scopes.iter().any(|s| s.saved.get(name).is_some_and(|v| v.local)) + self.scopes.last().is_some_and(|s| s.saved.get(name).is_some_and(|v| v.local)) } /// `t` in an object literal assigned to a variable, `before` the bracket depth before `t`: a single diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 9a99338da4..bf808469e5 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -208,7 +208,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else if of(catalog::FOLDER) && catalog::FOLDER_PLACES.contains(&n) { self.acc.feature(FeatureId::FilePlaces, line); } - if n == catalog::SAVE_CHANGES { + if n == catalog::SAVE_CHANGES && of(catalog::SAVE_OPTIONS) { self.save_changes(line); } if n == catalog::ON_DRAW { @@ -283,6 +283,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { "]" if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) => { let name = h0.map(|s| unquote(s.text, 16)).unwrap_or_default(); self.setter(&name, h2, h3, line); + if name == catalog::SAVE_CHANGES + && word(h2, catalog::SAVE_OPTIONS) + && !member_mark(h3) + && !self.own_names.contains(catalog::SAVE_OPTIONS) + { + self.save_changes(line); + } } // `local['saveAs']`: what the object before the bracket defines, for a call that may follow. "[" => self.index_receiver = self.writer_bits(h0, h1), @@ -364,7 +371,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// 0 for anything else. A receiver the check does not follow may be a document. fn writer_bits(&self, receiver: Option>, before: Option>) -> u8 { match receiver { - Some(r) if r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0), + Some(r) if !self.unsure && r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0), _ => 0, } } @@ -447,11 +454,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if t.text.contains(catalog::ACTION_TEXT) { self.acc.feature(FeatureId::Actions, line); } - // `SaveOptions['SAVECHANGES']`, or the value written as the string `"SaveOptions.SAVECHANGES"`. + // The value written as the string `"SaveOptions.SAVECHANGES"`. let value = unquote(t.text, 32); - if value == catalog::SAVE_CHANGES - || value.strip_prefix(catalog::SAVE_OPTIONS).and_then(|r| r.strip_prefix('.')) == Some(catalog::SAVE_CHANGES) - { + if value.strip_prefix(catalog::SAVE_OPTIONS).and_then(|r| r.strip_prefix('.')) == Some(catalog::SAVE_CHANGES) { self.save_changes(line); } let compares = h0.is_some_and(|s| s.kind == T::Punct && matches!(s.text, "==" | "===" | "!=" | "!==")); diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index b609217756..236bede7ce 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -573,6 +573,19 @@ fn export_variables_in_brackets_writes_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } +#[test] +fn evaluated_code_keeps_warnings_for_rebound_writer_receivers() { + for call in ["local.exportVariables(f);", "local['exportVariables'](f);", "local.saveAs(f);", "local['exportFile'](f);"] { + let r = report(&format!( + "var local = {{exportVariables: function () {{}}, saveAs: function () {{}}, exportFile: function () {{}}}};\n\ + eval('local = app.activeDocument');\n{call}\n" + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]), "{call}"); + let written = r.outside.iter().find(|o| o.id == "filesWritten"); + assert_eq!(written.map(|o| o.lines.as_slice()), Some(&[3][..]), "{call}"); + } +} + /// `SaveOptions.SAVECHANGES` makes a document's `close` save it to its own file, read directly, in /// brackets, as a string or through a variable; closing without it, and the other save options, /// write nothing. @@ -592,6 +605,24 @@ fn closing_with_save_changes_writes_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[4, 5, 7][..])]); } +#[test] +fn unrelated_save_changes_properties_and_strings_do_not_report_writes() { + let r = report(concat!( + "var a = other.SAVECHANGES;\n", + "var b = other['SAVECHANGES'];\n", + "app.activeDocument.close('SAVECHANGES');\n", + "var c = holder.SaveOptions.SAVECHANGES;\n", + "var d = holder.SaveOptions['SAVECHANGES'];\n", + "var e = 'SAVECHANGES';\n", + "var key = SaveOptions['SAVECHANGES' + suffix];\n", + "var f = SaveOptions.SAVECHANGES;\n", + "var g = SaveOptions['SAVECHANGES'];\n", + "var h = 'SaveOptions.SAVECHANGES';\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[8, 9, 10][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[8, 9, 10][..])]); +} + /// `saveAs` and `exportFile` called with their names as string literals in brackets write the file /// too; reading the method without calling it does not. #[test] @@ -714,6 +745,27 @@ fn a_function_read_earlier_that_assigns_the_variable_keeps_save_as_writing() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..])); } +#[test] +fn captured_reassignments_keep_save_as_writing_after_a_later_initializer() { + let r = report(concat!( + "var f = new File(p);\n", + "function outer() {\n", + " function choose() { d = app.activeDocument; }\n", + " var d = {saveAs: function () {}};\n", + " choose(); d.saveAs(f);\n", + " function bump() { e++; }\n", + " var e = {saveAs: function () {}};\n", + " bump(); e.saveAs(f);\n", + " function own() { var g; g = app.activeDocument; }\n", + " var g = {saveAs: function () {}};\n", + " own(); g.saveAs(f);\n", + "}\n", + "outer();\n", + )); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[5, 8][..])]); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8][..])); +} + /// Assigning a property of `this`, the global object in the global code and in a function called /// without a receiver, may give the global variable of that name another value, before or after /// its literal. diff --git a/docs/mcp.md b/docs/mcp.md index a9542a7435..7e98a72bbd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3003,6 +3003,8 @@ other files through `$`: those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. - `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. + When the format is selected by a `.vctemplate` path, `saveAs` writes a template copy and leaves the document's + file and saved state unchanged. `Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is. `app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/). @@ -3027,7 +3029,10 @@ other files through `$`: `coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and `includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with - `pageToOpen` and `pDFCropToBox`. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of + `pageToOpen` and `pDFCropToBox`. These options require PDF content, including PDF-compatible `.ai` and `.ait` files. + `app.open` rejects a file over 128 MiB before reading it. + Optional arguments to `saveAs`, `exportFile`, `app.open` and `close` use defaults when omitted or `undefined`; + explicit `null` throws a type error. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, `EPSPostScriptLevelEnum`, `PDFOverprint`, `SaveOptions` and `UserInteractionLevel` hold strings such as `"ExportType.PNG24"`. @@ -3059,13 +3064,15 @@ other files through `$`: artboard numbers (such as `abc` or `0-`) throws. `Document.path` is a `Folder` for the folder of the document's file. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. `fullName` and `path` of a document whose file the automation read roots do not allow throw - `Script file access denied`. Setting `saved` runs `document.setSaved`: `true` records the document as saved + `Script file access denied`. Changing `saved` runs `document.setSaved`: `true` records the document as saved without saving it, so `close()` then closes it, and `false` records it as having unsaved changes; neither adds an - undo step. With unsaved changes, `close` closes without them with `SaveOptions.DONOTSAVECHANGES`; + undo step. Assigning its current value runs no command and adds no journal entry. + With unsaved changes, `close` closes without them with `SaveOptions.DONOTSAVECHANGES`; `SaveOptions.SAVECHANGES` first saves them to the document's file with `file.saveAs`, in the format the document was last saved in and after the same write-access check of the path as `saveAs`, and throws an error and leaves the document open when the document has no file (a converted or recovered document included) or when - its last save named some of its artboards, without writing anything; and + the save would omit artboards. These refusals occur before writing any files. An SVG or SVGZ save of several + artboards requires Preserve Editing Capabilities to close with `SaveOptions.SAVECHANGES`. `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws an error and leaves the document open, since a script cannot show the prompt. A bad value throws an error before anything is written. - `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type From 8f1edd06449ee3231095bf4e062184478251660f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 06:33:02 -0800 Subject: [PATCH 19/69] Colors: a color with a component too large to store is refused A color given as {"c": 1e300, ...}, [1e300, 0, 0], {"gray": 1e300}, a Lab color or a color object with a number past f32::MAX was stored with an infinite component. paint.setFill, artboard.setProps, swatch.new, text.create and the other commands that read colors through cmd::color_value took it. - color_value refuses a color whose components are not finite, so the commands that read a color through it answer an error and change nothing. - An effect's color (Drop Shadow, Inner Glow, Outer Glow, Shift to Color) with such a number is refused with "`color` must be a #rrggbb color". - ui.colorWheel's contrastBackground refuses it as well. Docs: docs/mcp.md. --- crates/engine/src/cmd.rs | 18 +++++++- crates/engine/src/cmd/params.rs | 12 ++--- crates/engine/src/tests/panelcmds.rs | 46 +++++++++++++++++++ crates/engine/tests/it/param_keys.rs | 14 +++++- crates/ui-egui/src/panels/color_wheel.rs | 6 ++- .../src/panels/tests_color_wheel_contrast.rs | 2 + docs/mcp.md | 10 ++-- 7 files changed, 93 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 8a4e6ebe6f..cc0abc05a3 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -672,8 +672,24 @@ pub fn matrix_param(p: &Value, key: &str) -> Option { } /// A colour from `"#rrggbb"`, a colour key (`"cmyk 0 100 100 0"`, `"lab 55 60 40"`), `[r,g,b]` (0..1), /// `{"c":..,"m":..,"y":..,"k":..}` (percent when any component is above 1, else 0..1), `{"gray":..}` or `{"l":..,"a":..,"b":..}` (CIE Lab: L 0..100, a and b about -/// −128..127). `None` for a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without the `#`). +/// −128..127). `None` for a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without the `#`), +/// and for a color with a component too large to store ([`color_is_finite`]). pub fn color_value(v: &Value) -> Option { + given_color(v).filter(color_is_finite) +} + +/// Is every component of `c` finite? A number past `f32::MAX`, such as `{"c": 1e300}`, is stored +/// as an infinity. +pub fn color_is_finite(c: &Color) -> bool { + match *c { + Color::Rgb { r, g, b } | Color::Lab { l: r, a: g, b } => [r, g, b].iter().all(|x| x.is_finite()), + Color::Cmyk { c, m, y, k } => [c, m, y, k].iter().all(|x| x.is_finite()), + Color::Gray { k } => k.is_finite(), + } +} + +/// The color `v` gives, as [`color_value`] reads it, with its components unchecked. +fn given_color(v: &Value) -> Option { match v { Value::String(s) if hex_with_alpha(s) => None, // A hex, or a colour key ("cmyk 0 100 100 0", as Recolor Artwork lists colours). diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index dcc3eade04..9b498f1ca8 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -43,7 +43,7 @@ use std::sync::OnceLock; use serde_json::Value; use vectorcraft_apischema::shown_key; -use super::{bad, command_specs, find_command}; +use super::{bad, color_is_finite, command_specs, find_command}; use crate::Result; /// What a params description says about the keys of the params object. @@ -608,16 +608,16 @@ pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option { /// Can an effect read `v` as its `color`: a string [`Color::from_hex`] reads (`#rrggbb`, `#rgb`, /// `#rrggbbaa`, black, white, red, green, blue), `[r, g, b]` whose first three entries are numbers -/// (read on a 0..1 scale) or a color object (`{"model": "rgb", "r": …}`)? The effect draws its -/// default color for any other value, except that an array of three or more entries draws an -/// entry that isn't a number as 0. +/// (read on a 0..1 scale) or a color object (`{"model": "rgb", "r": …}`), with no component too +/// large to store ([`color_is_finite`])? The effect draws its default color for any other value, +/// except that an array of three or more entries draws an entry that isn't a number as 0. /// /// [`Color::from_hex`]: vectorcraft_color::Color::from_hex fn is_effect_color(v: &Value) -> bool { match v { Value::String(s) => vectorcraft_color::Color::from_hex(s).is_some(), - Value::Array(a) => a.len() >= 3 && a.iter().take(3).all(Value::is_number), - Value::Object(_) => serde_json::from_value::(v.clone()).is_ok(), + Value::Array(a) => a.len() >= 3 && a.iter().take(3).all(|n| n.as_f64().is_some_and(|n| (n as f32).is_finite())), + Value::Object(_) => serde_json::from_value::(v.clone()).is_ok_and(|c| color_is_finite(&c)), _ => false, } } diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index 397c9252b5..c99f58359f 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -266,6 +266,52 @@ fn a_color_with_an_alpha_part_is_refused() { s.execute("object.rasterize", &json!({"ppi": 72, "background": "#ff0000"})).unwrap(); } +/// A color param with a component too large to store (past `f32::MAX`, which would be stored as an +/// infinity) is refused and changes nothing, in every form a color is given in: CMYK, `[r, g, b]`, +/// Gray, Lab and a color object. The ends of each range still set the color. +#[test] +fn a_color_with_a_component_too_large_to_store_is_refused() { + let mut s = session(); + let id = rect(&mut s); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for bad in [ + json!({"c": f64::MAX, "m": 0, "y": 0, "k": 0}), + json!({"c": 0, "m": 0, "y": 0, "k": 1e308}), + json!([1e300, 0, 0]), + json!([0, 0, -1e300]), + json!({"gray": 1e300}), + json!({"l": 1e300, "a": 0, "b": 0}), + json!({"l": 50, "a": 0, "b": -1e300}), + json!({"model": "rgb", "r": 1e300, "g": 0, "b": 0}), + json!({"model": "cmyk", "c": 0, "m": 1e300, "y": 0, "k": 0}), + ] { + for (cmd, p) in [ + ("artboard.setProps", json!({"index": 0, "color": bad})), + ("artboard.new", json!({"color": bad})), + ("paint.setFill", json!({"ids": [id.0], "color": bad})), + ("paint.setStroke", json!({"ids": [id.0], "color": bad})), + ("swatch.new", json!({"name": "Far", "color": bad})), + ("swatch.new", json!({"colors": ["#00ff00", bad]})), + ("text.create", json!({"x": 10, "y": 10, "text": "a", "color": bad})), + ] { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + } + } + assert_eq!(*s.doc().unwrap().doc, *before, "a color too large to store changes nothing"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "and records no undo step"); + let fill = |s: &Session| node(s, id).appearance.fill_paint().color(); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": {"c": 100, "m": 0, "y": 0, "k": 0}})).unwrap(); + assert_eq!(fill(&s), Some(Color::cmyk(1.0, 0.0, 0.0, 0.0))); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": [1, 0, 0]})).unwrap(); + assert_eq!(fill(&s).map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": {"gray": 100}})).unwrap(); + assert_eq!(fill(&s), Some(Color::gray(1.0))); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": {"l": 100, "a": -128, "b": 127}})).unwrap(); + assert_eq!(fill(&s), Some(Color::lab(100.0, -128.0, 127.0))); +} + /// The native format writes an artboard's background color and reads it back. An artboard without /// one is written as before, with no `color` key. #[test] diff --git a/crates/engine/tests/it/param_keys.rs b/crates/engine/tests/it/param_keys.rs index fb30bf3c5c..7e80c1aedc 100644 --- a/crates/engine/tests/it/param_keys.rs +++ b/crates/engine/tests/it/param_keys.rs @@ -170,7 +170,8 @@ fn effect_params_no_longer_taken_still_replay_and_open() { } /// An effect's `color` that the effect can't read (a string `Color::from_hex` doesn't read, an -/// `[r, g, b]` without three numbers, an object that isn't a color, `null`) is refused by +/// `[r, g, b]` without three numbers, an object that isn't a color, `null`, a color with a component +/// too large to store) is refused by /// `effect.apply`, `appearance.addEffect` and `effect.setParams` themselves, not only by the check, /// and the document and its undo history stay as they were. The forms the effect reads pass. A /// document saved with an unreadable color still opens with it. @@ -186,7 +187,16 @@ fn an_effect_color_it_cannot_draw_is_refused() { }; let before = state(&s); let why = "`color` must be a #rrggbb color"; - for bad in [json!("not-a-color"), json!("#ff00"), json!([1, 0]), json!(["#ff0000", 0, 0]), json!({"gray": 50}), json!(null)] { + for bad in [ + json!("not-a-color"), + json!("#ff00"), + json!([1, 0]), + json!(["#ff0000", 0, 0]), + json!({"gray": 50}), + json!(null), + json!([1e300, 0, 0]), + json!({"model": "rgb", "r": 0, "g": 1e300, "b": 0}), + ] { for (cmd, params) in [ ("effect.setParams", json!({"index": 0, "params": {"color": bad}})), ("effect.apply", json!({"effect": "stylize.outerGlow", "params": {"color": bad}})), diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 3e706b06c1..71aab82559 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -334,9 +334,11 @@ fn deserialize_category<'de, D: serde::Deserializer<'de>>(d: D) -> Result Option { - serde_json::from_value(v.clone()).ok().or_else(|| vectorcraft_engine::cmd::color_value(v)) + let saved = serde_json::from_value(v.clone()).ok().filter(vectorcraft_engine::cmd::color_is_finite); + saved.or_else(|| vectorcraft_engine::cmd::color_value(v)) } fn deserialize_background<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { diff --git a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs index 2f938cc8e2..0b825aedc8 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs @@ -347,6 +347,8 @@ fn ui_color_wheel_sets_the_keys_given_and_refuses_bad_values() { (json!({"contrastFor": 3}), "`contrastFor` must be one of normalText, largeText, graphics"), (json!({"contrastBackground": "nope"}), "`contrastBackground` must be a color or null"), (json!({"contrast": false, "contrastBackground": 5}), "`contrastBackground` must be a color or null"), + (json!({"contrastBackground": {"model": "rgb", "r": 1e300, "g": 0, "b": 0}}), "`contrastBackground` must be a color or null"), + (json!({"contrastBackground": {"c": 0, "m": 0, "y": 0, "k": 1e300}}), "`contrastBackground` must be a color or null"), ] { assert_eq!(app.run("ui.colorWheel", p.clone()).unwrap_err(), e, "{p}"); } diff --git a/docs/mcp.md b/docs/mcp.md index d698534089..61fa504972 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -642,7 +642,8 @@ Paint values (`fill`, `stroke`) accept `"#rrggbb"`, `"none"`, `[r,g,b]` (0..1), or a full `paint.setFill` params object (`{"gradient": …}`, `{"swatch": "name"}`). A color read this way (a fill or stroke color, a swatch's, an artboard's or new type's color, and the other colors commands read in these forms) that is given as a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without -the `#`) is an error and changes nothing, as VectorCraft's own rule. The `color` of Drop Shadow, Inner Glow, Outer Glow +the `#`) is an error and changes nothing, as VectorCraft's own rule. So is a color with a component too large to store +as a 32-bit float, such as `{"c": 1e300, "m": 0, "y": 0, "k": 0}`. The `color` of Drop Shadow, Inner Glow, Outer Glow and Shift to Color is read differently and takes `#rrggbbaa`, as described below. For `draw_shape` and `draw_path`, omitted paint fields inherit the current [new-art appearance](#new-art). Both also style the new object in the same call: `dash` (lengths, or null for solid), `cap` @@ -2231,9 +2232,10 @@ in a replayed journal or action too, and nothing changes. The `color` of Drop Shadow, Inner Glow, Outer Glow and Shift to Color must be one the effect can read: a hex color (`#rrggbb`, `#rgb` or `#rrggbbaa`, with or without the `#`), `black`, `white`, `red`, `green` or `blue`, `[r, g, b]` -(three numbers, each read on a 0 to 1 scale), or a color object (`{"model": "rgb", "r": 1, "g": 0, "b": 0}`). -`effect.apply` and `effect.setParams` refuse any other value themselves (where the parameter check runs first, a number -or a boolean is refused as not a string), so the app's effect dialogs and Appearance panel, a step of +(three numbers, each read on a 0 to 1 scale), or a color object (`{"model": "rgb", "r": 1, "g": 0, "b": 0}`), with no +number too large to store as a 32-bit float (`[1e300, 0, 0]` is refused). `effect.apply` and `effect.setParams` +refuse any other value themselves (where the parameter check runs first, a number or a boolean is refused as not a +string), so the app's effect dialogs and Appearance panel, a step of `command.batch` and a replayed journal get the same error, and the document and its undo history stay as they were: ```json From 295296947eba240c08058b41fcb14b6d4dc0de8e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 08:09:58 -0800 Subject: [PATCH 20/69] MCP: the Simplify and Smooth sliders show in ui.inspect and answer ui.dialog The params text of ui.simplifyAuto and ui.smoothAuto and docs/mcp.md say Object > Path > Simplify and Smooth open the dialogs simplifySlider and smoothSlider with field `level`, kept by ui.dialog.confirm. The sliders are a strip over the canvas, not hosted dialogs, so ui.inspect listed no dialog while one was open and ui.dialog.set and ui.dialog.confirm had nothing to answer. - ui.inspect lists the open slider as {id, parent, key, fields: {level}}, first in `dialogs`, so "top" still names a hosted dialog open over it. - ui.dialog.set {field: "level", value} moves the slider to a level from 0 to 100 and previews it. A value outside that range, a value that is not a number, another field, or a set while another edit holds the interaction is refused and leaves the level as it was. - ui.dialog.confirm keeps the preview as one undo step, as Enter does, and ui.dialog.cancel puts the paths back, as Escape does. A set with `action` answers in the same request and replies {dialog, result}. --- crates/ui-egui/src/control.rs | 13 +- crates/ui-egui/src/dialogs/simplify_slider.rs | 143 +++++++++++++++++ crates/ui-egui/src/dialogs/tests_modal.rs | 146 ++++++++++++++++++ 3 files changed, 301 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index c0c6bd0bc6..7495e0ed02 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -18,7 +18,8 @@ //! - `ui.find`: the controls of the window's access tree that match a name or role //! - `ui.set {brightness?, panel?, dockTab?, rulers?, outline?, …}` //! - `ui.dialog.set` / `ui.dialog.confirm` / `ui.dialog.cancel`: answered by -//! `craft::automation::dialogs::dialog_method` for the dialog asked for (`dialog`, default `"top"`) +//! `craft::automation::dialogs::dialog_method` for the dialog asked for (`dialog`, default `"top"`), and by +//! `dialogs::simplify_slider::dialog_method` for the Simplify and Smooth sliders //! - `ui.resize {width, height}`, `ui.focus`, `ui.screenshot {path?, focus?}` (without a path the //! PNG comes back in the reply) //! - `ui.render {path?, scale?, artboard?, data?, traceViews?}`: render an artboard headlessly @@ -152,6 +153,10 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { } let mut dialogs = app.dialogs().map_or_else(|| json!([]), |dialogs| dialogs.with(|host| craft::automation::dialogs::inspect(host))); crate::dialogs::javascript_files::show_selected(app, &mut dialogs); + // The Simplify or Smooth slider over the canvas, listed first: `"top"` names a hosted dialog open with it. + if let (Some(open), Some(strip)) = (dialogs.as_array_mut(), crate::dialogs::simplify_slider::inspected(app)) { + open.insert(0, strip); + } json!({ "scriptRunning": app.session.script_running(), "scriptReport": app.session.shown_script_report(), @@ -1437,6 +1442,12 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val if crate::prefs_dialog::is_open(app) && (p["dialog"] == "preferences" || (top && dialogs.with(|host| host.stack().is_empty()))) { return wrap(preferences_method(app, method, p)); } + // The Simplify and Smooth sliders are the app's own strip over the canvas, not hosted dialogs: they take a + // request that names them, or the top dialog while no hosted dialog is open. + let hosted_open = dialogs.with(|host| !host.stack().is_empty()); + if let Some(r) = crate::dialogs::simplify_slider::dialog_method(app, method, p, hosted_open) { + return wrap(r); + } // The dialog asked for is `dialog`, the top one when it is missing. let mut params = if p.is_object() { p.clone() } else { json!({}) }; if params.get("dialog").is_none_or(Value::is_null) { diff --git a/crates/ui-egui/src/dialogs/simplify_slider.rs b/crates/ui-egui/src/dialogs/simplify_slider.rs index cb58f856a7..2a4f5b0f9c 100644 --- a/crates/ui-egui/src/dialogs/simplify_slider.rs +++ b/crates/ui-egui/src/dialogs/simplify_slider.rs @@ -13,11 +13,14 @@ // PLAN: the framework paths below (`craft_ui_widgets`, `craft_ui_contract`, `craft_behavior`) and // `LivePreview`'s module are assumed; no app file imports them yet. +use craft::automation::dialogs::MAX_DIALOG_FIELDS; +use craft::automation::protocol::Params; use craft::behavior::overlay::{Align, Side}; use craft::behavior::{CanvasView, IconId}; use craft::ui::buttons::IconButton; use craft::ui::contract::overlay::{Anchor, Dismiss, Outside, Place}; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::dialog::dialog_id; use craft::ui::layout_components::Row; use craft::ui::popover::Popover; use craft::ui::primitives::IconSpec; @@ -78,6 +81,20 @@ impl StripKind { StripKind::Smooth => SMOOTH_AUTO_LEVEL, } } + + /// The dialog key `ui.inspect` lists the strip under, which `ui.dialog.set`, `ui.dialog.confirm` and + /// `ui.dialog.cancel` take as `dialog`. + pub(crate) fn key(self) -> &'static str { + match self { + StripKind::Simplify => "simplifySlider", + StripKind::Smooth => "smoothSlider", + } + } + + /// The id `ui.inspect` lists the strip under: the one a hosted dialog with the same key has, as a decimal string. + fn id(self) -> String { + dialog_id(self.key()).value().to_string() + } } /// An open slider strip: the level the canvas previews, the selection's bounds from before any @@ -210,6 +227,132 @@ pub(crate) fn more_options(app: &mut VectorcraftApp) -> Result { Ok(json!({ "tolerance": tolerance })) } +/// The open strip as `ui.inspect` lists a dialog, `{id, parent, key, fields: {level}}`; `None` when no strip shows. +pub(crate) fn inspected(app: &VectorcraftApp) -> Option { + let strip = app.object_dialogs.strip.as_ref().filter(|strip| strip.in_source(app))?; + let kind = strip.kind; + Some(json!({ "id": kind.id(), "parent": null, "key": kind.key(), "fields": { "level": strip.level() } })) +} + +/// The level a `ui.dialog.set` on a strip of `kind` asks for: field `level`, a number from 0 to 100, as `field` and +/// `value` or as the last item of `fields`. `None` when it sets nothing. +fn requested_level(kind: StripKind, params: &Value) -> Result, String> { + let level = |field: &Value, value: &Value| { + let field = field.as_str().ok_or("`field` is not a string")?; + if field != "level" { + return Err(format!("the {} slider has no field `{field}`", kind.label())); + } + match value.as_f64() { + Some(level) if (0.0..=100.0).contains(&level) => Ok(level), + _ => Err("`level` must be a number from 0 to 100".to_string()), + } + }; + let Some(list) = params.get("fields") else { + return match params.get("field") { + Some(field) => level(field, params.get("value").unwrap_or(&Value::Null)).map(Some), + None if params.get("value").is_some() => Err("missing `field`".into()), + None => Ok(None), + }; + }; + if params.get("field").is_some() || params.get("value").is_some() { + return Err("`fields` takes the place of `field` and `value`".into()); + } + let items = list.as_array().ok_or("`fields` is not a list")?; + if items.len() > MAX_DIALOG_FIELDS { + return Err(format!("`fields` holds {} items; at most {MAX_DIALOG_FIELDS}", items.len())); + } + let mut last = None; + for item in items { + last = Some(level(item.get("field").unwrap_or(&Value::Null), item.get("value").unwrap_or(&Value::Null))?); + } + Ok(last) +} + +/// `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` (`method`) when `params.dialog` names the open strip: +/// its key or the id [`inspected`] lists, or `"top"` (or no `dialog`) while `hosted_open` is false. `None` for any +/// other dialog. +/// +/// `ui.dialog.set {field: "level", value}` moves the slider and previews the level, then answers with `action` +/// (`confirm` or `cancel`) when one is given; a set it refuses leaves the slider as it was. `ui.dialog.confirm` keeps +/// the preview as one undo step, as Enter does, and `ui.dialog.cancel` puts the paths back, as Escape does. +pub(crate) fn dialog_method(app: &mut VectorcraftApp, method: &str, params: &Value, hosted_open: bool) -> Option> { + let kind = app.object_dialogs.strip.as_ref().filter(|strip| strip.in_source(app))?.kind; + let ours = match params.get("dialog") { + None | Some(Value::Null) => !hosted_open, + Some(Value::String(named)) if named == "top" => !hosted_open, + Some(Value::String(named)) => named == kind.key() || *named == kind.id(), + Some(named) => named.as_u64().is_some_and(|id| id.to_string() == kind.id()), + }; + if !ours { + return None; + } + let keys: &[&str] = match method { + "ui.dialog.set" => &["dialog", "field", "value", "fields", "action"], + "ui.dialog.confirm" | "ui.dialog.cancel" => &["dialog"], + _ => return None, + }; + if let Err(e) = Params(params).only(None, keys) { + return Some(Err(e)); + } + let answer = match (method, params.get("action")) { + ("ui.dialog.confirm", _) => Some(true), + ("ui.dialog.cancel", _) => Some(false), + (_, None | Some(Value::Null)) => None, + (_, Some(action)) if action == "confirm" => Some(true), + (_, Some(action)) if action == "cancel" => Some(false), + (_, Some(_)) => return Some(Err("`action` must be confirm or cancel".into())), + }; + let level = if method == "ui.dialog.set" { + match requested_level(kind, params) { + Ok(None) if answer.is_none() => return Some(Err("missing `field`".into())), + Ok(level) => level, + Err(e) => return Some(Err(e)), + } + } else { + None + }; + let mut strip = app.object_dialogs.strip.take()?; + if let Some(level) = level { + let before = strip.level; + strip.level = level; + let params = strip.params(); + let ran = strip.preview.run(app, true, kind.label(), kind.cmd(), ¶ms); + // Nothing ran: the canvas already previews this level, or another edit holds the interaction. + let shown = || { + app.session + .active() + .and_then(|doc| doc.interaction.as_ref()?.preview.as_ref()) + .is_some_and(|(cmd, showing)| cmd == kind.cmd() && showing == ¶ms) + }; + let error = match ran { + Some(Err(e)) => Some(e), + None if !shown() => Some(tl!("Finish the active edit first.").to_owned()), + _ => None, + }; + if let Some(e) = error { + strip.level = before; + app.object_dialogs.strip = Some(strip); + return Some(Err(e)); + } + } + app.object_dialogs.strip = Some(strip); + let set = inspected(app).unwrap_or(Value::Null); + let Some(answer) = answer else { return Some(Ok(set)) }; + let strip = app.object_dialogs.strip.take()?; + let result = if answer { + let params = strip.params(); + strip.preview.commit(app, kind.cmd(), params).map(|_| Value::Null) + } else { + strip.cancel(app); + Ok(Value::Null) + }; + // A set with an `action` replies `{dialog, result}`: the slider as the set left it, and the answer's result. + Some(match (method, result) { + ("ui.dialog.set", Ok(result)) => Ok(json!({ "dialog": set, "result": result })), + (_, result) => result, + }) +} + /// Where the strip hangs: a point under the lowest corner on screen of the selection's bounds from /// before the preview, centred on them, kept on the canvas. fn anchor_rect(view: &CanvasView, bounds: Option) -> ScreenRect { diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index e9a2166fa7..f54cd71999 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -326,3 +326,149 @@ fn path_sliders_close_when_file_revert_restores_the_artwork() { assert!(app.session.in_interaction()); } } + +/// The two sliders: the dialog key `ui.inspect` lists, the menu command that opens it and its undo step's name. +const PATH_SLIDERS: [(&str, &str, &str); 2] = + [("simplifySlider", "object.path.simplify", "Simplify"), ("smoothSlider", "object.path.smooth", "Smooth")]; + +/// One control channel request, answered at once. +fn control(app: &mut VectorcraftApp, method: &str, params: serde_json::Value) -> serde_json::Value { + let ctx = app.ui_ctx.clone().unwrap(); + let (req, _) = craft::automation::ControlRequest::new(method, params); + let craft::automation::Reply::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("{method} answered later") }; + r +} + +/// The open dialog `key` in `ui.inspect`'s `dialogs`. +fn inspected_dialog(app: &mut VectorcraftApp, key: &str) -> Option { + let r = control(app, "ui.inspect", json!({})); + r["result"]["dialogs"].as_array()?.iter().find(|d| d["key"] == key).cloned() +} + +/// Both sliders show in `ui.inspect` as the dialog their params text names, with field `level`. `ui.dialog.set` +/// moves the slider and previews the level, and `ui.dialog.confirm` keeps the result as one undo step. +#[test] +fn path_sliders_show_in_ui_inspect_and_ui_dialog_confirm_keeps_the_level() { + for (key, command, label) in PATH_SLIDERS { + let mut app = app_with_dense_path(); + let undo_len = app.session.doc().unwrap().history.undo.len(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + let open = inspected_dialog(&mut app, key).unwrap_or_else(|| panic!("{key} in ui.inspect")); + assert!(open["fields"]["level"].is_number(), "{open}"); + + let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "field": "level", "value": 20})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(r["result"]["fields"]["level"], 20.0, "{r}"); + let preview = app.session.doc().unwrap().interaction.as_ref().and_then(|it| it.preview.clone()).map(|p| p.1); + assert_eq!(preview, Some(json!({"level": 20.0})), "{key}"); + settle(&mut app); + assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(json!(20.0)), "{key}"); + + let r = control(&mut app, "ui.dialog.confirm", json!({"dialog": key})); + assert_eq!(r["ok"], true, "{r}"); + assert!(inspected_dialog(&mut app, key).is_none(), "{key}"); + assert!(!app.session.in_interaction(), "{key}"); + let history = &app.session.doc().unwrap().history; + assert_eq!(history.undo.len(), undo_len + 1, "{key}"); + assert_eq!(history.undo.last().map(|step| step.label.as_str()), Some(label), "{key}"); + } +} + +/// A repeated level succeeds, but another active edit blocks a set and leaves the slider's level unchanged. +#[test] +fn path_sliders_refuse_a_set_when_another_edit_owns_the_interaction() { + for (key, command, _) in PATH_SLIDERS { + let mut app = app_with_dense_path(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + for _ in 0..2 { + let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "field": "level", "value": 30})); + assert_eq!(r["ok"], true, "{key}: {r}"); + } + let level = inspected_dialog(&mut app, key).unwrap_or_else(|| panic!("{key} in ui.inspect"))["fields"]["level"].clone(); + app.session.cancel_interaction().unwrap(); + app.begin_interaction("Other").unwrap(); + + let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "field": "level", "value": 20})); + assert_eq!(r["ok"], false, "{key}: {r}"); + assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(level.clone()), "{key}"); + settle(&mut app); + assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(level), "{key}"); + } +} + +/// `ui.dialog.set` with `action` sets the level and answers in one request, replying `{dialog, result}` with the +/// slider as the set left it: `confirm` keeps the level as one undo step, and `cancel` puts the paths back. +#[test] +fn path_sliders_answer_a_set_with_an_action_in_one_request() { + for (key, command, label) in PATH_SLIDERS { + for action in ["confirm", "cancel"] { + let mut app = app_with_dense_path(); + let before = app.session.active().unwrap().doc.clone(); + let undo_len = app.session.doc().unwrap().history.undo.len(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "fields": [{"field": "level", "value": 30}], "action": action})); + assert_eq!(r["ok"], true, "{key} {action}: {r}"); + assert_eq!(r["result"]["dialog"]["key"], key, "{r}"); + assert_eq!(r["result"]["dialog"]["fields"]["level"], 30.0, "{r}"); + assert!(r["result"].get("result").is_some(), "{r}"); + assert!(inspected_dialog(&mut app, key).is_none(), "{key} {action}"); + assert!(!app.session.in_interaction(), "{key} {action}"); + let history = &app.session.doc().unwrap().history; + if action == "confirm" { + assert_eq!(history.undo.len(), undo_len + 1, "{key}"); + assert_eq!(history.undo.last().map(|step| step.label.as_str()), Some(label), "{key}"); + } else { + assert_eq!(history.undo.len(), undo_len, "{key}"); + assert_eq!(app.session.active().unwrap().doc, before, "{key}"); + } + } + } +} + +/// With a hosted dialog open over a slider, `ui.inspect` lists the slider first, and `"top"` names the hosted dialog. +#[test] +fn path_sliders_list_below_a_hosted_dialog_that_top_names() { + let mut app = app_with_dense_path(); + crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + settle(&mut app); + app.run("ui.javascriptFilesDialog", json!({})).unwrap(); + let r = control(&mut app, "ui.inspect", json!({})); + let open = r["result"]["dialogs"].as_array().cloned().unwrap_or_default(); + assert!(open.len() >= 2 && open[0]["key"] == "simplifySlider", "{open:?}"); + let r = control(&mut app, "ui.dialog.cancel", json!({"dialog": "top"})); + assert_eq!(r["ok"], true, "{r}"); + assert!(inspected_dialog(&mut app, "simplifySlider").is_some(), "the hosted dialog closed, the slider stays"); + let r = control(&mut app, "ui.inspect", json!({})); + assert_eq!(r["result"]["dialogs"].as_array().map(Vec::len), Some(open.len() - 1), "{r}"); +} + +/// `ui.dialog.cancel` on the top dialog puts the paths back, as Escape does. A level outside 0..100, a value that +/// isn't a number and another field are refused, and the slider keeps its level. +#[test] +fn path_sliders_answer_ui_dialog_cancel_and_refuse_bad_fields() { + for (key, command, _) in PATH_SLIDERS { + let mut app = app_with_dense_path(); + let before = app.session.active().unwrap().doc.clone(); + let undo_len = app.session.doc().unwrap().history.undo.len(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + let level = inspected_dialog(&mut app, key).unwrap_or_else(|| panic!("{key} in ui.inspect"))["fields"]["level"].clone(); + for bad in [json!({"field": "level", "value": 101}), json!({"field": "level", "value": "20"}), json!({"field": "tolerance", "value": 2})] { + let mut params = bad.clone(); + params["dialog"] = json!(key); + let r = control(&mut app, "ui.dialog.set", params); + assert_eq!(r["ok"], false, "{key} {bad}: {r}"); + assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(level.clone()), "{key} {bad}"); + } + + let r = control(&mut app, "ui.dialog.cancel", json!({})); + assert_eq!(r["ok"], true, "{r}"); + assert!(inspected_dialog(&mut app, key).is_none(), "{key}"); + assert!(!app.session.in_interaction(), "{key}"); + assert_eq!(app.session.active().unwrap().doc, before, "{key}"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo_len, "{key}"); + } +} From b19aac26ec46020afc30997752ad3d699f9155db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:21:40 -0800 Subject: [PATCH 21/69] Selection Tools: Edit Points Only narrows a Direct Selection to its anchor points addon.select.editPointsOnly {segmentEnds?} turns the current selection into one that holds only anchor points, so a move or transform that follows acts on the points alone. Selected segments leave the selection, and the points at their ends leave it too unless segmentEnds is true. Paths selected whole keep every point. A group or compound path selected whole gives way to the visible, unlocked paths inside it (no Shaper Group originals, and no guide paths while guides are locked). Type, images, symbols and other objects without anchor points leave the selection. Only the selection changes, so there is no undo step. With nothing selected or nothing left to keep it is an error and the selection stays as it was. The command is on the plug-in allowed list. Object > Plug-ins > Selection Tools > Edit Points Only... opens a dialog with Keep Ends of Selected Segments; it previews the narrowed selection on the canvas, OK keeps it and Cancel puts the selection back. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/addons/select.rs | 122 ++++++++++++- crates/engine/src/cmd/addons/select/tests.rs | 160 ++++++++++++++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/tests/command_sweep.rs | 2 + crates/ui-egui/src/addons/dialogs.rs | 1 + crates/ui-egui/src/addons/select.rs | 7 +- .../ui-egui/src/addons/select/points_only.rs | 51 ++++++ .../src/addons/select/points_only/tests.rs | 85 ++++++++++ docs/mcp.md | 21 +++ docs/target-app-parity.md | 1 + 10 files changed, 444 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/addons/select/points_only.rs create mode 100644 crates/ui-egui/src/addons/select/points_only/tests.rs diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index c9ae29a303..6c3346ca80 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -1,17 +1,19 @@ //! Selection Tools (`addon.select.*`), a built-in add-on: Select by Artboards selects the objects //! overlapping, fully inside or fully outside one or more chosen artboards (#5525), and Select by //! Link Status selects the images and placed documents whose file is linked, embedded, missing or -//! modified (#5526), saying which ones it had to leave out and why. Its submenu (Object › Plug-ins -//! › Selection Tools), the Links panel's menu items and the dialogs are the UI's. +//! modified (#5526), saying which ones it had to leave out and why. Edit Points Only narrows the +//! selection to the anchor points selected in it, dropping selected segments and objects without +//! anchor points. Its submenu (Object › Plug-ins › Selection Tools), the Links panel's menu items +//! and the dialogs are the UI's. #[cfg(test)] mod tests; -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet, HashSet}; use serde_json::{Value, json}; -use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind}; -use vectorcraft_geom::Point; +use vectorcraft_doc::{AnchorRef, LockedArtboards, Node, NodeId, NodeKind}; +use vectorcraft_geom::{PathData, Point}; use super::super::links::{Status, statuses}; use super::super::panelcmds::listed_artboards; @@ -47,6 +49,15 @@ pub fn specs() -> Vec { has_doc, by_link_status ), + cmd!( + "addon.select.editPointsOnly", + "Edit Points Only", + ["Object", "Plug-ins", "Selection Tools"], + None, + "{segmentEnds?: false (true: the points at the ends of each selected segment stay selected, as anchor points)} narrow the selection to the anchor points selected in it, so that a move or transform that follows acts on those points alone: a path with selected anchor points keeps them; a path with selected segments drops the segments and keeps its other selected anchor points, and the points at the segments' ends leave the selection unless segmentEnds is true; a path selected whole keeps all its points; a group or compound path selected whole gives way to the paths inside it, each selected whole, leaving out hidden and locked ones, a Shaper Group's original shapes and, while guides are locked, paths made into guides; type, images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. With nothing selected, or no anchor point left to keep, it is an error that leaves the selection as it was. Only the selection changes, not the document, so there is nothing to undo → {changed (false when the selection already held only anchor points), count (the paths left selected), points (the anchor points selected on them)}", + has_doc, + edit_points_only + ), ] } @@ -193,3 +204,104 @@ fn by_link_status(s: &mut Session, p: &Value) -> Result { } Ok(out) } + +/// The anchor points of `path` that `refs` names, leaving out references to points it does not have. +fn on_path(path: &PathData, refs: &BTreeSet) -> BTreeSet { + refs.iter().copied().filter(|&(si, ai)| path.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len())).collect() +} + +/// The points at the ends of the segments `segments` of `path`. +fn segment_ends(path: &PathData, segments: &BTreeSet) -> BTreeSet { + let mut ends = BTreeSet::new(); + for &(si, seg) in segments { + if let Some(sp) = path.subpaths.get(si) { + ends.extend([(si, seg), (si, (seg + 1) % sp.anchors.len().max(1))]); + } + } + ends +} + +/// The paths inside container `n` with at least one anchor point, depth first, through the groups +/// and compound paths in it: hidden and locked objects (and what they hold), a Shaper Group's +/// original shapes, and paths made into guides while `guides_locked`, are left out. +fn paths_inside<'a>(n: &'a Node, guides_locked: bool, out: &mut Vec<&'a Node>) { + let originals = usize::from(n.extras().shaper.is_some()); + for c in n.children().into_iter().flatten().skip(originals) { + if !c.visible || c.locked { + continue; + } + match &c.kind { + NodeKind::Path { guide: true, .. } if guides_locked => {} + NodeKind::Path { path, .. } if path.anchors().next().is_some() => out.push(c), + NodeKind::Group { .. } | NodeKind::Compound { .. } => paths_inside(c, guides_locked, out), + _ => {} + } + } +} + +/// `addon.select.editPointsOnly`: narrow the selection to the anchor points selected in it. +fn edit_points_only(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.select.editPointsOnly"; + let keep_ends = switch_or(p, "segmentEnds", false, C)?; + let guides_locked = s.menu.guides_locked; + let st = s.doc()?; + let (doc, sel) = (&st.doc, &st.selection); + if sel.objects.is_empty() { + return Err(bad(C, "select anchor points or segments first")); + } + // Each path once, in selection order, with its points kept: `None` for all of them. + let mut seen = HashSet::new(); + let mut kept: Vec<(NodeId, usize, Option>)> = vec![]; + for id in &sel.objects { + let Some(n) = doc.node(*id) else { continue }; + match &n.kind { + NodeKind::Path { path, .. } => { + let Some(refs) = sel.anchors.get(id) else { + let count = path.anchors().count(); + if count > 0 && seen.insert(*id) { + kept.push((*id, count, None)); + } + continue; + }; + let mut picked = on_path(path, refs); + if let Some(segments) = sel.segments.get(id) + && !keep_ends + { + let ends = segment_ends(path, segments); + picked.retain(|r| !ends.contains(r)); + } + if !picked.is_empty() && seen.insert(*id) { + kept.push((*id, picked.len(), Some(picked))); + } + } + NodeKind::Group { .. } | NodeKind::Compound { .. } => { + let mut inside = vec![]; + paths_inside(n, guides_locked, &mut inside); + for c in inside { + if seen.insert(c.id) { + kept.push((c.id, c.path_data().map_or(0, |path| path.anchors().count()), None)); + } + } + } + _ => {} + } + } + let points: usize = kept.iter().map(|(_, n, _)| n).sum(); + let objects: Vec = kept.iter().map(|(id, ..)| *id).collect(); + let anchors: BTreeMap> = kept.into_iter().filter_map(|(id, _, set)| Some((id, set?))).collect(); + if objects.is_empty() { + return Err(bad(C, "no anchor points are selected")); + } + let changed = objects != sel.objects || anchors != sel.anchors || !sel.segments.is_empty() || !sel.guides.is_empty(); + let count = objects.len(); + if changed { + s.select(|_, sel| { + let (key, key_anchor) = (sel.key.filter(|k| objects.contains(k)), sel.key_anchor); + sel.set(objects); + sel.anchors = anchors; + sel.key = key; + sel.key_anchor = key_anchor; + })?; + } + Ok(json!({ "changed": changed, "count": count, "points": points })) +} diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index 09106a3652..85844c241d 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -337,3 +337,163 @@ mod by_link_status { assert!(Session::new().execute(C, &json!({"status": "linked"})).is_err()); } } + +/// Edit Points Only. +mod edit_points_only { + use std::collections::{BTreeMap, BTreeSet}; + + use serde_json::{Value, json}; + use vectorcraft_doc::NodeId; + + use super::rect; + use crate::Session; + + const C: &str = "addon.select.editPointsOnly"; + + /// A document with two rectangles, `a` and `b` (four anchors each, anchor 0 first). + fn two() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 10.0, 50.0, 50.0); + let b = rect(&mut s, 100.0, 10.0, 50.0, 50.0); + (s, a, b) + } + + /// Anchors 0 and 1 of `a`, anchor 3 of `b`, and then segment 1 of `b` (its ends are anchors 1 and 2). + fn mixed(s: &mut Session, a: NodeId, b: NodeId) { + let items = json!([{"id": a.0, "anchors": [[0, 0], [0, 1]]}, {"id": b.0, "anchors": [[0, 3]]}]); + s.execute("select.anchorsMany", &json!({"items": items})).unwrap(); + s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + } + + fn refs(v: &[(usize, usize)]) -> BTreeSet<(usize, usize)> { + v.iter().copied().collect() + } + + /// Selected objects, with the selected anchors of those selected in part. + type Picked = (Vec, BTreeMap>); + + /// The selected objects and their selected anchors. + fn picked(s: &Session) -> Picked { + let sel = &s.doc().unwrap().selection; + (sel.objects.clone(), sel.anchors.clone()) + } + + #[test] + fn selected_segments_drop_out_and_the_anchor_points_stay() { + let (mut s, a, b) = two(); + mixed(&mut s, a, b); + let before = s.doc().unwrap().selection.clone(); + assert_eq!(before.anchors[&b], refs(&[(0, 1), (0, 2), (0, 3)]), "a segment's ends move with it"); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!(r, json!({"changed": true, "count": 2, "points": 3})); + let sel = &s.doc().unwrap().selection; + assert_eq!(sel.objects, vec![a, b]); + assert_eq!(sel.anchors[&a], refs(&[(0, 0), (0, 1)])); + assert_eq!(sel.anchors[&b], refs(&[(0, 3)]), "the segment's ends leave the selection"); + assert!(sel.segments.is_empty(), "no segment stays selected"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "only the selection changes"); + } + + #[test] + fn segment_ends_stay_as_anchor_points_when_asked() { + let (mut s, a, b) = two(); + mixed(&mut s, a, b); + let r = s.execute(C, &json!({"segmentEnds": true})).unwrap(); + assert_eq!(r, json!({"changed": true, "count": 2, "points": 5})); + let sel = &s.doc().unwrap().selection; + assert_eq!(sel.anchors[&b], refs(&[(0, 1), (0, 2), (0, 3)])); + assert!(sel.segments.is_empty()); + // With the default, a path holding only a selected segment leaves the selection. + s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 0]]})).unwrap(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 2]], "mode": "add"})).unwrap(); + let r = s.execute(C, &json!({"segmentEnds": false})).unwrap(); + assert_eq!(r, json!({"changed": true, "count": 1, "points": 1})); + assert_eq!(picked(&s), (vec![a], BTreeMap::from([(a, refs(&[(0, 2)]))]))); + } + + #[test] + fn a_selection_of_anchor_points_alone_is_left_as_it_is() { + let (mut s, a, b) = two(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 2]]})).unwrap(); + let before = picked(&s); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": false, "count": 1, "points": 2})); + assert_eq!(picked(&s), before); + // Paths selected whole keep all their points. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": false, "count": 2, "points": 8})); + assert_eq!(picked(&s), (vec![a, b], BTreeMap::new())); + } + + #[test] + fn groups_and_compound_paths_give_way_to_their_paths_and_other_objects_leave() { + let (mut s, a, b) = two(); + let c = rect(&mut s, 200.0, 10.0, 20.0, 20.0); + let hidden = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Points"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [b.0, c.0, hidden.0, text.0]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [hidden.0]})).unwrap(); + s.execute("object.hide", &json!({})).unwrap(); + let d = rect(&mut s, 20.0, 20.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [a.0, d.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.doc().unwrap().selection.objects.clone(); + assert_eq!(compound.len(), 1); + let members: Vec = s.doc().unwrap().doc.node(compound[0]).unwrap().children().unwrap().iter().map(|m| m.id).collect(); + assert_eq!(members.len(), 2); + s.execute("select.set", &json!({"ids": [compound[0].0, group]})).unwrap(); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!(r, json!({"changed": true, "count": 4, "points": 16}), "{r}"); + let mut want = members; + want.extend([b, c]); + assert_eq!(picked(&s), (want, BTreeMap::new()), "the hidden path and the type are left out"); + } + + #[test] + fn guide_paths_in_a_group_are_left_out_while_guides_are_locked() { + let (mut s, a, b) = two(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Points"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [b.0, text.0]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + s.execute("select.set", &json!({"ids": [group]})).unwrap(); + let before = s.doc().unwrap().selection.clone(); + let e = s.execute(C, &json!({})).unwrap_err().to_string(); + assert!(e.contains("no anchor points are selected"), "{e}"); + assert_eq!(s.doc().unwrap().selection, before); + s.execute("select.set", &json!({"ids": [a.0, group]})).unwrap(); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": true, "count": 1, "points": 4})); + assert_eq!(picked(&s), (vec![a], BTreeMap::new())); + // Unlocked, the guide path is a path like any other. + s.execute("view.guides.lock", &json!({"locked": false})).unwrap(); + s.execute("select.set", &json!({"ids": [group]})).unwrap(); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": true, "count": 1, "points": 4})); + assert_eq!(picked(&s), (vec![b], BTreeMap::new())); + } + + #[test] + fn nothing_to_keep_is_an_error_that_leaves_the_selection() { + let (mut s, a, b) = two(); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Points"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute(C, &json!({})).is_err(), "nothing selected"); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]]})).unwrap(); + s.execute("select.add", &json!({"ids": [text.0]})).unwrap(); + let before = s.doc().unwrap().selection.clone(); + let e = s.execute(C, &json!({})).unwrap_err().to_string(); + assert!(e.contains("no anchor points are selected"), "{e}"); + assert_eq!(s.doc().unwrap().selection, before); + for p in [json!({"segmentEnds": "yes"}), json!({"segmentEnds": 1}), json!({"segmentEnds": [true]}), json!({"segmentEnd": true})] { + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]]})).unwrap(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "add"})).unwrap(); + let before = s.doc().unwrap().selection.clone(); + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().selection, before, "{p}"); + } + assert!(Session::new().execute(C, &Value::Null).is_err(), "without a document"); + } +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index c2699f219c..6b146b91ec 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -81,6 +81,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.pen.segment", "addon.pen.togglePoint", "addon.select.byArtboards", + "addon.select.editPointsOnly", "addon.shapes.box3d", "addon.shapes.configure", "addon.shapes.ellipse", diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 462641b953..44919a7960 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -538,6 +538,8 @@ fn structured_junk() { ("addon.select.byLinkStatus", json!({"status": "embedded", "ids": {"a": 1}, "add": [1], "zoom": "yes"})), ("addon.select.byLinkStatus", json!({"status": ["modified", "embedded"], "ids": [], "add": true, "zoom": true})), ("addon.select.byLinkStatus", json!({"status": [[["linked"]]], "ids": null})), + ("addon.select.editPointsOnly", json!({"segmentEnds": "yes"})), + ("addon.select.editPointsOnly", json!({"segmentEnds": [true], "ids": [2, u64::MAX]})), ("links.relink", json!({"scope": "each", "paths": [{"ids": [2, u64::MAX, -1, "x"], "path": ""}, null, 7, {"path": [1]}]})), ("links.relink", json!({"scope": ["all"], "path": "/no/such/file.png", "ids": {"a": 1}})), ("links.relink", json!({"scope": "missingInFolder", "path": "", "folder": [], "paths": "x"})), diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index e58443e259..3273764d5f 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -108,6 +108,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option color::legend::open, color::nearest::COMMAND => color::nearest::open, select::COMMAND => select::open, + select::points_only::COMMAND => select::points_only::open, _ => return super::arrange::open(app, id), }; Some(open(app)) diff --git a/crates/ui-egui/src/addons/select.rs b/crates/ui-egui/src/addons/select.rs index 6ae9a2ae91..22428bef53 100644 --- a/crates/ui-egui/src/addons/select.rs +++ b/crates/ui-egui/src/addons/select.rs @@ -1,8 +1,8 @@ //! Selection Tools in the interface: its submenu (Object › Plug-ins › Selection Tools) and the //! Select by Artboards dialog (#5548), which lists the artboards with their number, name and size, //! filters them by name, picks several, fits one in the window on double-click (#5549), and on OK -//! runs `addon.select.byArtboards` with the relation chosen; and Select by Link Status -//! ([`link_status`], #5526). +//! runs `addon.select.byArtboards` with the relation chosen; Select by Link Status +//! ([`link_status`], #5526); and Edit Points Only ([`points_only`]). use craft::behavior::{Selection, keyed}; use craft::i18n::Folder; @@ -27,6 +27,7 @@ use crate::VectorcraftApp; use crate::menus::{Sep, cp}; pub mod link_status; +pub mod points_only; /// Select by Artboards, and its dialog's kind. pub const COMMAND: &str = "addon.select.byArtboards"; @@ -40,6 +41,8 @@ const LIST_ROWS: u16 = 9; pub fn menu() -> Vec { let mut v = vec![cp("Select by Artboards…", COMMAND, Value::Null), Sep]; v.extend(link_status::menu()); + v.push(Sep); + v.extend(points_only::menu()); v } diff --git a/crates/ui-egui/src/addons/select/points_only.rs b/crates/ui-egui/src/addons/select/points_only.rs new file mode 100644 index 0000000000..f4b0d157d2 --- /dev/null +++ b/crates/ui-egui/src/addons/select/points_only.rs @@ -0,0 +1,51 @@ +//! Edit Points Only in the interface: its item in Object › Plug-ins › Selection Tools and its +//! dialog, which previews the narrowed selection on the canvas and runs +//! `addon.select.editPointsOnly` on OK; Cancel puts the selection back. + +use std::borrow::Cow; + +use craft::menu::Node; +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind}; +use serde_json::{Map, Value, json}; + +use crate::VectorcraftApp; +use crate::addons::dialogs::Spec; +use crate::dialogs::form; +use crate::menus::c; + +/// Edit Points Only: the dialog's key and the command its OK runs. +pub const COMMAND: &str = "addon.select.editPointsOnly"; + +static SPEC: Spec = Spec { command: COMMAND, params, found: None }; + +/// The menu item. +pub fn menu() -> Vec { + vec![c("Edit Points Only…", COMMAND)] +} + +/// The dialog's rows. +fn rows() -> Vec { + vec![Param::new("segmentEnds", tl!("Keep Ends of Selected Segments"), ParamKind::bool(false))] +} + +/// The command's params for the dialog's `fields`. +fn params(fields: &DialogFields) -> Value { + Value::Object(form::json_of(&rows(), fields)) +} + +/// Opens the dialog on the active document, with the ends of selected segments left out. +pub(crate) fn open(app: &mut VectorcraftApp) -> Result { + if app.session.active().is_none() { + return Err("no document".into()); + } + let mut opening = Map::new(); + opening.insert("segmentEnds".into(), json!(false)); + let fields = form::fields_of(&rows(), &opening); + crate::addons::dialogs::open(app, &SPEC, fields, |fields| { + ParamDialog::new(COMMAND, tl!("Edit Points Only"), Cow::Owned(rows())).previews(true).values(Bind::bound(fields)) + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/select/points_only/tests.rs b/crates/ui-egui/src/addons/select/points_only/tests.rs new file mode 100644 index 0000000000..21285a1e8e --- /dev/null +++ b/crates/ui-egui/src/addons/select/points_only/tests.rs @@ -0,0 +1,85 @@ +use std::collections::BTreeSet; + +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::Session; + +use crate::VectorcraftApp; +use crate::addons::dialogs::tests as host; +use crate::tests::panel_harness::Panel as Harness; + +/// An app with a window and two rectangles: anchors 0 and 1 of the first selected, and segment 1 +/// of the second (whose ends are its anchors 1 and 2) beside its anchor 3. +fn app() -> (VectorcraftApp, NodeId, NodeId) { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let mut rect = |x| NodeId(app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + let (a, b) = (rect(10), rect(100)); + let items = json!([{"id": a.0, "anchors": [[0, 0], [0, 1]]}, {"id": b.0, "anchors": [[0, 3]]}]); + app.run("select.anchorsMany", json!({"items": items})).unwrap(); + app.run("select.segments", json!({"id": b.0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + (app, a, b) +} + +fn refs(v: &[(usize, usize)]) -> BTreeSet<(usize, usize)> { + v.iter().copied().collect() +} + +/// The selected anchors of `id`, and whether any segment is selected. +fn points(app: &VectorcraftApp, id: NodeId) -> (Option>, bool) { + let sel = &app.session.doc().unwrap().selection; + (sel.anchors.get(&id).cloned(), !sel.segments.is_empty()) +} + +#[test] +fn the_dialog_previews_keeps_on_ok_and_takes_the_segment_ends_from_the_keyboard() { + let (app, a, b) = app(); + let undo = app.session.doc().unwrap().history.undo.len(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + host::open_item(&mut panel.app(), "Selection Tools", "Edit Points Only…"); + panel.frame(); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.bool("segmentEnds")), Some(false)); + assert_eq!(points(&panel.app(), b), (Some(refs(&[(0, 3)])), false), "the preview drops the segment and its ends"); + assert_eq!(points(&panel.app(), a).0, Some(refs(&[(0, 0), (0, 1)]))); + panel.focus("Keep Ends of Selected Segments"); + panel.key(egui::Key::Space, egui::Modifiers::NONE); + panel.frame(); + assert_eq!(host::read(&panel.app(), id, |f| f.bool("segmentEnds")), Some(true)); + assert_eq!(points(&panel.app(), b), (Some(refs(&[(0, 1), (0, 2), (0, 3)])), false), "the ends are kept as anchor points"); + panel.click("OK"); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!(points(&app, b), (Some(refs(&[(0, 1), (0, 2), (0, 3)])), false)); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "a selection change is not an undo step"); +} + +#[test] +fn cancel_puts_the_selection_back() { + let (app, _, b) = app(); + let before = app.session.doc().unwrap().selection.clone(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + host::open_item(&mut panel.app(), "Selection Tools", "Edit Points Only…"); + panel.frame(); + assert_eq!(points(&panel.app(), b), (Some(refs(&[(0, 3)])), false)); + panel.click("Cancel"); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!(app.session.doc().unwrap().selection, before); +} + +#[test] +fn ok_with_nothing_to_keep_says_why_and_leaves_the_selection() { + let (mut app, a, _) = app(); + app.run("select.segments", json!({"id": a.0, "segments": [[0, 0]]})).unwrap(); + let before = app.session.doc().unwrap().selection.clone(); + host::open_item(&mut app, "Selection Tools", "Edit Points Only…"); + let id = host::dialog_id(&app); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(!app.any_dialog_open()); + assert_eq!(app.session.doc().unwrap().selection, before); + assert!(app.ui.status.contains("no anchor points are selected"), "{}", app.ui.status); +} diff --git a/docs/mcp.md b/docs/mcp.md index d698534089..1c9c20ff48 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17313,6 +17313,27 @@ locked". Select by Link Status… lists every image and placed document with its name and filters by status (Show), chooses rows with checkboxes (All / None act on the rows shown), and on Select selects the rows chosen, zooming to them when Zoom to Selection is on (the default). +`addon.select.editPointsOnly {segmentEnds?}` (Edit Points Only…) narrows the selection to the anchor points selected in +it, so that a move or transform that follows acts on those points alone. A path with selected anchor points keeps them. +A path with selected segments drops the segments and keeps its other selected anchor points; the points at the ends of +the segments leave the selection unless `segmentEnds` is `true` (default `false`), which keeps them as selected anchor +points. A path selected whole keeps all its points. A group or compound path selected whole is replaced by the paths +inside it, each selected whole, without hidden and locked ones, without a Shaper Group's original shapes and, while +guides are locked, without paths made into guides. Type, +images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. Only the +selection changes, so there is nothing to undo. It returns `{changed, count, points}`: `changed` is `false` when the +selection already held only anchor points, `count` is the number of paths left selected and `points` the number of +anchor points selected on them. Nothing selected, no anchor point left to keep ("no anchor points are selected"), or a +`segmentEnds` that is not `true` or `false` is an error, and the selection is left as it was. + +```json +{"name":"run_command","arguments":{"command":"addon.select.editPointsOnly","params":{"segmentEnds":false}}} +``` + +In the desktop app, Object › Plug-ins › Selection Tools › Edit Points Only… opens a dialog with Keep Ends of Selected +Segments (off). With Preview on, the canvas shows the narrowed selection; OK keeps it and Cancel puts the selection +back. + ### Vector Halftone (live) `addon.color.halftone` (Effect › Color Effects › Vector Halftone…, also in Object › Plug-ins › Color Effects) draws its diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 032041c2a1..ad53f0194a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1529,6 +1529,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Polygonal Lasso selects anchor points (and gradient mesh points) inside a straight-edged loop, with the Lasso's rule for which points are inside, and is listed under Object › Plug-ins. Its tool is also in the Lasso tool's group in both shipped toolbars, after the Enclosing Lasso, and All Tools lists it there, under Select; a toolbar edited before it joined keeps its saved layout until Reset Toolbar (tests `polygonal_lasso_is_in_the_lasso_flyout`, `a_saved_toolbar_without_polygonal_lasso_keeps_its_layout` and `a_torn_off_lasso_group_shows_polygonal_lasso` in `edit_toolbar::tests`, `polygonal_lasso_is_in_the_lasso_group_once` in `addons::tests`, `headless_lists_the_lasso_group` in `vectorcraft-mcp`). It has no default shortcut. Each click sets a vertex. A double-click, Enter or a click on the first vertex closes the loop, Backspace or Delete removes the last vertex, Escape drops the loop, and Shift keeps the next segment to 45° steps. Shift or Alt held at the first click adds to or subtracts from the selection. This is a VectorCraft addition; scores and estimates are unchanged. Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`. Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`. + Edit Points Only (Object › Plug-ins › Selection Tools, a VectorCraft addition) narrows a Direct Selection to its selected anchor points (`addon.select.editPointsOnly {segmentEnds?}`): selected segments leave the selection, and the points at their ends leave it too unless Keep Ends of Selected Segments is on; paths selected whole keep every point; a group or compound path selected whole gives way to the visible, unlocked paths inside it; type, images, symbols and other objects without anchor points leave the selection. Only the selection changes, so there is no undo step; with nothing left to keep it is an error and the selection stays as it was. The dialog previews the narrowed selection, and Cancel puts the selection back. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`edit_points_only`), `crates/ui-egui/src/addons/select/points_only/tests.rs`, `crates/engine/tests/command_sweep.rs`. The Links panel provides an item right-click context menu on link rows offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Separator, and Embed Image / Unembed…. Right-clicking an unselected row selects that row first; right-clicking a row that is already part of a multi-selection preserves the multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. The Location row of the Links panel's Link Info has a folder button, Show in Folder, that opens the folder of the file Link Info shows in the system's file manager (`links.reveal {id}` with that image's id); the help page describes a folder icon on this row ([Links information](https://helpx.adobe.com/illustrator/using/links-info.html)). The button's name and its off state while the file is missing or no file manager is available (the web build) are VectorCraft's own. Tests: `panels::tests_links::link_infos_location_row_shows_the_file_in_its_folder`. A marquee selects a clip group, or an object on a layer with a clipping mask, only when it reaches the area inside the clipping path, and it measures the art only within that path's bounds. Within the bounds of a mask that is not a rectangle, it can still select art that the mask hides. Direct Selection's marquee still selects the hidden anchor points inside it (#2345). From 8cd15651fbee9394615927fca81296c805f3485c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 12:33:55 -0800 Subject: [PATCH 22/69] Canvas: a touchpad pinch zooms on native Wayland Fixes #5981. The winit patch rev moves from a517b384 to 0dfcec0e (storytold/winit craft/0.30.13, with storytold/winit#20), whose Wayland backend binds zwp_pointer_gestures_v1 and reports a touchpad pinch and rotation as PinchGesture and RotationGesture. egui-winit turns them into Event::Zoom and Event::Rotate, which the canvas already reads, so a pinch zooms about the pointer and a two-finger turn rotates the view. Before, winit's Wayland backend never bound the protocol, so the gesture never reached the app. X11 and XWayland still report no pinch. The same winit range types an Alt + keypad code's character itself on Windows (W36: the WM_CHAR after Alt's release becomes a key press with that text). windows_alt_codes typed it too, which would type it twice, so it now only takes the keypad digits typed with Alt out of the frame. Docs: docs/hardware-parity.md (Trackpad row, Linux), docs/type-parity.md (Alt + numeric-keypad codes row). --- Cargo.lock | 2 +- Cargo.toml | 2 +- apps/vectorcraft/src/app.rs | 2 +- apps/vectorcraft/src/main.rs | 4 +- apps/vectorcraft/src/windows_alt_codes.rs | 175 ++++++++-------------- docs/hardware-parity.md | 2 +- docs/type-parity.md | 2 +- 7 files changed, 69 insertions(+), 120 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d7b77b1065..dbfa5d703c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10067,7 +10067,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winit" version = "0.30.13" -source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc" +source = "git+https://github.com/storytold/winit.git?rev=0dfcec0eb62fda5904137a63a6dd0c3d83295f45#0dfcec0eb62fda5904137a63a6dd0c3d83295f45" dependencies = [ "ahash", "android-activity", diff --git a/Cargo.toml b/Cargo.toml index 41bca3bd33..5bd5b732b5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -217,4 +217,4 @@ egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } +winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" } diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index b91282e7da..d998e23a0d 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -44,7 +44,7 @@ impl eframe::App for App { if let Some(window_frame) = self.window_frame.as_mut() { window_frame(); } - // The characters Alt + keypad codes typed (#5108). + // The keypad digits of Alt + keypad codes leave the frame (#5108). #[cfg(windows)] super::windows_alt_codes::raw_input_hook(raw); // Symbol-font characters a keyboard tool typed (NHM Writer legacy Tamil). diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 5a7d3e33ba..007a9a3bdb 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -695,14 +695,14 @@ fn main() -> std::process::ExitCode { // With Windows Ink, winit reports a pen as a touch and drops its barrel button and which end // is down; the message hook notes each pointer contact and whether it starts with the barrel // button held, and writes the pen's end into the pen feed (`windows_stylus`). It also notes the - // characters Alt + keypad codes type (`windows_alt_codes`). + // keypad digits of Alt + keypad codes (`windows_alt_codes`). #[cfg(windows)] let options = { use winit::platform::windows::EventLoopBuilderExtWindows as _; let mut options = options; options.event_loop_builder = Some(Box::new(|builder| { builder.with_msg_hook(|msg| { - // Alt + keypad codes (#5108), which winit drops; neither hook consumes a message. + // Alt + keypad codes (#5108); neither hook consumes a message. windows_alt_codes::msg_hook(msg); windows_stylus::msg_hook(msg) }); diff --git a/apps/vectorcraft/src/windows_alt_codes.rs b/apps/vectorcraft/src/windows_alt_codes.rs index 0abf65ddc9..c358a65653 100644 --- a/apps/vectorcraft/src/windows_alt_codes.rs +++ b/apps/vectorcraft/src/windows_alt_codes.rs @@ -4,14 +4,12 @@ //! Windows does the work: when Alt comes up after keypad digits, `TranslateMessage` posts a //! `WM_CHAR` holding the character the code stands for (in the system's ANSI code page for a code //! with a leading 0, else its OEM code page), the convention every Windows text field follows -//! (). winit -//! 0.30 reads a `WM_CHAR` only as part of the key press before it, so it drops this one, which -//! follows a key release, and egui never sees the text. winit's message hook ([`msg_hook`]) sees -//! the message before winit handles it: [`AltCodes`] notes keypad digits typed with Alt held, takes -//! the character that follows Alt's release, and [`raw_input_hook`] hands it to the frame as typed -//! text, so the Type tool (or a panel's text field) types it like any other character, in the -//! same undo step as the typing round it. The keypad digits themselves are taken out of the frame, -//! so they don't run a shortcut bound to Alt and a digit. +//! (). winit reports +//! that character as a key press of its own with the character as its text (storytold/winit W36), +//! so egui types it like any other character. Each keypad digit typed with Alt held also arrives +//! as Alt and a digit, which would run a shortcut bound to Alt and that digit: winit's message +//! hook ([`msg_hook`]) sees each message before winit handles it, [`AltCodes`] notes the keypad +//! digits typed with Alt held, and [`raw_input_hook`] takes them out of the frame. //! //! With NumLock off the keypad keys arrive as Insert, End, Down, Page Down, Left, Clear, Right, //! Home, Up and Page Up, and Windows still composes the code from them. They are told from the @@ -29,11 +27,11 @@ use std::cell::RefCell; use egui::{Event, Key}; +#[cfg(windows)] const WM_KEYDOWN: u32 = 0x0100; -const WM_KEYUP: u32 = 0x0101; -const WM_CHAR: u32 = 0x0102; const WM_SYSKEYDOWN: u32 = 0x0104; const WM_SYSKEYUP: u32 = 0x0105; +#[cfg(windows)] const WM_SYSCHAR: u32 = 0x0106; /// `VK_NUMPAD0` to `VK_NUMPAD9` (`winuser.h`): keypad digits with NumLock on. const VK_NUMPAD0: usize = 0x60; @@ -49,25 +47,15 @@ const DIGIT_KEYS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key:: /// Bit 24 of a key message's `lParam`: an extended key, such as the navigation keys beside the /// keypad (the keypad's own keys clear it). const EXTENDED_KEY: isize = 1 << 24; -/// `VK_MENU`, `VK_LMENU` and `VK_RMENU`: Alt. -const ALT_KEYS: [usize; 3] = [0x12, 0xA4, 0xA5]; thread_local! { /// The UI thread's sequence: [`msg_hook`] and [`raw_input_hook`] both run on it. static CODES: RefCell = RefCell::new(AltCodes::default()); } -/// Where an Alt + keypad code stands, from the keyboard messages of the thread's queue. +/// The keypad digits typed with Alt held, from the keyboard messages of the thread's queue. #[derive(Default)] struct AltCodes { - /// Keypad digits typed while Alt has been held. - digits: usize, - /// Alt came up after keypad digits: the next character message is the code's character. - armed: bool, - /// A high surrogate waiting for its low half. - high: Option, - /// Characters the codes typed, for the next frame. - typed: String, /// The digits of the keypad presses and releases with Alt held since the last frame, which /// egui reports as Alt and a digit (or, with NumLock off, Alt and a navigation key): taken /// out of the frame. @@ -88,80 +76,45 @@ fn keypad_digit(wparam: usize, lparam: isize) -> Option { impl AltCodes { /// Note a keyboard message `message` with `wparam` (the virtual-key code, or a UTF-16 unit) - /// and `lparam` (its flags). + /// and `lparam` (its flags). Windows sends a key pressed or released with Alt held as a system + /// key. fn message(&mut self, message: u32, wparam: usize, lparam: isize) { - let keypad = match message { - WM_SYSKEYDOWN | WM_SYSKEYUP => keypad_digit(wparam, lparam), - _ => None, - }; - if let Some(d) = keypad { - // Windows sends a key pressed with Alt held as a system key. - if message == WM_SYSKEYDOWN { - self.digits += 1; - self.armed = false; - } + if matches!(message, WM_SYSKEYDOWN | WM_SYSKEYUP) + && let Some(d) = keypad_digit(wparam, lparam) + { self.keypad_events.push(d); - return; - } - match message { - WM_KEYDOWN | WM_SYSKEYDOWN if ALT_KEYS.contains(&wparam) => {} - // Any other key ends the sequence and keeps its own meaning. - WM_KEYDOWN | WM_SYSKEYDOWN => self.reset(), - WM_KEYUP | WM_SYSKEYUP if ALT_KEYS.contains(&wparam) => { - self.armed = self.digits > 0; - self.digits = 0; - } - WM_CHAR | WM_SYSCHAR if self.armed => { - let unit = (wparam & 0xffff) as u16; - if (0xd800..0xdc00).contains(&unit) { - self.high = Some(unit); - return; - } - let units: Vec = self.high.take().into_iter().chain([unit]).collect(); - self.typed.extend(char::decode_utf16(units).filter_map(Result::ok).filter(|c| !c.is_control())); - self.armed = false; - } - _ => {} } } - fn reset(&mut self) { - self.digits = 0; - self.armed = false; - self.high = None; - } - - /// Hand the frame `events` the characters typed since the last frame, as typed text, and take - /// out the keypad digits typed with Alt held. + /// Take out of the frame `events` the keypad digits typed with Alt held since the last frame. + /// The character a code types comes from winit, as typed text. fn drain(&mut self, events: &mut Vec) { let mut keypad = std::mem::take(&mut self.keypad_events); - if !keypad.is_empty() { - events.retain(|e| { - let Event::Key { key, modifiers, .. } = e else { - return true; - }; - if !modifiers.alt { - return true; - } - // The first keypad key still to take out that egui reports as `key`. - let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key); - match keypad.iter().position(stands_for) { - Some(i) => { - keypad.remove(i); - false - } - None => true, - } - }); - } - if !self.typed.is_empty() { - events.push(Event::Text(std::mem::take(&mut self.typed))); + if keypad.is_empty() { + return; } + events.retain(|e| { + let Event::Key { key, modifiers, .. } = e else { + return true; + }; + if !modifiers.alt { + return true; + } + // The first keypad key still to take out that egui reports as `key`. + let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key); + match keypad.iter().position(stands_for) { + Some(i) => { + keypad.remove(i); + false + } + None => true, + } + }); } } -/// winit's message hook for the keyboard: notes Alt + keypad codes and the characters they type, -/// and hands each message to `windows_symbol_chars`. It never consumes the message. +/// winit's message hook for the keyboard: notes the keypad digits typed with Alt held, and hands +/// each message to `windows_symbol_chars`. It never consumes the message. #[cfg(windows)] #[allow(unsafe_code)] pub fn msg_hook(msg: *const std::ffi::c_void) { @@ -182,7 +135,7 @@ pub fn msg_hook(msg: *const std::ffi::c_void) { } } -/// Before egui reads the main window's frame: the characters Alt + keypad codes typed, as text. +/// Before egui reads the main window's frame: the keypad digits typed with Alt held are taken out. pub fn raw_input_hook(raw: &mut egui::RawInput) { CODES.with(|c| { if let Ok(mut c) = c.try_borrow_mut() { @@ -196,6 +149,9 @@ mod tests { use super::*; const ALT: usize = 0x12; + const WM_KEYDOWN: u32 = 0x0100; + const WM_KEYUP: u32 = 0x0101; + const WM_CHAR: u32 = 0x0102; /// Alt held, keypad digits `code`, Alt released, and the character Windows then posts. fn alt_code(c: &mut AltCodes, code: &str, posted: u16) { @@ -215,59 +171,53 @@ mod tests { } #[test] - fn an_alt_code_types_its_character_when_alt_comes_up() { + fn an_alt_codes_keypad_digits_leave_the_frame_and_its_character_is_typed_once() { let mut c = AltCodes::default(); alt_code(&mut c, "0176", 0xB0); alt_code(&mut c, "0151", 0x2014); - let mut events = vec![key(Key::Num0, true, true), key(Key::Num0, true, false), key(Key::Num1, false, true)]; + // winit reports each code's character as typed text. + let mut events = vec![ + key(Key::Num0, true, true), + key(Key::Num0, true, false), + key(Key::Num1, false, true), + Event::Text("°".into()), + Event::Text("—".into()), + ]; c.drain(&mut events); // The keypad digits typed with Alt are gone (eight presses and eight releases, two here); - // the digit typed without Alt stays, and the characters follow. - assert_eq!(events, vec![key(Key::Num1, false, true), Event::Text("°—".into())]); + // the digit typed without Alt stays, and each character stays once. + assert_eq!(events, vec![key(Key::Num1, false, true), Event::Text("°".into()), Event::Text("—".into())]); let mut events = vec![key(Key::Num0, true, true)]; c.drain(&mut events); assert_eq!(events.len(), 1, "counts don't carry over to a later frame"); } #[test] - fn a_character_without_a_code_before_it_is_left_to_winit() { + fn characters_are_left_to_winit() { let mut c = AltCodes::default(); - // A plain key press's character (winit types it), and Alt pressed and released alone. + // A plain key press's character, Alt pressed and released alone, and a code's character. c.message(WM_KEYDOWN, 0x41, 0); c.message(WM_CHAR, usize::from(b'a'), 0); c.message(WM_SYSKEYDOWN, ALT, 0); c.message(WM_KEYUP, ALT, 0); c.message(WM_CHAR, usize::from(b'b'), 0); + alt_code(&mut c, "0176", 0xB0); let mut events = vec![]; c.drain(&mut events); assert!(events.is_empty(), "{events:?}"); } #[test] - fn another_key_while_alt_is_held_cancels_the_code() { + fn alt_with_another_key_keeps_its_shortcut() { let mut c = AltCodes::default(); c.message(WM_SYSKEYDOWN, ALT, 0); c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0); // Alt+F: a shortcut, not a code. c.message(WM_SYSKEYDOWN, 0x46, 0); c.message(WM_KEYUP, ALT, 0); - c.message(WM_CHAR, 0x41, 0); - let mut events = vec![]; + let mut events = vec![key(Key::Num1, true, true), key(Key::F, true, true)]; c.drain(&mut events); - assert!(!events.iter().any(|e| matches!(e, Event::Text(_))), "{events:?}"); - } - - #[test] - fn a_code_above_the_basic_plane_arrives_as_two_halves() { - let mut c = AltCodes::default(); - c.message(WM_SYSKEYDOWN, ALT, 0); - c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0); - c.message(WM_KEYUP, ALT, 0); - c.message(WM_CHAR, 0xD83D, 0); - c.message(WM_CHAR, 0xDE00, 0); - let mut events = vec![]; - c.drain(&mut events); - assert_eq!(events, vec![Event::Text("😀".into())]); + assert_eq!(events, vec![key(Key::F, true, true)]); } /// Alt held, keypad digits `code` with NumLock off (keypad Insert, End, …, flags without the @@ -284,7 +234,7 @@ mod tests { } #[test] - fn with_numlock_off_the_keypad_keys_type_the_code_and_leave_the_caret_alone() { + fn with_numlock_off_the_keypad_keys_leave_the_caret_alone() { let mut c = AltCodes::default(); alt_code_numlock_off(&mut c, "0176", 0xB0); // What egui reports for keypad 0, 1, 7 and 6 with NumLock off and Alt held, a press and a @@ -296,7 +246,7 @@ mod tests { } events.push(key(Key::Home, false, true)); c.drain(&mut events); - assert_eq!(events, vec![key(Key::Home, false, true), Event::Text("°".into())]); + assert_eq!(events, vec![key(Key::Home, false, true)]); } #[test] @@ -309,11 +259,11 @@ mod tests { let mut events = vec![key(Key::Num5, true, true), key(Key::ArrowDown, true, true), key(Key::PageDown, true, true), key(Key::ArrowLeft, true, true)]; c.drain(&mut events); - assert_eq!(events, vec![Event::Text("—ê".into())]); + assert!(events.is_empty(), "{events:?}"); } #[test] - fn the_separate_navigation_keys_still_move_the_caret_and_cancel_the_code() { + fn the_separate_navigation_keys_still_move_the_caret() { let mut c = AltCodes::default(); c.message(WM_SYSKEYDOWN, ALT, 0); c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[1], 0); @@ -322,7 +272,6 @@ mod tests { c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY); c.message(WM_SYSKEYUP, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY); c.message(WM_KEYUP, ALT, 0); - c.message(WM_CHAR, 0x41, 0); let mut events = vec![key(Key::End, true, true), key(Key::End, true, false), key(Key::Home, true, true), key(Key::Home, true, false)]; c.drain(&mut events); assert_eq!(events, vec![key(Key::Home, true, true), key(Key::Home, true, false)]); diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 0c3a73b8cc..f36a536288 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -25,7 +25,7 @@ It reads the pen's tilt and barrel rotation on macOS and on Linux under X11 and | Pen tilt, bearing, barrel rotation (6D Art Pen) | yes, drives brushes | read from AppKit's tablet events (tilt, and the barrel rotation of a pen that reports one); Calligraphic and Scatter brushes vary with them (#764; not yet tried on a Mac) | with Windows Ink, read from the pen's `POINTER_PEN_INFO` (tilt and barrel rotation where its pen mask says the pen reports them); Calligraphic and Scatter brushes vary with them (#372; not yet tried with a pen) | under X11 and XWayland, read from XInput2 raw events; Calligraphic and Scatter brushes vary with them (#764); **no** on native Wayland | no | partial: native Wayland and the web read none, and Bristle brushes do not use them (an Art brush's Width and a Pattern brush's Scale follow them); 3–6 h (#372) | | Pen eraser end | yes | the eraser end (AppKit's tablet proximity events) selects the Eraser tool and the tip brings back the tool used before, as on Linux (#852; not yet tried on a Mac) | with Windows Ink, an inverted pen or its eraser button (`PEN_FLAG_INVERTED`, `PEN_FLAG_ERASER` in the pen's pointer messages) selects the Eraser tool and the tip brings back the tool used before, as on Linux (not yet tried with a pen) | under X11 and XWayland, the eraser end selects the Eraser tool and the tip brings back the tool used before (#764); **no** on native Wayland | a press of the eraser end (Pointer Events eraser button, `button` 5) selects the Eraser tool, and that press erases; a press of the tip brings back the tool used before; Pointer Events report no end while the pen hovers | partial | | Touch gestures (pinch zoom, two-finger pan, rotate view, Touch workspace) | yes (Windows touch, Surface) | trackpad pinch, scroll and rotate | pinch, pan (a second finger cancels the first finger's tool press, #4198); two-finger tap undo, three-finger redo (#585); in the Touch workspace a two-finger tap switches between the Selection tool and the last drawing tool | same where winit reports touch | eframe until the first pen contact, then Pointer Events (pen and fingers told apart); long press opens the context menu | partial: touch workspace and touch-screen rotation missing, 3–5 h | -| Trackpad (smooth scroll, pinch) | yes | yes | precision touchpads | yes | yes | done | +| Trackpad (smooth scroll, pinch) | yes | yes | precision touchpads | smooth scroll; pinch and rotate on native Wayland where the compositor offers pointer gestures (#5981), not under X11 or XWayland | yes | done | | HiDPI / Retina, per-monitor scale | yes | yes | yes | yes | yes | done; a window dragged between monitors of different scale can still grow on Windows (#1459, open); the custom title bar's window on Windows stays truly borderless so the pointer lines up with what is drawn (#1791, #1758; awaiting the reporter's confirmation) ; macOS cursors use aligned 1×/2× native image representations (#2292), covered by headless construction tests; mixed-display transitions and physical cursor sizing remain unverified, no additional hardware validated | | Multiple monitors: panels and document windows on another screen | yes | no (one OS window) | no | no | — | missing: 6–10 h (with multiple windows, gap G7) | | Display colour profile (proof and display through the monitor's ICC) | yes | yes: the window is tagged sRGB and macOS converts it | yes: the display's default ICC profile, Windows' own conversion with Advanced Color on | X11: colord or `_ICC_PROFILE`; Wayland: sRGB | — | done on macOS, Windows and X11; Wayland and floating document windows remain | diff --git a/docs/type-parity.md b/docs/type-parity.md index 1587d7f8f1..19d84fdaed 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -57,7 +57,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters`: marks spaces, tabs, nonbreaking and narrow nonbreaking spaces, the spaces of a set width, discretionary hyphens, forced line breaks, paragraph ends and the story's end, in horizontal, vertical and right-to-left type and on a path, and none on type in a hidden group or layer; the mark shapes are VectorCraft's own. Evidence: `canvas::tests::hidden_characters_*` | | Spell check (Check Spelling, Auto Spell Check, custom dictionary) | done | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. A right-click on an underlined word lists the words its dictionary suggests (each replaces it in one undo step, `text.editRange`), or No Suggestions, then Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check, checked while it is on. Edit › Edit Custom Dictionary… lists the custom dictionary's words, with an Entry field and Add, Delete and Change, applied on Done (Cancel leaves the dictionary as it was). The modal Check Spelling dialog is done: Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) opens a modal dialog displaying the unrecognized word in sentence context ("Not in Dictionary"), a list of suggestions with double-click or selection to replace ("Change to" field), and action buttons: Ignore, Ignore All, Change (one-step Undo/Redo via `text.editRange`), Change All (batched across occurrences in a single undo step), Add to Dictionary (`text.spelling.addWord`), Done and Cancel, with keyboard navigation (Tab between controls, Enter to Change or Done, Escape to close). Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`), `crates/ui-egui/src/tests/contextmenu.rs` (the right-click), `crates/ui-egui/src/dialogs/custom_dictionary.rs` (the dialog), `crates/ui-egui/src/dialogs/check_spelling.rs` (the Check Spelling dialog). | | Smart Punctuation, Change Case, Find & Replace | done | Type › Smart Punctuation… opens a dialog with the ff, fi, ffi and ff, fl, ffl ligatures, Smart Quotes, Smart Spaces, En, Em Dashes, Ellipses and Expert Fractions, Replace In and Report Results, which lists the count of each replacement; ligatures and fractions are written only where the font has a glyph for them. Evidence: `tests::menucmds::smart_punctuation_ligatures_spaces_and_fractions_are_counted`, `smart_punctuation_skips_ligatures_and_fractions_the_font_lacks`, `smart_spaces_keeps_one_space_after_a_period`, `dialogs::smart_punctuation::tests::menu_item_opens_the_dialog_and_ok_reports_the_counts` | -| Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | +| Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step (winit reports it as typed text), and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; in a floating panel window the keypad digits typed with Alt are not taken out of the frame | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | | Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match, a part still matching exactly when some of its contours run the other way round (an o's counter alone in an even-odd compound). A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them). A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place; a line of one or two glyphs that joins tracked lines in one object takes their tracking. Other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Both also compare the installed fonts not loaded yet, reading their files within VectorCraft's own limits (256 MiB per file, 2 GiB and 500,000 glyphs per search) and loading only the fonts that match; `type.retype` matches them with its tolerance and splits compound paths for them as it does for loaded fonts; in the app the search runs in the background with Cancel (`retype.cancelSearch`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | From 8f3709ce6ec4dc00100b799074fdd5db39585ca1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 13:36:49 -0800 Subject: [PATCH 23/69] Menus: a new window keymap sets the panel rows' shortcuts without a rebuild The window builds its first keymap after the first frame's menus, and the menu model's key held the keymap's address, so the next refresh built the whole model again with nothing else changed. Only the Window menu's panel rows and the Settings rows read their shortcuts from the keymap (Build::decorate). refresh now compares a key without the keymap (rows_key) and keeps the keymap's address on its own. When only the keymap changed, it sets the shortcuts of those rows again and lays the bar out again, leaving the rows' states and the catalog as they were. state_key, which the native menu sync, Help search and the Properties panel read, still holds the keymap. The rows key also holds the user's shortcut set, which the catalog's rows are made from. --- crates/ui-egui/src/menus/model.rs | 136 +++++++++++++++++++++++++++--- 1 file changed, 122 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index fffff70049..6913942fd8 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -40,9 +40,15 @@ pub(crate) struct Menus { /// The pass number of the last frame with a pointer button or a key press ([`pressed_pass`]), `None` before the /// first: the `input` of [`state_key`]. pressed: Option, + /// The address of the window's keymap that the panel rows took their shortcuts from ([`keymap_addr`]), `None` + /// before the window has one. + keymap: Option, /// How many times [`refresh`] built the model. #[cfg(test)] pub(crate) rebuilds: u64, + /// How many times [`refresh`] set the keymap's shortcuts again without building the model ([`refresh_shortcuts`]). + #[cfg(test)] + pub(crate) shortcut_refreshes: u64, /// The menus as built, before a layout. pub(crate) bar: MenuBar, /// `bar` laid out for the shell's target: what the in-window bar shows. @@ -90,14 +96,22 @@ pub(crate) fn translate_label(english: &'static str) -> String { /// doesn't list (panels shown, a tool picked). While an /// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's /// preview, or a typing session), the revision, which each of its previews changes, is left out: -/// the hash changes as the interaction begins and as it ends. +/// the hash changes as the interaction begins and as it ends. The window's keymap, which the shown +/// shortcuts are read from, is in the hash too. pub(crate) fn state_key(app: &VectorcraftApp, input: Option) -> u64 { + let mut h = DefaultHasher::new(); + (rows_key(app, input), keymap_addr(app)).hash(&mut h); + h.finish() +} + +/// [`state_key`] without the window's keymap: what the model's rows are built from. A new keymap alone changes only +/// the shortcuts of the rows that read it, which [`refresh`] sets again without a rebuild ([`refresh_shortcuts`]). +fn rows_key(app: &VectorcraftApp, input: Option) -> u64 { let mut h = DefaultHasher::new(); input.hash(&mut h); app.run_count.hash(&mut h); - // The window's keymap, which the panel rows read their shortcuts from (`Build::decorate`): the framework builds it - // after the first frame's menus, and builds a new one when the bindings or the catalog change. - app.ui_ctx.as_ref().and_then(craft::ui::runtime::commands::keymap).map(|k| std::sync::Arc::as_ptr(&k).addr()).hash(&mut h); + // The user's shortcuts, which the catalog's rows are made from. + std::sync::Arc::as_ptr(&app.shortcut_overrides).addr().hash(&mut h); let s = &app.session; (s.journal.len(), s.active_index(), s.clipboard.is_empty(), s.tool_composing()).hash(&mut h); if let Some(d) = s.active() { @@ -126,12 +140,19 @@ pub(crate) fn state_key(app: &VectorcraftApp, input: Option) -> u64 { } /// Brings the menus up to date once per frame, before the frame's input: the model is built again -/// when the rows' state ([`state_key`]) or the shell's target changed. +/// when the rows' state ([`rows_key`]) or the shell's target changed. When only the window's keymap +/// changed (the framework builds the first one after the first frame's menus), the rows that read +/// their shortcuts from it get them again ([`refresh_shortcuts`]). pub(crate) fn refresh(app: &mut VectorcraftApp, ctx: &egui::Context) { let target = Target::of_shell(&WindowHost::of(ctx).shell()); let press = last_press(app, ctx); - let key = state_key(app, press); + let key = rows_key(app, press); + let keymap = keymap_addr(app); if app.menus.key == Some(key) && app.menus.target == Some(target) { + if app.menus.keymap != keymap { + refresh_shortcuts(app, target); + app.menus.keymap = keymap; + } return; } rebuild(app, target); @@ -141,6 +162,54 @@ pub(crate) fn refresh(app: &mut VectorcraftApp, ctx: &egui::Context) { } app.menus.key = Some(key); app.menus.target = Some(target); + app.menus.keymap = keymap; +} + +/// The address of the window's keymap, which the panel rows read their shortcuts from ([`reads_keymap`]): the framework +/// builds it after the first frame's menus, and builds a new one when the bindings or the catalog change. +fn keymap_addr(app: &VectorcraftApp) -> Option { + app.ui_ctx.as_ref().and_then(craft::ui::runtime::commands::keymap).map(|k| std::sync::Arc::as_ptr(&k).addr()) +} + +/// Whether the row running `id` with `params` shows a shortcut read from the window's keymap ([`Build::decorate`]). +fn reads_keymap(id: &str, params: &Value) -> bool { + matches!(id, "window.panel" | "edit.preferences") && !params.is_null() +} + +/// Sets the shortcuts of the rows that read the window's keymap ([`reads_keymap`]) again and lays the bar out again. +/// The rows' states and the catalog stay as the last rebuild made them. +fn refresh_shortcuts(app: &mut VectorcraftApp, target: Target) { + fn walk(app: &VectorcraftApp, nodes: &mut [Node]) { + for node in nodes { + match node { + Node::Item(item) if reads_keymap(&item.command.id, &item.command.params) => { + let shortcut = super::labels::item_shortcut(app, &item.command.id, &item.command.params); + item.shortcut = shortcut; + } + Node::Submenu { children, .. } => walk(app, children), + _ => {} + } + } + } + let mut bar = std::mem::take(&mut app.menus.bar); + for menu in &mut bar.menus { + walk(app, &mut menu.children); + } + app.menus.bar = bar; + lay_out(app, target); + #[cfg(test)] + { + app.menus.shortcut_refreshes += 1; + } +} + +/// Lays `app.menus.bar` out for `target` into `app.menus.laid`, which is edited only when the laid-out bar differs. +fn lay_out(app: &mut VectorcraftApp, target: Target) { + let options = LayoutOptions::new(APP_NAME).label(&translate_label); + let laid = layout(&app.menus.bar, target, &options).bar; + if *app.menus.laid != laid { + app.menus.laid.edit(|l| *l = laid); + } } /// The pass number of the last frame with a pointer button pressed or released or a key pressed, the frame `ctx` read @@ -294,14 +363,9 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) { row_states(app, &rows, &mut states); crate::panels::panel_menu_states(app, &mut states); - let bar = MenuBar::new(menus); - let options = LayoutOptions::new(APP_NAME).label(&translate_label); - let laid = layout(&bar, target, &options).bar; app.menus.rows = Some(rows); - app.menus.bar = bar; - if *app.menus.laid != laid { - app.menus.laid.edit(|l| *l = laid); - } + app.menus.bar = MenuBar::new(menus); + lay_out(app, target); app.menus.states.edit(|s| *s = states); } @@ -597,7 +661,7 @@ impl Build<'_> { // A panel row shows the chord of the panel's shortcut (`panel:`), which binds `window.panel {panel}`; // a Window row runs it with `toggle: true`, so the framework finds no chord for the row's own command. // Settings' first page shows Preferences' shortcut, which binds `edit.preferences` with no page. - "window.panel" | "edit.preferences" if !params.is_null() => { + _ if reads_keymap(id, params) => { let mut item = item; item.shortcut = super::labels::item_shortcut(self.app, id, params); item @@ -658,6 +722,50 @@ mod tests { assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled)); } + /// A new window keymap with nothing else changed (the framework builds the first one after the first frame's + /// menus) sets the panel rows' shortcuts from it, in the bar and in the laid-out bar, without building the menus + /// again. + #[test] + fn a_new_keymap_alone_sets_the_shortcuts_without_a_rebuild() { + fn clear(nodes: &mut [Node]) { + for node in nodes { + match node { + Node::Item(item) if reads_keymap(&item.command.id, &item.command.params) => item.shortcut = None, + Node::Submenu { children, .. } => clear(children), + _ => {} + } + } + } + fn panel_chords(bar: &MenuBar) -> usize { + bar.items() + .into_iter() + .filter(|it| it.command.id == "window.panel" && it.command.params["toggle"] == true && it.shortcut.is_some()) + .count() + } + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + for _ in 0..2 { + crate::testing::app_frame(&mut app, &ctx, egui::RawInput::default()); + } + let shown = panel_chords(&app.menus.bar); + assert!(shown > 0, "the panel rows show their shortcuts' chords"); + // The menus as a refresh before the window's keymap leaves them. + app.menus.keymap = None; + for menu in &mut app.menus.bar.menus { + clear(&mut menu.children); + } + app.menus.laid.edit(|laid| laid.menus.iter_mut().for_each(|menu| clear(&mut menu.children))); + let (rebuilds, refreshes) = (app.menus.rebuilds, app.menus.shortcut_refreshes); + refresh(&mut app, &ctx); + assert_eq!(app.menus.rebuilds, rebuilds, "a new keymap alone does not build the menus again"); + assert_eq!(app.menus.shortcut_refreshes, refreshes + 1, "the new keymap sets the shortcuts"); + assert_eq!(panel_chords(&app.menus.bar), shown, "the panel rows show their chords again"); + assert_eq!(panel_chords(&app.menus.laid), shown, "the laid-out bar shows them too"); + refresh(&mut app, &ctx); + assert_eq!((app.menus.rebuilds, app.menus.shortcut_refreshes), (rebuilds, refreshes + 1), "the same keymap sets nothing again"); + } + /// A rebuild asks each dimmed row's command once whether it can run, for its state and its reason together. #[test] fn a_rebuild_checks_each_dimmed_row_once() { From e3077d3c1f4e6a34a4237e7233ef40d033bd668b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:18:39 -0800 Subject: [PATCH 24/69] Script check: test the computed-key case of an own saveAs in its own script A computed key such as c[k] = w makes the check unsure for the whole script, so since the last commit every saveAs in that script counts as a write, the ones before the computed key included. The test put that case in the same script as the others, so the own saveAs calls it expected to write nothing were reported. The computed-key case now has its own script and assertion, and the other cases keep theirs. --- crates/scriptcheck/src/tests.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 61474e854f..0493014da0 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -671,18 +671,16 @@ fn the_scripts_own_save_as_writes_no_file() { fn a_changed_or_shared_own_save_as_writes_a_file() { let r = report(concat!( "var f = new File(p);\n", - "var a = {saveAs: function () {}}; var b = {saveAs: function () {}}; var c = {saveAs: function () {}};\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n", "var d = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n", "a.saveAs(f); b['saveAs'](f); a.n = 1; a.n;\n", "a.saveAs = app.activeDocument.saveAs;\n", "b['saveAs'] = w;\n", - "c[k] = w;\n", "delete d.saveAs;\n", "var h = e;\n", "use(g);\n", "a.saveAs(f);\n", "b.saveAs(f);\n", - "c.saveAs(f);\n", "d.saveAs(f);\n", "e.saveAs(f);\n", "g['saveAs'](f);\n", @@ -693,7 +691,11 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { "q['saveAs'](f);\n", "s.saveAs(f);\n", )); - assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16, 18, 19, 21, 22][..])); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13, 14, 16, 17, 19, 20][..])); + // A computed key may name any variable, so every `saveAs` in the script may write, the ones + // before the computed key included. + let r = report("var f = new File(p);\nvar c = {saveAs: function () {}};\nc.saveAs(f);\nc[k] = w;\nc.saveAs(f);\n"); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 5][..])); } /// Only a `var` statement directly in a function body or the global code that gives its first name From 7574374bc038b280468681ed88177f3ec9a3a0ed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:45:51 -0800 Subject: [PATCH 25/69] Docs: Edit Points Only names the paths a group leaves out A group or compound path selected whole gives way to its visible, unlocked paths, without a Shaper Group's original shapes and, while guides are locked, without paths made into guides. --- 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 ad53f0194a..88004065be 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1529,7 +1529,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Polygonal Lasso selects anchor points (and gradient mesh points) inside a straight-edged loop, with the Lasso's rule for which points are inside, and is listed under Object › Plug-ins. Its tool is also in the Lasso tool's group in both shipped toolbars, after the Enclosing Lasso, and All Tools lists it there, under Select; a toolbar edited before it joined keeps its saved layout until Reset Toolbar (tests `polygonal_lasso_is_in_the_lasso_flyout`, `a_saved_toolbar_without_polygonal_lasso_keeps_its_layout` and `a_torn_off_lasso_group_shows_polygonal_lasso` in `edit_toolbar::tests`, `polygonal_lasso_is_in_the_lasso_group_once` in `addons::tests`, `headless_lists_the_lasso_group` in `vectorcraft-mcp`). It has no default shortcut. Each click sets a vertex. A double-click, Enter or a click on the first vertex closes the loop, Backspace or Delete removes the last vertex, Escape drops the loop, and Shift keeps the next segment to 45° steps. Shift or Alt held at the first click adds to or subtracts from the selection. This is a VectorCraft addition; scores and estimates are unchanged. Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`. Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`. - Edit Points Only (Object › Plug-ins › Selection Tools, a VectorCraft addition) narrows a Direct Selection to its selected anchor points (`addon.select.editPointsOnly {segmentEnds?}`): selected segments leave the selection, and the points at their ends leave it too unless Keep Ends of Selected Segments is on; paths selected whole keep every point; a group or compound path selected whole gives way to the visible, unlocked paths inside it; type, images, symbols and other objects without anchor points leave the selection. Only the selection changes, so there is no undo step; with nothing left to keep it is an error and the selection stays as it was. The dialog previews the narrowed selection, and Cancel puts the selection back. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`edit_points_only`), `crates/ui-egui/src/addons/select/points_only/tests.rs`, `crates/engine/tests/command_sweep.rs`. + Edit Points Only (Object › Plug-ins › Selection Tools, a VectorCraft addition) narrows a Direct Selection to its selected anchor points (`addon.select.editPointsOnly {segmentEnds?}`): selected segments leave the selection, and the points at their ends leave it too unless Keep Ends of Selected Segments is on; paths selected whole keep every point; a group or compound path selected whole gives way to the visible, unlocked paths inside it, leaving out a Shaper Group's original shapes and, while guides are locked, paths made into guides; type, images, symbols and other objects without anchor points leave the selection. Only the selection changes, so there is no undo step; with nothing left to keep it is an error and the selection stays as it was. The dialog previews the narrowed selection, and Cancel puts the selection back. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`edit_points_only`), `crates/ui-egui/src/addons/select/points_only/tests.rs`, `crates/engine/tests/command_sweep.rs`. The Links panel provides an item right-click context menu on link rows offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Separator, and Embed Image / Unembed…. Right-clicking an unselected row selects that row first; right-clicking a row that is already part of a multi-selection preserves the multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. The Location row of the Links panel's Link Info has a folder button, Show in Folder, that opens the folder of the file Link Info shows in the system's file manager (`links.reveal {id}` with that image's id); the help page describes a folder icon on this row ([Links information](https://helpx.adobe.com/illustrator/using/links-info.html)). The button's name and its off state while the file is missing or no file manager is available (the web build) are VectorCraft's own. Tests: `panels::tests_links::link_infos_location_row_shows_the_file_in_its_folder`. A marquee selects a clip group, or an object on a layer with a clipping mask, only when it reaches the area inside the clipping path, and it measures the art only within that path's bounds. Within the bounds of a mask that is not a rectangle, it can still select art that the mask hides. Direct Selection's marquee still selects the hidden anchor points inside it (#2345). From c1bfae38c20f96181fbe62dced597f63a1996576 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:11:19 -0800 Subject: [PATCH 26/69] Selection Tools: Edit Points Only keeps explicit anchor picks inside selected groups A path's own anchor pick now wins over its group's whole-path expansion in either selection order, a segmentEnds of null is rejected, and OK in the dialog runs the command outside the preview so dropping Puppet Warp pins adds no undo step. The docs say whole paths still take object transforms. --- crates/engine/src/cmd/addons/select.rs | 10 +++- crates/engine/src/cmd/addons/select/tests.rs | 46 ++++++++++++++++++- crates/ui-egui/src/addons/dialogs.rs | 12 ++++- .../src/addons/select/points_only/tests.rs | 26 +++++++++++ crates/ui-egui/src/dialogs/preview.rs | 6 +++ docs/mcp.md | 18 ++++---- 6 files changed, 105 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index 6c3346ca80..bda973fb2c 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Edit Points Only", ["Object", "Plug-ins", "Selection Tools"], None, - "{segmentEnds?: false (true: the points at the ends of each selected segment stay selected, as anchor points)} narrow the selection to the anchor points selected in it, so that a move or transform that follows acts on those points alone: a path with selected anchor points keeps them; a path with selected segments drops the segments and keeps its other selected anchor points, and the points at the segments' ends leave the selection unless segmentEnds is true; a path selected whole keeps all its points; a group or compound path selected whole gives way to the paths inside it, each selected whole, leaving out hidden and locked ones, a Shaper Group's original shapes and, while guides are locked, paths made into guides; type, images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. With nothing selected, or no anchor point left to keep, it is an error that leaves the selection as it was. Only the selection changes, not the document, so there is nothing to undo → {changed (false when the selection already held only anchor points), count (the paths left selected), points (the anchor points selected on them)}", + "{segmentEnds?: false (true: the points at the ends of each selected segment stay selected, as anchor points; any non-boolean value, including null, is an error)} narrow the selection to paths and their selected anchor points: a path with selected anchor points keeps them; a path with selected segments drops the segments and keeps its other selected anchor points, and the points at the segments' ends leave the selection unless segmentEnds is true; a path selected whole stays selected whole and still receives object transforms, including stroke and effect scaling when enabled; a group or compound path selected whole gives way to the paths inside it, each selected whole unless it has an explicit anchor pick, leaving out hidden and locked ones, a Shaper Group's original shapes and, while guides are locked, paths made into guides; explicit anchor picks take precedence regardless of selection order; type, images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. With nothing selected, or no anchor point left to keep, it is an error that leaves the selection as it was. The command does not add an undo step → {changed (false when the selection already held only anchor points), count (the paths left selected), points (the anchor points selected on them)}", has_doc, edit_points_only ), @@ -242,7 +242,10 @@ fn paths_inside<'a>(n: &'a Node, guides_locked: bool, out: &mut Vec<&'a Node>) { /// `addon.select.editPointsOnly`: narrow the selection to the anchor points selected in it. fn edit_points_only(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.select.editPointsOnly"; - let keep_ends = switch_or(p, "segmentEnds", false, C)?; + let keep_ends = match p.get("segmentEnds") { + None => false, + Some(value) => value.as_bool().ok_or_else(|| bad(C, "`segmentEnds` must be true or false"))?, + }; let guides_locked = s.menu.guides_locked; let st = s.doc()?; let (doc, sel) = (&st.doc, &st.selection); @@ -278,6 +281,9 @@ fn edit_points_only(s: &mut Session, p: &Value) -> Result { let mut inside = vec![]; paths_inside(n, guides_locked, &mut inside); for c in inside { + if sel.objects.contains(&c.id) && sel.anchors.contains_key(&c.id) { + continue; + } if seen.insert(c.id) { kept.push((c.id, c.path_data().map_or(0, |path| path.anchors().count()), None)); } diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index 85844c241d..ec6054a237 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -426,6 +426,44 @@ mod edit_points_only { assert_eq!(picked(&s), (vec![a, b], BTreeMap::new())); } + #[test] + fn explicit_anchor_picks_override_group_expansion_in_either_order() { + for group_first in [true, false] { + let (mut s, a, b) = two(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| { + sel.set(if group_first { vec![group, a] } else { vec![a, group] }); + sel.anchors.insert(a, refs(&[(0, 0)])); + }) + .unwrap(); + let before = s.doc().unwrap().doc.node(a).unwrap().path_data().unwrap().clone(); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": true, "count": 2, "points": 5})); + assert_eq!(s.doc().unwrap().selection.anchors[&a], refs(&[(0, 0)])); + s.execute("object.move", &json!({"dx": 10, "dy": 20})).unwrap(); + let after = s.doc().unwrap().doc.node(a).unwrap().path_data().unwrap(); + for ((_, i, old), (_, _, new)) in before.anchors().zip(after.anchors()) { + if i == 0 { + assert_ne!(new.p, old.p); + } else { + assert_eq!(new.p, old.p, "unselected anchors stay in place"); + } + } + } + } + + #[test] + fn whole_paths_keep_object_transforms_and_stroke_scaling() { + let (mut s, a, _) = two(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + let before = s.doc().unwrap().doc.node(a).unwrap().appearance.stroke_width(); + s.execute(C, &json!({})).unwrap(); + assert!(!s.doc().unwrap().selection.anchors.contains_key(&a)); + s.execute("object.transform", &json!({"matrix": [2, 0, 0, 2, 0, 0], "strokes": true})).unwrap(); + assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.stroke_width() > before); + } + #[test] fn groups_and_compound_paths_give_way_to_their_paths_and_other_objects_leave() { let (mut s, a, b) = two(); @@ -487,7 +525,13 @@ mod edit_points_only { let e = s.execute(C, &json!({})).unwrap_err().to_string(); assert!(e.contains("no anchor points are selected"), "{e}"); assert_eq!(s.doc().unwrap().selection, before); - for p in [json!({"segmentEnds": "yes"}), json!({"segmentEnds": 1}), json!({"segmentEnds": [true]}), json!({"segmentEnd": true})] { + for p in [ + json!({"segmentEnds": null}), + json!({"segmentEnds": "yes"}), + json!({"segmentEnds": 1}), + json!({"segmentEnds": [true]}), + json!({"segmentEnd": true}), + ] { s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]]})).unwrap(); s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "add"})).unwrap(); let before = s.doc().unwrap().selection.clone(); diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 3273764d5f..c2d1f138de 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -157,8 +157,16 @@ fn pump_commit(app: &mut VectorcraftApp) { app.status("The document was reverted. Reopen this dialog to continue."); } else if !on_document { app.status("The add-on settings apply only to the drawing where the dialog opened."); - } else if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) { - app.status(error); + } else { + let params = (spec.params)(&result.fields); + let answer = if spec.command == super::select::points_only::COMMAND { + preview.commit_selection(app, spec.command, params) + } else { + preview.commit(app, spec.command, params) + }; + if let Err(error) = answer { + app.status(error); + } } } Some(None) => { diff --git a/crates/ui-egui/src/addons/select/points_only/tests.rs b/crates/ui-egui/src/addons/select/points_only/tests.rs index 21285a1e8e..ba0bc13b73 100644 --- a/crates/ui-egui/src/addons/select/points_only/tests.rs +++ b/crates/ui-egui/src/addons/select/points_only/tests.rs @@ -55,6 +55,32 @@ fn the_dialog_previews_keeps_on_ok_and_takes_the_segment_ends_from_the_keyboard( assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "a selection change is not an undo step"); } +#[test] +fn ok_drops_puppet_pins_without_an_undo_step() { + for previewing in [true, false] { + let (mut app, a, b) = app(); + app.run("select.set", json!({"ids": [a.0, b.0]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + app.run("object.puppetWarp", json!({"pins": [[35, 35]], "moved": [[35, 35]], "rest": true})).unwrap(); + assert!(app.session.doc().unwrap().doc.puppet.is_some()); + let undo = app.session.doc().unwrap().history.undo.len(); + host::open_item(&mut app, "Selection Tools", "Edit Points Only…"); + let id = host::dialog_id(&app); + if previewing { + host::frame(&mut app); + assert!(app.session.doc().unwrap().doc.puppet.is_none()); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(!app.any_dialog_open()); + let st = app.session.doc().unwrap(); + assert!(st.doc.puppet.is_none()); + assert_eq!(st.selection.objects, vec![a, b]); + assert!(!app.session.in_interaction()); + assert_eq!(st.history.undo.len(), undo, "pin cleanup does not add an undo step"); + } +} + #[test] fn cancel_puts_the_selection_back() { let (app, _, b) = app(); diff --git a/crates/ui-egui/src/dialogs/preview.rs b/crates/ui-egui/src/dialogs/preview.rs index 2e029fc1c6..f1585adc6b 100644 --- a/crates/ui-egui/src/dialogs/preview.rs +++ b/crates/ui-egui/src/dialogs/preview.rs @@ -125,6 +125,12 @@ impl LivePreview { Ok(Value::Null) } + /// OK for a selection command: rolls its preview back and runs the command without an interaction. + pub(crate) fn commit_selection(self, app: &mut VectorcraftApp, cmd: &str, params: Value) -> Result { + self.cancel(app); + Self::default().commit(app, cmd, params) + } + /// Cancel: rolls a shown preview back, and leaves any other edit in progress as it is. pub(crate) fn cancel(self, app: &mut VectorcraftApp) { if self.previewed.is_some() && self.owns(app) { diff --git a/docs/mcp.md b/docs/mcp.md index 1c9c20ff48..65c28a7c38 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17313,18 +17313,20 @@ locked". Select by Link Status… lists every image and placed document with its name and filters by status (Show), chooses rows with checkboxes (All / None act on the rows shown), and on Select selects the rows chosen, zooming to them when Zoom to Selection is on (the default). -`addon.select.editPointsOnly {segmentEnds?}` (Edit Points Only…) narrows the selection to the anchor points selected in -it, so that a move or transform that follows acts on those points alone. A path with selected anchor points keeps them. +`addon.select.editPointsOnly {segmentEnds?}` (Edit Points Only…) narrows the selection to paths and their selected +anchor points. A path with selected anchor points keeps them. A path with selected segments drops the segments and keeps its other selected anchor points; the points at the ends of the segments leave the selection unless `segmentEnds` is `true` (default `false`), which keeps them as selected anchor -points. A path selected whole keeps all its points. A group or compound path selected whole is replaced by the paths -inside it, each selected whole, without hidden and locked ones, without a Shaper Group's original shapes and, while -guides are locked, without paths made into guides. Type, -images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. Only the -selection changes, so there is nothing to undo. It returns `{changed, count, points}`: `changed` is `false` when the +points. A path selected whole stays selected whole and still receives object transforms, including stroke and effect +scaling when enabled. A group or compound path selected whole is replaced by the paths +inside it, each selected whole unless it has an explicit anchor pick. Explicit anchor picks take precedence regardless +of selection order. The command leaves out hidden and locked paths, a Shaper Group's original shapes and, while +guides are locked, paths made into guides. Type, +images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. The command +does not add an undo step. It returns `{changed, count, points}`: `changed` is `false` when the selection already held only anchor points, `count` is the number of paths left selected and `points` the number of anchor points selected on them. Nothing selected, no anchor point left to keep ("no anchor points are selected"), or a -`segmentEnds` that is not `true` or `false` is an error, and the selection is left as it was. +`segmentEnds` that is not `true` or `false` (including `null`) is an error, and the selection is left as it was. ```json {"name":"run_command","arguments":{"command":"addon.select.editPointsOnly","params":{"segmentEnds":false}}} From f99ef023ad76a2a1da0e76a7abd3706119e60b69 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:49:37 -0800 Subject: [PATCH 27/69] Scripts: close checks the artboards the saved file keeps; saves report warnings Document.close(SaveOptions.SAVECHANGES) now judges artboard loss by the file the save writes. A PDF last saved with useArtboards: false is refused, since it holds one page of the art's bounds. A native or .ai file saved with separateArtboards is saved and closed whatever its range names, since the range picks only the separate files; a version 7 .ai file keeps the range check. Document.saveAs, Document.exportFile, app.open and the save that close(SaveOptions.SAVECHANGES) runs write each warning of their command to the console after the method's name (for example "saveAs: SVG keeps 1 of the document's 2 artboards ..."). Script Check reports a file write for a saveAs or exportFile call on the script's own object when the variable is assigned in a loop around the call, since a later iteration may run the call on a document. Loop bodies without braces follow if, else and line breaks, and a variable of the same name that a function declares is kept apart. A test shows that a waiting point change counts as unsaved for Document.saved and close(). --- crates/engine/src/cmd/fileio.rs | 6 + crates/engine/src/script/dom/save_open.rs | 33 ++- crates/engine/src/tests/script_save_open.rs | 73 ++++++ crates/scriptcheck/src/analyze.rs | 6 +- crates/scriptcheck/src/analyze/declared.rs | 263 +++++++++++++++++++- crates/scriptcheck/src/analyze/features.rs | 23 +- crates/scriptcheck/src/tests.rs | 63 +++++ docs/mcp.md | 8 +- docs/target-app-parity.md | 2 +- 9 files changed, 458 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 51d7590f35..21424f7bdc 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -126,6 +126,12 @@ pub use screens::{ preset_rows as screen_preset_rows, }; pub(crate) use svg::lost_artboards_warning as svg_lost_artboards_warning; + +/// Does a save in `format` (a format id) with options `p` write a legacy version 7 `.ai` file, +/// which holds the artboards its own options pick? An unknown version counts as one. +pub(crate) fn saves_legacy_ai(format: &str, p: &serde_json::Value) -> bool { + format == "ai" && formats::format(format).is_none_or(|f| legacy_ai::wanted("file.saveAs", f, p).unwrap_or(true)) +} pub use svg::options_map as svg_options; /// Atomic file writes (a temporary file renamed over the target: a failed write never damages the /// file it replaces), for the apps' own writers too. diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index bf49aae883..9106158e60 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -665,6 +665,17 @@ fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer { r } +/// Runs command `id` with `p` and writes each warning it gives to the console after `method`'s +/// name, as `app.documents.addDocument` does: what a save or an export leaves out of its file, or +/// a linked image an open could not read. → the command's answer. +fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer { + let (answer, value) = super::super::command_value(h, id, p)?; + for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::super::each_line(&format!("{method}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } + Ok(answer) +} + /// The path to give a command for the real path `real`. fn plain(real: std::path::PathBuf) -> String { crate::cmd::findfiles::plain(real).to_string_lossy().into_owned() @@ -728,7 +739,7 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "saveAs", "file.saveAs", &Value::Object(p))))?; Ok(Data::Undefined) } @@ -782,7 +793,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { let named = with_extension(path, &kind, svgz); let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportFile", "document.export", &Value::Object(p))))?; Ok(Data::Undefined) } @@ -831,7 +842,7 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { } h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(std::path::PathBuf::from(path)))); - let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?; + let r = exactly(h, || warned(h, "open", "document.open", &Value::Object(p)))?; let index = match &r { Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { ("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()), @@ -925,12 +936,24 @@ const NO_FILE_TO_SAVE: &str = const SAVES_SOME_ARTBOARDS: &str = "the save would keep only some of its artboards: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; -/// Whether saving `st` with its remembered options would omit artboards. +/// Whether the file that saving `st` with its remembered options writes would omit artboards. A +/// PDF with `useArtboards: false` holds one page of the art's bounds. A native file, or a `.ai` +/// file other than a legacy version 7 one, with `separateArtboards` holds every artboard, and its +/// `range` names only the separate files. fn picks_artboards(st: &crate::doc_state::DocState) -> bool { let options = Value::Object(crate::cmd::fileio::remembered_save_options(st)); if matches!(st.format, "svg" | "svgz") && crate::cmd::fileio::svg_lost_artboards_warning(&st.doc, &options, st.format).is_some() { return true; } + if st.format == "pdf" && options.get("useArtboards") == Some(&Value::Bool(false)) { + return true; + } + if matches!(st.format, "vectorcraft" | "template" | "ai" | "ait") + && options.get("separateArtboards") == Some(&Value::Bool(true)) + && !crate::cmd::fileio::saves_legacy_ai(st.format, &options) + { + return false; + } let count = st.doc.artboards.len(); let pick = serde_json::from_value::(options); match pick.map_err(|e| e.to_string()).and_then(|p| p.resolve(count)) { @@ -969,7 +992,7 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { let name = super::with_doc(h, doc, |_, st| st.title()); let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?; let p = json!({"path": plain(real), "format": format}); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &p)))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "close", "file.saveAs", &p)))?; } _ => return Err(HostError::Error(UNSAVED_CHANGES.into())), } diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 8c09da874c..da96519b6e 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -1010,6 +1010,42 @@ fn closing_with_save_changes_accepts_a_range_covering_all_current_artboards() { let _ = std::fs::remove_dir_all(base); } +/// The artboard check of `close(SaveOptions.SAVECHANGES)` follows the file the save writes: a PDF +/// last saved without its artboards (`useArtboards: false`) is refused, and a `.ai` file whose +/// `range` names only the separate artboard files keeps every artboard and is saved. +#[test] +fn closing_with_save_changes_checks_the_artboards_the_file_keeps() { + let base = folder("closeencoder"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let pdf = dir.join("art.pdf"); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + s.execute("document.save", &json!({"path": pdf.to_string_lossy(), "useArtboards": false})).unwrap(); + let before = std::fs::read(&pdf).unwrap(); + let e = failure( + &mut s, + &base, + "Folder.userData; vc.run('shape.rectangle', {x: 10, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(e.contains("some of its artboards"), "{e}"); + assert_eq!(std::fs::read(&pdf).unwrap(), before, "the PDF is left as it was"); + let mut s = session(&base); + data_folder(&mut s, &base); + let ai = dir.join("all.ai"); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + s.execute("document.save", &json!({"path": ai.to_string_lossy(), "separateArtboards": true, "range": "2"})).unwrap(); + let before = std::fs::read(&ai).unwrap(); + logged( + &mut s, + &base, + "Folder.userData; vc.run('shape.rectangle', {x: 10, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(s.documents().is_empty(), "the .ai file keeps every artboard, so it closes"); + assert_ne!(std::fs::read(&ai).unwrap(), before, "and the change is saved"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn closing_with_save_changes_refuses_svg_artboard_loss_before_writing() { let base = folder("closesvgboards"); @@ -1098,6 +1134,43 @@ fn setting_saved_records_the_saved_state() { let _ = std::fs::remove_dir_all(base); } +/// The warnings of a save go to the console after the method's name. +#[test] +fn save_as_writes_its_warnings_to_the_console() { + let base = folder("warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + let r = run(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("two.svg")))).unwrap(); + let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default(); + assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("saveAs: ")), "{lines:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A point change that waits to be written counts as an unsaved change for `saved` and `close`. +#[test] +fn waiting_point_changes_count_as_unsaved_changes() { + let base = folder("pendingpoints"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File({d} + '/a.svg'));\n\ + d.pathItems[0].pathPoints[0].anchor = [1, 2]; vc.log(d.saved);\n\ + d.saved = true; d.pathItems[0].pathPoints[0].anchor = [3, 4];\n\ + var e = ''; try {{ d.close(); }} catch (x) {{ e = String(x); }} vc.log([e, app.documents.length]);" + ), + ); + assert_eq!(out[0], json!(false), "a waiting point change is unsaved"); + assert!(out[1][0].as_str().unwrap().contains("unsaved changes"), "{}", out[1]); + assert_eq!(out[1][1], json!(1), "close() keeps the document open"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn unchanged_saved_assignments_do_not_record_commands() { let base = folder("savednoop"); diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 869938027f..a66b20ef06 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -531,6 +531,8 @@ impl Chain { /// member chain or a File object assigned in it to an outer name stays. struct Scope { depth: usize, + /// The offset of the body's `{` in the text, which [`Declared::looped`] names it by. + start: usize, saved: HashMap, /// The bracket depth of the `var` statement the body is in, if any: it goes on when the body /// closes. @@ -1234,7 +1236,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if body { let params = self.params.take().map(|(_, names)| names).unwrap_or_default(); if self.scopes.len() < self.acc.limits.nesting { - self.scopes.push(Scope { depth: self.depth(), saved: HashMap::new(), var_depth: self.var_depth.take() }); + self.scopes.push(Scope { depth: self.depth(), start: t.start, saved: HashMap::new(), var_depth: self.var_depth.take() }); // The parameters are the body's own names, and so are the names it declares. for name in params { self.acc.steps = self.acc.steps.saturating_add(1); @@ -1454,11 +1456,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// The variable of the [`ObjectValue::whole`] literal whose `}` the token before `t` was joins /// [`Analyzer::writers`] when `t` ends the value (`;`, `,` or a line break). It is read before `t` /// closes a function body, so a literal given to the body's own variable stays inside the body. + /// Calls inside a loop that assigns the variable use [`Declared::looped`] to classify its methods. fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) && !self.later_full && !self.later.contains(&name) + && !self.declared.looped_full && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { self.writers.insert(name, bits); diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index 48f071d2ac..9079c352ef 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -1,6 +1,6 @@ //! The names declared, read before the analysis. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use super::{Acc, Brackets, Lexer, LineBreaks, Read, Sig, T, catalog, for_in, goes_on_after, goes_on_with, is, member_mark, unquote, word}; @@ -14,6 +14,10 @@ const UNREAD_BINDINGS: &[&str] = &["with", "eval", "Function", catalog::DOLLAR_E /// The property a function reaches `Function` through. const CONSTRUCTOR: &str = "constructor"; +/// The statements whose parentheses the rest of the statement follows, so a line break after them +/// does not end a loop's body without braces. +const HEADS: &[&str] = &["if", "while", "for", "with", "switch"]; + /// The longest property name, in characters, that [`Declared::rebound`] keeps. A string literal in /// brackets that spells a longer one sets [`Declared::unsure`]. const PROPERTY_CHARS: usize = 256; @@ -36,6 +40,16 @@ pub(crate) struct Declared<'s> { /// The property names a member assignment writes (`o.d = …`, `o['d'] = …`). The object may be /// the global object, so a variable of that name may get a value the analysis doesn't read. pub(super) rebound: HashSet, + /// The variables assigned inside a loop, its parentheses included (`name = …`), each by the + /// offset of the `{` of the function body that declares it (`None`: the global code's), with the + /// outermost loops that assign it, entries of `loop_spans`. + pub(super) looped: HashMap<(Option, &'s str), Vec>, + /// For each outermost loop, the offsets in the text where it starts and ends (`usize::MAX`: at + /// the end of the text). + pub(super) loop_spans: Vec<(usize, usize)>, + /// `looped` or `loop_spans` ran out of room, or loops nest past [`crate::Limits::nesting`]: any + /// variable may be assigned in a loop. + pub(super) looped_full: bool, /// The file gives names values the analysis doesn't read in other ways ([`UNREAD_BINDINGS`] or /// a `constructor` property used, a property read, called or assigned whose name in brackets is /// not one string or number literal, which may be a variable's name on the global object @@ -48,12 +62,14 @@ pub(crate) struct Declared<'s> { /// A function body [`Declarations`] is reading: the bracket depth inside it, its entry in /// [`Declared::bodies`], the names it declares so far, and the bracket depth of the `var` statement -/// the body is in, which goes on when the body closes. +/// the body is in, which goes on when the body closes, and the names assigned in a loop inside it +/// so far, each with its loops ([`Declared::looped`]). struct Body<'s> { depth: usize, index: usize, names: HashSet<&'s str>, var_depth: Option, + looped: HashMap<&'s str, Vec>, } /// A `[` [`Declarations`] is reading: the bracket depth inside it, whether a property's name in @@ -87,9 +103,43 @@ struct Declarations<'s, 'a, 'l> { untracked: Option, /// The `[` brackets being read, the innermost last, up to [`crate::Limits::nesting`]. keys: Vec, + /// The loops being read, the innermost last, up to [`crate::Limits::nesting`]. + loops: Vec, out: Declared<'s>, } +/// A loop [`Declarations`] is reading: the bracket depth of its keyword, how far it has been read, +/// and, for a body without braces, whether the last `{` at that depth opened a block (not an object +/// literal), whether an `if`, `while`, `for` or `with` at that depth waits for its `)`, and whether +/// the last token was that `)`. +struct Loop { + depth: usize, + stage: Stage, + block: bool, + head: bool, + after_head: bool, + /// The loop starts with `do` and has a trailing condition. + do_loop: bool, +} + +/// How far a [`Loop`] has been read. +#[derive(Clone, Copy, PartialEq)] +enum Stage { + /// The parentheses after `for` or `while`. + Head, + /// The parentheses after the `while` of a `do` loop. + DoHead, + /// The body's first token is next. + Start, + /// A body in braces. + Block, + /// A body that is one statement without braces. + Statement, + /// The statement of a body without braces has reached its end: the loop ends at the next token, + /// unless it is `else`, which goes on with the statement. + Tail, +} + /// What `src` declares ([`Declared`]), read in one pass over its tokens. pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { let mut lexer = Lexer::new(src, acc.limits.nesting); @@ -103,6 +153,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { bodies: vec![], untracked: None, keys: vec![], + loops: vec![], out: Declared::default(), }; let mut breaks = LineBreaks::default(); @@ -113,6 +164,10 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { Read::Token(sig) => d.token(sig), } } + // A body the file does not close keeps its names assigned in a loop as well. + while let Some(body) = d.bodies.pop() { + d.settle_looped(body); + } let mut out = d.out; out.unsure |= out.rebound.contains(catalog::FOLDER); acc.steps = acc.steps.saturating_add(lexer.steps); @@ -138,12 +193,22 @@ impl<'s> Declarations<'s, '_, '_> { if t.nl && self.var_depth == Some(self.depth()) && !goes_on_after(h0) && !goes_on_with(&t) { self.var_depth = None; } + self.loop_start(&t); if t.kind == T::Punct { self.bracket(&t); } else if t.kind == T::Ident { self.declaration(&t); } let depth = self.depth(); + self.loop_end(&t, depth); + if t.is("=") + && !self.loops.is_empty() + && !member_mark(h1) + && !is(h1, "@") + && let Some(name) = h0.filter(|s| s.kind == T::Ident) + { + self.looped(name.text); + } if let Some(after_new) = self.assign.take() { if t.word("new") && !after_new { self.assign = Some(true); @@ -167,6 +232,191 @@ impl<'s> Declarations<'s, '_, '_> { self.h = [Some(t), h0, h1]; } + /// `t`, a token before the brackets are followed past it: the body of the innermost loop starts + /// at it, and `for`, `while` and `do` start a loop. Past [`crate::Limits::nesting`] loops, any + /// variable may be assigned in one ([`Declared::looped_full`]). + fn loop_start(&mut self, t: &Sig<'s>) { + let [h0, ..] = self.h; + let depth = self.depth(); + while let Some(l) = self.loops.last_mut() { + let after_head = std::mem::take(&mut l.after_head); + match l.stage { + Stage::Start => { + l.stage = if t.is("{") { Stage::Block } else { Stage::Statement }; + l.head = HEADS.iter().any(|w| t.word(w)) && !member_mark(h0); + break; + } + // A line break ends a body of one statement where the tokens on either side of it + // don't go on with it, as in [`Analyzer::token`], and it does not follow the + // parentheses of an `if` or another statement that the body goes on with. + Stage::Statement + if t.nl && depth == l.depth && !goes_on_after(h0) && !goes_on_with(t) && !after_head && !word(h0, "else") && !word(h0, "do") => + { + l.stage = Stage::Tail; + } + Stage::Statement => { + if depth == l.depth { + if t.is("{") { + l.block = t.stmt || after_head || word(h0, "else"); + } else if HEADS.iter().any(|w| t.word(w)) && !member_mark(h0) { + l.head = true; + } + } + break; + } + Stage::Tail if l.do_loop && t.word("while") => { + l.stage = Stage::DoHead; + return; + } + Stage::Tail if t.word("else") => { + l.stage = Stage::Statement; + break; + } + Stage::Tail => { + self.pop_loop(t.start); + // A body of one statement that is this loop ends with it. + if let Some(outer) = self.loops.last_mut() + && outer.stage == Stage::Statement + && outer.depth == depth + { + outer.stage = Stage::Tail; + } + } + _ => break, + } + } + let stage = if (t.word("for") || t.word("while")) && !member_mark(h0) { + Stage::Head + } else if t.word("do") && !member_mark(h0) { + Stage::Start + } else { + return; + }; + if self.loops.len() >= self.acc.limits.nesting || (self.loops.is_empty() && !self.acc.room(self.out.loop_spans.len())) { + self.out.looped_full = true; + } else { + if self.loops.is_empty() { + self.out.loop_spans.push((t.start, usize::MAX)); + } + self.loops.push(Loop { depth, stage, block: false, head: false, after_head: false, do_loop: t.word("do") }); + } + } + + /// Ends the innermost loop at offset `at`, which ends the outermost one in + /// [`Declared::loop_spans`]. + fn pop_loop(&mut self, at: usize) { + self.loops.pop(); + if self.loops.is_empty() + && let Some((_, end)) = self.out.loop_spans.last_mut() + { + *end = at; + } + } + + /// `t`, after the brackets are followed past it to `depth`: the parentheses of a loop end at the + /// `)` back at its depth, and a body in braces at the `}` back at it. A body of one statement + /// reaches its end ([`Stage::Tail`]) at a `;` at the loop's depth, at a `}` there that closes a + /// block, or with a loop that is that statement. A bracket closing below a loop's depth ends it. + fn loop_end(&mut self, t: &Sig<'s>, depth: usize) { + let mut inner = false; + while let Some(l) = self.loops.last_mut() { + let ended = depth < l.depth + || match l.stage { + Stage::Head => { + if t.is(")") && depth == l.depth { + l.stage = Stage::Start; + } + false + } + Stage::DoHead => t.is(")") && depth == l.depth, + Stage::Block => { + if t.is("}") && depth == l.depth && l.do_loop { + l.stage = Stage::Tail; + false + } else { + t.is("}") && depth == l.depth + } + } + Stage::Statement => { + if depth == l.depth { + if t.is(";") || (t.is("}") && l.block) || inner { + l.stage = Stage::Tail; + } else if t.is(")") && l.head { + l.head = false; + l.after_head = true; + } + } + false + } + Stage::Start | Stage::Tail => false, + }; + if !ended { + break; + } + self.pop_loop(t.start); + inner = true; + } + } + + /// `name` is assigned in the loops being read: kept with the outermost one for the innermost + /// function body that declares it when that body closes ([`Self::settle_looped`]), or for the + /// global code. + fn looped(&mut self, name: &'s str) { + let id = self.out.loop_spans.len().saturating_sub(1); + match self.bodies.last_mut() { + Some(body) if body.looped.contains_key(name) || self.acc.room(body.looped.len()) => { + let ids = body.looped.entry(name).or_default(); + if !ids.contains(&id) { + ids.push(id); + } + } + Some(_) => self.out.looped_full = true, + None => self.keep_looped(None, name, vec![id]), + } + } + + /// The names assigned in a loop inside `body`, which is closing: the body's own are kept for it, + /// and the others go to the body around it, or to the global code. + fn settle_looped(&mut self, body: Body<'s>) { + let start = self.out.bodies.get(body.index).map(|(at, _)| *at); + for (name, ids) in body.looped { + if body.names.contains(name) { + self.keep_looped(start, name, ids); + } else if let Some(outer) = self.bodies.last_mut() { + if outer.looped.contains_key(name) || self.acc.room(outer.looped.len()) { + let kept = outer.looped.entry(name).or_default(); + for id in ids { + if !kept.contains(&id) { + kept.push(id); + } + } + } else { + self.out.looped_full = true; + } + } else { + self.keep_looped(None, name, ids); + } + } + } + + /// Keeps `name` of `body` as assigned in outermost loops `ids`. + fn keep_looped(&mut self, body: Option, name: &'s str, ids: Vec) { + let len = self.out.looped.len(); + match self.out.looped.get_mut(&(body, name)) { + Some(kept) => { + for id in ids { + if !kept.contains(&id) { + kept.push(id); + } + } + } + None if self.acc.room(len) => { + self.out.looped.insert((body, name), ids); + } + None => self.out.looped_full = true, + } + } + /// `t`, a token before the brackets are followed past it: notes in [`Declared::rebound`] and /// [`Declared::unsure`] the ways the file gives names values the analysis doesn't read. fn unread_binding(&mut self, t: &Sig<'s>) { @@ -234,7 +484,13 @@ impl<'s> Declarations<'s, '_, '_> { if self.bodies.len() < self.acc.limits.nesting { let index = self.out.bodies.len(); self.out.bodies.push((t.start, vec![])); - self.bodies.push(Body { depth: self.depth(), index, names: HashSet::new(), var_depth: self.var_depth.take() }); + self.bodies.push(Body { + depth: self.depth(), + index, + names: HashSet::new(), + var_depth: self.var_depth.take(), + looped: HashMap::new(), + }); } else if self.untracked.is_none() { self.untracked = Some(self.depth()); } @@ -261,6 +517,7 @@ impl<'s> Declarations<'s, '_, '_> { } while let Some(body) = self.bodies.pop_if(|b| depth < b.depth) { self.var_depth = body.var_depth; + self.settle_looped(body); } if self.untracked.is_some_and(|d| depth < d) { self.untracked = None; diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index bf808469e5..8b6b4c5f1d 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -292,8 +292,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } // `local['saveAs']`: what the object before the bracket defines, for a call that may follow. - "[" => self.index_receiver = self.writer_bits(h0, h1), - "(" => self.call(line), + "[" => self.index_receiver = self.writer_bits(h0, h1, Some(t.start)), + "(" => self.call(t, line), // `Name.prototype["+"] = …` defines an operator. "=" => { let operator = || h1.filter(|s| s.kind == T::Str).is_some_and(|s| catalog::OPERATORS.contains(&unquote(s.text, 4).as_str())); @@ -308,7 +308,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } /// `(` after a name: a call. - fn call(&mut self, line: Option) { + fn call(&mut self, t: &Sig<'s>, line: Option) { let [h0, h1, h2, h3] = self.h; // `doc['saveAs'](f)`: a document method named by a string literal in brackets. if is(h0, "]") @@ -342,7 +342,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { self.acc.feature(FeatureId::FileRead, line); } else if (file && catalog::FILE_WRITES.contains(&n)) - || (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3), n)) + || (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3, Some(t.start)), n)) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); @@ -369,9 +369,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// The methods that `receiver`, which `before` comes before, defines when it is a variable holding /// an object literal of the script's own ([`Analyzer::writers`]), not a property of the same name; /// 0 for anything else. A receiver the check does not follow may be a document. - fn writer_bits(&self, receiver: Option>, before: Option>) -> u8 { + /// At call offset `at`, a variable assigned in a loop containing that offset may be a document. + fn writer_bits(&self, receiver: Option>, before: Option>, at: Option) -> u8 { match receiver { - Some(r) if !self.unsure && r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0), + Some(r) if !self.unsure && r.kind == T::Ident && !member_mark(before) => { + let looped = at.is_some_and(|at| { + self.declared.looped_full + || self.declared.looped.get(&(self.scopes.last().map(|s| s.start), r.text)).is_some_and(|ids| { + ids.iter().any(|id| self.declared.loop_spans.get(*id).is_some_and(|(start, end)| *start <= at && at < *end)) + }) + }); + if looped { 0 } else { self.writers.get(r.text).copied().unwrap_or(0) } + } _ => 0, } } @@ -400,7 +409,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.reassigned_later(&name); } } - let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); + let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before, None) != 0).map(|s| s.text); let escaped = if word(h0, "delete") { // `delete local…` writer(Some(*t), h0) diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 0493014da0..a580c3d311 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -698,6 +698,69 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 5][..])); } +/// A variable assigned in a loop may hold a document when a later iteration calls its `saveAs`, +/// before the assignment in the text: the call writes a file. One assigned only after a loop does +/// not. +#[test] +fn an_own_save_as_reassigned_later_in_a_loop_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}}; var c = {saveAs: function () {}};\n", + "var d = {saveAs: function () {}};\n", + "for (var i = 0; i < 2; i++) { a.saveAs(f); a = app.activeDocument; }\n", + "while (n--) b.saveAs(f), b = app.activeDocument;\n", + "do { c.saveAs(f); } while ((c = next()));\n", + "for (;;) { d.saveAs(f); break; }\n", + "d = app.activeDocument;\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 6][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[4, 5, 6][..])]); + // The `else` of a body without braces is in the loop; a statement after a line break that ends + // such a body is not, and neither is a variable of the same name that a function declares. + let r = report(concat!( + "var f = new File(p);\n", + "var e = {saveAs: function () {}}; var g = {saveAs: function () {}}; var h = {saveAs: function () {}};\n", + "while (n--) if (n) e.saveAs(f); else e = app.activeDocument;\n", + "while (n--) g.saveAs(f), n\n", + "g = app.activeDocument\n", + "function k() { var h; for (;;) h = app.activeDocument; }\n", + "h.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..])); + // An object literal's `}` does not end a body without braces, a call's `)` before a line break + // does, and a literal given after the last loop that assigns its variable is the script's own. + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n", + "while (n--) a.saveAs(f), t = {}, a = app.activeDocument;\n", + "b.saveAs(f);\n", + "while (n--) tick()\n", + "b = app.activeDocument\n", + "for (;;) { c = app.activeDocument; }\n", + "var c = {saveAs: function () {}};\n", + "c.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..])); + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}};\n", + "while (n--) if (n)\n", + " a.saveAs(f), a = app.activeDocument;\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..])); + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n", + "a.saveAs(f); b['saveAs'](f);\n", + "while (n--) { a.saveAs(f); a = app.activeDocument; }\n", + "while (n--) { b['saveAs'](f); b = app.activeDocument; }\n", + "var a = {saveAs: function () {}};\n", + "a.saveAs(f);\n", + "while (n--) { a.saveAs(f); a = app.activeDocument; }\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 8][..])); +} + /// Only a `var` statement directly in a function body or the global code that gives its first name /// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the /// statement. A literal given in a branch, one the value goes on from, one given by an assignment diff --git a/docs/mcp.md b/docs/mcp.md index 2fcb2dc34f..c073a93f02 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3168,9 +3168,13 @@ through `$`: was last saved in and after the same write-access check of the path as `saveAs`, and throws an error and leaves the document open when the document has no file (a converted or recovered document included) or when the save would omit artboards. These refusals occur before writing any files. An SVG or SVGZ save of several - artboards requires Preserve Editing Capabilities to close with `SaveOptions.SAVECHANGES`. + artboards requires Preserve Editing Capabilities to close with `SaveOptions.SAVECHANGES`. A PDF last saved with + `useArtboards: false` omits artboards; a native or `.ai` file (other than a version 7 `.ai` file) saved with + `separateArtboards` keeps every artboard whatever its range names. `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws an error and leaves the document open, since a script cannot - show the prompt. A bad value throws an error before anything is written. + show the prompt. A bad value throws an error before anything is written. The warnings of the save or export that + `saveAs`, `exportFile`, `app.open` and `close` run go to the console, each after the method's name + (`saveAs: …`). - `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`, `getByName(name)`, `removeAll()`, `add()` (a path with no points, from `path.create`, painted as new art; when new diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 13d8c9200e..2ed9a978e8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1127,7 +1127,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - 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: `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, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.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, and read and write only where the script's `File` objects may; 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`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `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`. From 8d5fb2ff6b6d0de7a9f2dc32ed403705a1e79e9f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 17:19:26 -0800 Subject: [PATCH 28/69] Selection Tools: Edit Points Only skips hidden and locked art and keeps the Appearance row Edit Points Only now leaves out selected paths and groups that are hidden or locked, themselves or through an ancestor. Group expansion looks up explicit anchor picks in a set instead of scanning the selection for each path. Canceling the preview restores the active Appearance row, and a preview or OK that succeeds clears the earlier status error. --- crates/engine/src/cmd/addons/select.rs | 6 +- crates/engine/src/cmd/addons/select/tests.rs | 73 +++++++++++++++++++ crates/engine/src/interaction.rs | 1 + crates/engine/src/session/edit.rs | 12 ++- crates/ui-egui/src/addons/dialogs.rs | 5 ++ .../src/addons/select/points_only/tests.rs | 22 ++++++ 6 files changed, 116 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index bda973fb2c..fb8c49aed6 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -254,9 +254,13 @@ fn edit_points_only(s: &mut Session, p: &Value) -> Result { } // Each path once, in selection order, with its points kept: `None` for all of them. let mut seen = HashSet::new(); + let explicit: HashSet = sel.objects.iter().copied().filter(|id| sel.anchors.contains_key(id)).collect(); let mut kept: Vec<(NodeId, usize, Option>)> = vec![]; for id in &sel.objects { let Some(n) = doc.node(*id) else { continue }; + if !doc.ancestry(*id).is_some_and(|ancestors| ancestors.iter().all(|id| doc.node(*id).is_some_and(|n| n.visible && !n.locked))) { + continue; + } match &n.kind { NodeKind::Path { path, .. } => { let Some(refs) = sel.anchors.get(id) else { @@ -281,7 +285,7 @@ fn edit_points_only(s: &mut Session, p: &Value) -> Result { let mut inside = vec![]; paths_inside(n, guides_locked, &mut inside); for c in inside { - if sel.objects.contains(&c.id) && sel.anchors.contains_key(&c.id) { + if explicit.contains(&c.id) { continue; } if seen.insert(c.id) { diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index ec6054a237..6171c08ef9 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -452,6 +452,79 @@ mod edit_points_only { } } + #[test] + fn hidden_or_locked_selected_nodes_and_their_ancestors_are_left_out() { + for locked in [false, true] { + for target in ["path", "group", "ancestor", "layer"] { + let (mut s, a, b) = two(); + let good = rect(&mut s, 200.0, 10.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let blocked = match target { + "path" => a, + "layer" => s.doc().unwrap().doc.layers[0].id, + _ => group, + }; + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let node = doc.node_mut(blocked).unwrap(); + if locked { + node.locked = true; + } else { + node.visible = false; + } + let selected = if matches!(target, "path" | "ancestor") { a } else { group }; + s.execute("select.set", &json!({"ids": [good.0, selected.0]})).unwrap(); + if target == "layer" { + let before = s.doc().unwrap().selection.clone(); + assert!(s.execute(C, &json!({})).is_err()); + assert_eq!(s.doc().unwrap().selection, before); + } else { + s.execute(C, &json!({})).unwrap(); + assert_eq!(picked(&s), (vec![good], BTreeMap::new()), "{target}, locked: {locked}"); + } + } + } + } + + #[test] + fn group_expansion_does_not_scan_the_selection_for_each_descendant() { + let source = include_str!("../select.rs"); + let command = source.split("fn edit_points_only(").nth(1).unwrap(); + assert!(!command.contains("sel.objects.contains(&c.id)"), "descendant lookup must not scan every selected object"); + + let (mut s, _, _) = two(); + let mut groups = vec![]; + let mut paths = vec![]; + for x in [10.0, 100.0, 200.0] { + let a = rect(&mut s, x, 100.0, 20.0, 20.0); + let b = rect(&mut s, x, 150.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + groups.push(NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap())); + paths.extend([a, b]); + } + s.select(|_, sel| sel.set(groups)).unwrap(); + s.execute(C, &json!({})).unwrap(); + assert_eq!(picked(&s), (paths, BTreeMap::new())); + } + + #[test] + fn canceling_a_selection_preview_restores_the_active_appearance_item() { + let (mut s, a, b) = two(); + mixed(&mut s, a, b); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap(); + let before = s.doc().unwrap().doc.node(a).unwrap().appearance.items.clone(); + s.begin_interaction("Edit Points Only").unwrap(); + s.preview(C, &json!({})).unwrap(); + assert_eq!(s.appearance_item(), None); + s.cancel_interaction().unwrap(); + assert_eq!(s.appearance_item(), Some(0)); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let after = &s.doc().unwrap().doc.node(a).unwrap().appearance.items; + assert_ne!(after[0], before[0]); + assert_eq!(&after[1..], &before[1..]); + } + #[test] fn whole_paths_keep_object_transforms_and_stroke_scaling() { let (mut s, a, _) = two(); diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index a2b9417461..dc7b5684fe 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -10,6 +10,7 @@ pub struct Interaction { pub doc: Arc, /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, + pub(crate) active_appearance_item: Option, pub preview: Option<(String, Value)>, /// The active tool began it (a drag): a command from outside the tool runs as a step of its /// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index d5d62e607c..45d0dfd370 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -536,6 +536,7 @@ impl Session { } self.clear_deferred_overlay_cache(); let paint = self.paint.clone(); + let active_appearance_item = self.active_appearance_item.clone(); let st = self.doc_mut()?; if st.interaction.is_some() { return Ok(()); @@ -545,6 +546,7 @@ impl Session { effect: None, doc: st.doc.clone(), selection: Arc::new(st.selection.clone()), + active_appearance_item, preview: None, tool: false, paint, @@ -577,7 +579,7 @@ impl Session { // preview starts from the colors the interaction began with; so does a preview with // `defaultsOnly: true`, and one after it. let tool_paints = self.tool_paints(false) || self.tool_paints(true); - let (paint, restore_paint) = { + let (paint, restore_paint, active_appearance_item) = { let menu = self.menu.clone(); let st = self.doc_mut()?; let Some(it) = &mut st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) }; @@ -599,6 +601,7 @@ impl Session { || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some(); let paint = it.paint.clone(); + let active_appearance_item = it.active_appearance_item.clone(); it.preview_paint = None; it.color_mode_paints = None; it.deferred_color_mode = None; @@ -615,8 +618,9 @@ impl Session { // undone with it. st.restore_isolation(isolation, &undone); cmd::globaledit::follow_history(st); - (paint, restore_paint) + (paint, restore_paint, active_appearance_item) }; + self.active_appearance_item = active_appearance_item; if restore_paint { self.paint = paint.clone(); } @@ -782,10 +786,14 @@ impl Session { self.paint = paint; } let menu = self.menu.clone(); + let active_appearance_item = self.active().and_then(|st| st.interaction.as_ref()).map(|it| it.active_appearance_item.clone()); let st = self.doc_mut()?; st.undo_interaction(); // Guides locked and slices locked or hidden during the interaction stay deselected. deselect_hidden(&menu, &st.doc, &mut st.selection); + if let Some(active_appearance_item) = active_appearance_item { + self.active_appearance_item = active_appearance_item; + } // A canceled preview's Assign Profile is undone with it. self.sync_front_profiles(); // With New Art Has Basic Appearance off, new art takes the appearance of the selection as diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index c2d1f138de..f0642c31fc 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -140,6 +140,9 @@ fn pump_commit(app: &mut VectorcraftApp) { let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label); let answer = preview.run(app, *previewing, label, spec.command, params); app.addon_dialogs.preview = preview; + if spec.command == super::select::points_only::COMMAND && matches!(&answer, Some(Ok(_))) { + app.ui.status.clear(); + } if let (Some(found), Some(answer)) = (spec.found, answer) { host.with(|h| { if let Some(d) = h.get_mut_by_id::(id) { @@ -166,6 +169,8 @@ fn pump_commit(app: &mut VectorcraftApp) { }; if let Err(error) = answer { app.status(error); + } else if spec.command == super::select::points_only::COMMAND { + app.ui.status.clear(); } } } diff --git a/crates/ui-egui/src/addons/select/points_only/tests.rs b/crates/ui-egui/src/addons/select/points_only/tests.rs index ba0bc13b73..ff0fef879f 100644 --- a/crates/ui-egui/src/addons/select/points_only/tests.rs +++ b/crates/ui-egui/src/addons/select/points_only/tests.rs @@ -96,6 +96,28 @@ fn cancel_puts_the_selection_back() { assert_eq!(app.session.doc().unwrap().selection, before); } +#[test] +fn keeping_segment_ends_clears_the_preview_error() { + for previewing in [true, false] { + let (mut app, a, _) = app(); + app.run("select.segments", json!({"id": a.0, "segments": [[0, 0]]})).unwrap(); + host::open_item(&mut app, "Selection Tools", "Edit Points Only…"); + let id = host::dialog_id(&app); + host::frame(&mut app); + assert!(app.ui.status.contains("no anchor points are selected"), "{}", app.ui.status); + host::set(&app, id, "segmentEnds", json!(true)); + if previewing { + host::frame(&mut app); + assert!(app.ui.status.is_empty(), "{}", app.ui.status); + assert_eq!(points(&app, a), (Some(refs(&[(0, 0), (0, 1)])), false)); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(app.ui.status.is_empty(), "{}", app.ui.status); + assert!(!app.any_dialog_open()); + } +} + #[test] fn ok_with_nothing_to_keep_says_why_and_leaves_the_selection() { let (mut app, a, _) = app(); From 3e29a71b9986754961467c16f90c0ec93485d7c7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 18:05:26 -0800 Subject: [PATCH 29/69] Selection Tools: Edit Points Only keeps Appearance row changes and other status messages Replacing or canceling a drag's preview restores the Appearance row only when the preview itself changed it, so a row set or cleared during the drag stays. The dialog clears only its own preview error, and only while it is still the current status message. The group expansion test checks behavior instead of source text. --- crates/engine/src/cmd/addons/select.rs | 2 +- crates/engine/src/cmd/addons/select/tests.rs | 50 +++++++++++++++++-- crates/engine/src/cmd/appearance.rs | 17 ++++++- crates/engine/src/interaction.rs | 8 ++- crates/engine/src/session/edit.rs | 28 +++++++---- crates/ui-egui/src/addons/dialogs.rs | 25 ++++++++-- .../src/addons/select/points_only/tests.rs | 42 ++++++++++++++++ docs/mcp.md | 4 ++ 8 files changed, 154 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index fb8c49aed6..e99294a4b0 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Edit Points Only", ["Object", "Plug-ins", "Selection Tools"], None, - "{segmentEnds?: false (true: the points at the ends of each selected segment stay selected, as anchor points; any non-boolean value, including null, is an error)} narrow the selection to paths and their selected anchor points: a path with selected anchor points keeps them; a path with selected segments drops the segments and keeps its other selected anchor points, and the points at the segments' ends leave the selection unless segmentEnds is true; a path selected whole stays selected whole and still receives object transforms, including stroke and effect scaling when enabled; a group or compound path selected whole gives way to the paths inside it, each selected whole unless it has an explicit anchor pick, leaving out hidden and locked ones, a Shaper Group's original shapes and, while guides are locked, paths made into guides; explicit anchor picks take precedence regardless of selection order; type, images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. With nothing selected, or no anchor point left to keep, it is an error that leaves the selection as it was. The command does not add an undo step → {changed (false when the selection already held only anchor points), count (the paths left selected), points (the anchor points selected on them)}", + "{segmentEnds?: false (true: the points at the ends of each selected segment stay selected, as anchor points; any non-boolean value, including null, is an error)} narrow the selection to paths and their selected anchor points: a path with selected anchor points keeps them; a path with selected segments drops the segments and keeps its other selected anchor points, and the points at the segments' ends leave the selection unless segmentEnds is true; a path selected whole stays selected whole and still receives object transforms, including stroke and effect scaling when enabled; a group or compound path selected whole gives way to the paths inside it, each selected whole unless it has an explicit anchor pick, leaving out hidden and locked ones, a Shaper Group's original shapes and, while guides are locked, paths made into guides; explicit anchor picks take precedence regardless of selection order; type, images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. With nothing selected, or no anchor point left to keep, it is an error that leaves the selection as it was. The command does not add an undo step. In the desktop dialog, a successful preview or OK clears only that dialog's preview error if it is still the current status message → {changed (false when the selection already held only anchor points), count (the paths left selected), points (the anchor points selected on them)}", has_doc, edit_points_only ), diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index 6171c08ef9..4b86ae5802 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -487,11 +487,7 @@ mod edit_points_only { } #[test] - fn group_expansion_does_not_scan_the_selection_for_each_descendant() { - let source = include_str!("../select.rs"); - let command = source.split("fn edit_points_only(").nth(1).unwrap(); - assert!(!command.contains("sel.objects.contains(&c.id)"), "descendant lookup must not scan every selected object"); - + fn group_expansion_selects_each_descendant_path() { let (mut s, _, _) = two(); let mut groups = vec![]; let mut paths = vec![]; @@ -507,6 +503,48 @@ mod edit_points_only { assert_eq!(picked(&s), (paths, BTreeMap::new())); } + #[test] + fn appearance_row_commands_survive_preview_replacement_and_cancel() { + for index in [json!(1), Value::Null] { + for selection_preview in [false, true] { + let (mut s, a, b) = two(); + mixed(&mut s, a, b); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap(); + s.begin_interaction("Drag").unwrap(); + s.doc_mut().unwrap().interaction.as_mut().unwrap().tool = !selection_preview; + if selection_preview { + s.preview(C, &json!({})).unwrap(); + assert_eq!(s.appearance_item(), None); + } else { + s.preview("object.move", &json!({"dx": 10, "dy": 0})).unwrap(); + } + s.execute("appearance.setActiveItem", &json!({"index": index})).unwrap(); + let expected = index.as_u64().map(|i| i as usize); + s.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + assert_eq!(s.appearance_item(), expected, "replacement preserves the explicit row command"); + s.cancel_interaction().unwrap(); + assert_eq!(s.appearance_item(), expected, "cancel preserves the explicit row command"); + } + } + } + + #[test] + fn cancel_preserves_an_appearance_row_command_without_another_preview() { + for index in [json!(1), Value::Null] { + let (mut s, a, b) = two(); + mixed(&mut s, a, b); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap(); + s.begin_interaction("Drag").unwrap(); + s.doc_mut().unwrap().interaction.as_mut().unwrap().tool = true; + s.preview(C, &json!({})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": index})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(s.appearance_item(), index.as_u64().map(|i| i as usize)); + } + } + #[test] fn canceling_a_selection_preview_restores_the_active_appearance_item() { let (mut s, a, b) = two(); @@ -517,6 +555,8 @@ mod edit_points_only { s.begin_interaction("Edit Points Only").unwrap(); s.preview(C, &json!({})).unwrap(); assert_eq!(s.appearance_item(), None); + s.preview(C, &json!({"segmentEnds": true})).unwrap(); + assert_eq!(s.appearance_item(), None); s.cancel_interaction().unwrap(); assert_eq!(s.appearance_item(), Some(0)); s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index d319e0d2a4..a530efce99 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -139,7 +139,7 @@ pub fn specs() -> Vec { "Select Appearance Item", [], None, - "{index: paint-order item index in the first selected object's stack | null} make that fill/stroke row the target of the paint.setFill/setStroke, stroke.set/setAdvanced, paint.editGradient/setGradientGeom, transparency.set and effect.* calls that omit `item` (a fill row brings the Fill proxy forward, a stroke row the Stroke proxy); null or any selection change clears it → {index}", + "{index: paint-order item index in the first selected object's stack | null} make that fill/stroke row the target of the paint.setFill/setStroke, stroke.set/setAdvanced, paint.editGradient/setGradientGeom, transparency.set and effect.* calls that omit `item` (a fill row brings the Fill proxy forward, a stroke row the Stroke proxy); null or any selection change clears it. A row set or cleared outside a drag's preview stays set or cleared when the preview is replaced or canceled → {index}", has_selection, set_active_item ), @@ -174,7 +174,7 @@ pub fn specs() -> Vec { } /// The Appearance panel's active row, remembered for the selection it was chosen in. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct ActiveItem { doc: u64, objects: Vec, @@ -956,6 +956,7 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result { let index = match p.get("index") { Some(Value::Null) => { s.active_appearance_item = None; + clear_preview_item(s); return Ok(json!({ "index": Value::Null })); } Some(_) => index_param(p, "index", C)?, @@ -968,9 +969,21 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result { let doc = st.uid; s.fill_active = fill; s.active_appearance_item = Some(ActiveItem { doc, objects, index }); + clear_preview_item(s); Ok(json!({ "index": index })) } +fn clear_preview_item(s: &mut Session) { + if !s.previewing { + if let Some(it) = s.active_mut().and_then(|st| st.interaction.as_mut()) { + it.active_appearance_item = None; + } + if let Some(held) = &mut s.held_interaction { + held.interaction.active_appearance_item = None; + } + } +} + fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { let cmd = if fill { "appearance.addFill" } else { "appearance.addStroke" }; let mut ids = row_targets(s, p, cmd)?; diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index dc7b5684fe..748dd764cc 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -10,7 +10,7 @@ pub struct Interaction { pub doc: Arc, /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, - pub(crate) active_appearance_item: Option, + pub(crate) active_appearance_item: Option, pub preview: Option<(String, Value)>, /// The active tool began it (a drag): a command from outside the tool runs as a step of its /// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an @@ -53,6 +53,12 @@ pub struct Interaction { pub keep_on_switch: bool, } +#[derive(Clone, Debug)] +pub(crate) struct PreviewAppearanceItem { + pub(crate) before: Option, + pub(crate) after: Option, +} + /// An interaction that a command from outside the tool set aside while it runs /// ([`crate::Session::outside_interaction`]). #[derive(Debug)] diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 45d0dfd370..e337be95ab 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -536,7 +536,6 @@ impl Session { } self.clear_deferred_overlay_cache(); let paint = self.paint.clone(); - let active_appearance_item = self.active_appearance_item.clone(); let st = self.doc_mut()?; if st.interaction.is_some() { return Ok(()); @@ -546,7 +545,7 @@ impl Session { effect: None, doc: st.doc.clone(), selection: Arc::new(st.selection.clone()), - active_appearance_item, + active_appearance_item: None, preview: None, tool: false, paint, @@ -574,12 +573,14 @@ impl Session { if self.script_running() { return Err(EngineError::Busy); } + self.restore_preview_appearance_item(); + let before_item = self.active_appearance_item.clone(); // While the active tool paints with the chosen fill or stroke (the Live Paint Bucket, the // Shape Builder), paint previews of that kind change only the colors it paints with, so each // preview starts from the colors the interaction began with; so does a preview with // `defaultsOnly: true`, and one after it. let tool_paints = self.tool_paints(false) || self.tool_paints(true); - let (paint, restore_paint, active_appearance_item) = { + let (paint, restore_paint) = { let menu = self.menu.clone(); let st = self.doc_mut()?; let Some(it) = &mut st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) }; @@ -601,7 +602,6 @@ impl Session { || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some(); let paint = it.paint.clone(); - let active_appearance_item = it.active_appearance_item.clone(); it.preview_paint = None; it.color_mode_paints = None; it.deferred_color_mode = None; @@ -618,9 +618,8 @@ impl Session { // undone with it. st.restore_isolation(isolation, &undone); cmd::globaledit::follow_history(st); - (paint, restore_paint, active_appearance_item) + (paint, restore_paint) }; - self.active_appearance_item = active_appearance_item; if restore_paint { self.paint = paint.clone(); } @@ -642,8 +641,11 @@ impl Session { } let params = self.noted(params); let batch_paint = (r.is_ok() && cmd == "command.batch").then(|| self.paint.clone()); + let after_item = self.active_appearance_item.clone(); let st = self.doc_mut()?; if let Some(it) = &mut st.interaction { + it.active_appearance_item = + (before_item != after_item).then_some(crate::interaction::PreviewAppearanceItem { before: before_item, after: after_item }); it.used_defaults_only |= ran_defaults_only; // A failed preview leaves the document at the snapshot, so nothing is left to commit // (not even an earlier successful preview, which the reset above already undid). @@ -761,8 +763,18 @@ impl Session { } } + fn restore_preview_appearance_item(&mut self) { + let changed = self.active_mut().and_then(|st| st.interaction.as_mut()).and_then(|it| it.active_appearance_item.take()); + if let Some(changed) = changed + && self.active_appearance_item == changed.after + { + self.active_appearance_item = changed.before; + } + } + pub fn cancel_interaction(&mut self) -> Result<()> { self.put_back_interaction(); + self.restore_preview_appearance_item(); self.clear_deferred_overlay_cache(); self.decoded_images.empty(); self.pending_paint = None; @@ -786,14 +798,10 @@ impl Session { self.paint = paint; } let menu = self.menu.clone(); - let active_appearance_item = self.active().and_then(|st| st.interaction.as_ref()).map(|it| it.active_appearance_item.clone()); let st = self.doc_mut()?; st.undo_interaction(); // Guides locked and slices locked or hidden during the interaction stay deselected. deselect_hidden(&menu, &st.doc, &mut st.selection); - if let Some(active_appearance_item) = active_appearance_item { - self.active_appearance_item = active_appearance_item; - } // A canceled preview's Assign Profile is undone with it. self.sync_front_profiles(); // With New Art Has Basic Appearance off, new art takes the appearance of the selection as diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index f0642c31fc..a1c9dcf5b8 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -34,6 +34,7 @@ pub(crate) struct Spec { pub(crate) struct AddonDialogs { open: Option, preview: LivePreview, + preview_error: Option<(u64, String)>, /// The open Tangent Circle Tool radius dialog. pub(crate) tangent_radius: Option, } @@ -65,6 +66,7 @@ fn active_document(app: &VectorcraftApp) -> Option<(u64, u64)> { /// Closes the open add-on dialog without an answer and rolls its preview back. fn close_open(app: &mut VectorcraftApp) { let Some(open) = app.addon_dialogs.open.take() else { return }; + app.addon_dialogs.preview_error = None; let id = open.id; if let (Some(host), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) { host.with(|h| { @@ -133,6 +135,7 @@ fn pump_commit(app: &mut VectorcraftApp) { if !on_document { // Switching drawings already ends the old preview. Discard its bookkeeping without touching the other drawing. app.addon_dialogs.preview = LivePreview::default(); + app.addon_dialogs.preview_error = None; } let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), (spec.params)(d.fields())))); if on_document && let Some((previewing, params)) = &live { @@ -140,8 +143,12 @@ fn pump_commit(app: &mut VectorcraftApp) { let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label); let answer = preview.run(app, *previewing, label, spec.command, params); app.addon_dialogs.preview = preview; - if spec.command == super::select::points_only::COMMAND && matches!(&answer, Some(Ok(_))) { - app.ui.status.clear(); + if spec.command == super::select::points_only::COMMAND { + match &answer { + Some(Err(_)) => app.addon_dialogs.preview_error = Some((app.ui.status_sets, app.ui.status.clone())), + Some(Ok(_)) => clear_preview_error(app), + None => {} + } } if let (Some(found), Some(answer)) = (spec.found, answer) { host.with(|h| { @@ -170,18 +177,30 @@ fn pump_commit(app: &mut VectorcraftApp) { if let Err(error) = answer { app.status(error); } else if spec.command == super::select::points_only::COMMAND { - app.ui.status.clear(); + clear_preview_error(app); } } + app.addon_dialogs.preview_error = None; } Some(None) => { app.addon_dialogs.open = None; + app.addon_dialogs.preview_error = None; mem::take(&mut app.addon_dialogs.preview).cancel(app); } None if live.is_none() => { app.addon_dialogs.open = None; + app.addon_dialogs.preview_error = None; mem::take(&mut app.addon_dialogs.preview).cancel(app); } None => {} } } + +fn clear_preview_error(app: &mut VectorcraftApp) { + if let Some((sets, error)) = app.addon_dialogs.preview_error.take() + && app.ui.status_sets == sets + && app.ui.status == error + { + app.ui.status.clear(); + } +} diff --git a/crates/ui-egui/src/addons/select/points_only/tests.rs b/crates/ui-egui/src/addons/select/points_only/tests.rs index ff0fef879f..75ddaf5703 100644 --- a/crates/ui-egui/src/addons/select/points_only/tests.rs +++ b/crates/ui-egui/src/addons/select/points_only/tests.rs @@ -96,6 +96,48 @@ fn cancel_puts_the_selection_back() { assert_eq!(app.session.doc().unwrap().selection, before); } +#[test] +fn successful_preview_and_confirmation_preserve_another_status() { + for previewing in [true, false] { + let (mut app, _, _) = app(); + host::open_item(&mut app, "Selection Tools", "Edit Points Only…"); + let id = host::dialog_id(&app); + app.status("The active text edit reported a warning."); + if previewing { + host::frame(&mut app); + assert_eq!(app.ui.status, "The active text edit reported a warning."); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(app.ui.status, "The active text edit reported a warning."); + assert!(!app.any_dialog_open()); + } +} + +#[test] +fn recovering_from_a_preview_error_preserves_a_later_status() { + for previewing in [true, false] { + for same_text in [true, false] { + let (mut app, a, _) = app(); + app.run("select.segments", json!({"id": a.0, "segments": [[0, 0]]})).unwrap(); + host::open_item(&mut app, "Selection Tools", "Edit Points Only…"); + let id = host::dialog_id(&app); + host::frame(&mut app); + assert!(app.ui.status.contains("no anchor points are selected")); + let status = if same_text { app.ui.status.clone() } else { "Another command reported a warning.".to_owned() }; + app.status(status.clone()); + host::set(&app, id, "segmentEnds", json!(true)); + if previewing { + host::frame(&mut app); + assert_eq!(app.ui.status, status); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(app.ui.status, status); + } + } +} + #[test] fn keeping_segment_ends_clears_the_preview_error() { for previewing in [true, false] { diff --git a/docs/mcp.md b/docs/mcp.md index 65c28a7c38..c6a4aff22a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -985,6 +985,8 @@ Cmd+Alt+/ runs `appearance.addStroke` (`press_key {key: "/", mods: {cmd: true, a `item` to edit one of them; `run_command appearance.setActiveItem {"index": n}` makes that row the target of later calls that omit `item` (as clicking the row in the Appearance panel does) until the selection changes; the proxy of its kind (`paint.proxies`) and the Gradient tool's annotator then show that row. +An `appearance.setActiveItem` call made outside a drag's preview keeps its selected row, including an explicit +`index: null`, when the preview is replaced or canceled. `inspect_document` reports it as `paint.appearanceItem`. `paint.setFill` and `paint.setStroke` also take `opacity` (0 to 100, a percentage as in `transparency.set`), which sets the opacity of the fill or stroke row they paint, with or without a new paint, as one undo step. An opacity that no target takes is an error and also leaves the paint @@ -17335,6 +17337,8 @@ anchor points selected on them. Nothing selected, no anchor point left to keep ( In the desktop app, Object › Plug-ins › Selection Tools › Edit Points Only… opens a dialog with Keep Ends of Selected Segments (off). With Preview on, the canvas shows the narrowed selection; OK keeps it and Cancel puts the selection back. +After a failed preview, a successful preview or OK clears the dialog's error only if that error is still the current +status message. Messages from other commands stay displayed. ### Vector Halftone (live) From 1bf9a00828e10dcb8d7576dfbb69afe235b5e589 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 18:40:33 -0800 Subject: [PATCH 30/69] Docs: ROADMAP matches what main ships - Feature breadth: 3D maps graphics on the Materials page (#6960); base materials are still missing. - Simplified Chinese: status and error messages are translated (#2578); the row stays partial at 85%. - Current focus, G11: the Transform effect in a fill's or stroke's own effects is fixed (#5221, #885); the unit preference (#864) remains. --- ROADMAP.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index e317f148d8..752a457682 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -24,7 +24,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)). | | Value | Kind | |---|---|---| -| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 717/719 wired (99.7%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) | +| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 717/719 wired (99.7%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, graphics on the Materials page (#6960), no base materials) | | **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated | | **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated | | **To full parity** | **~360–590 h** one agent · ~95–165 h with 4–6 agents | estimated | @@ -95,7 +95,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta | Language | Code | Status | Translated | |---|---|---|---:| | English | `en` | full | 100% | -| Simplified Chinese | `zh-hans` | partial (messages in English) | 85% | +| Simplified Chinese | `zh-hans` | partial (messages translated, #2578) | 85% | | Spanish | `es` | full | 100% | | Hindi | `hi` | catalog complete; machine-assisted draft, native review pending | complete under the scanner | | Gujarati | `gu` | 4,673 contributor-reviewed catalog rows; 11 corrections applied to the 387 additions | menus and dialogs; status/error messages partial | @@ -119,7 +119,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap 1. **Interaction-fidelity pass** (G1), tool by tool from [ui-parity.md](docs/ui-parity.md): 60–90 h. 2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h. 3. **Launch and stability on real machines** (G10): 20–35 h. -4. **Core-tool correctness** (G11: the unit preference reverting to points, #864, SVG export units fixed; a Transform effect in a fill's or stroke's own effects, #885; Shape Builder regions and Asset Export borders are fixed): 6–13 h. +4. **Core-tool correctness** (G11: the unit preference reverting to points, #864, SVG export units fixed; a Transform effect in a fill's or stroke's own effects (#5221, #885), Shape Builder regions and Asset Export borders are fixed): 6–13 h. 5. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). The Effect Gallery's filter thumbnails and in-dialog preview are in (G2). ## Progress log From 82d4ec4336627df6a4ae241f7c3e27eb6ef68b71 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 19:01:56 -0800 Subject: [PATCH 31/69] Scripts: explicit crop boxes, EPS close-with-save and writer receivers checked per call - document.open with an explicit PDFCROPBOX crop opens on the crop box of a file with editing data; the default keeps the trim box and bleed. - Closing with save changes keeps an EPS document's artboard range, since the EPS file holds the whole document. - The script checker treats a writer receiver captured from an outer scope as able to change before each call, and finds the loop that holds a call with a binary search instead of a scan of every loop. --- crates/engine/src/cmd/fileio/pdfimport.rs | 10 +++- crates/engine/src/script/dom/save_open.rs | 6 +- crates/engine/src/tests/script_save_open.rs | 65 +++++++++++++++++++++ crates/scriptcheck/src/analyze/declared.rs | 40 ++++++++++++- crates/scriptcheck/src/analyze/features.rs | 9 ++- crates/scriptcheck/src/tests.rs | 47 +++++++++++++++ 6 files changed, 170 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 8ffb3f8133..954a345ae0 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -22,6 +22,8 @@ pub struct LoadOptions { pub pages: Option, /// The box each page's artboard (or placed frame) gets. pub crop: CropTo, + /// Whether the options explicitly request the crop box. + pub explicit_crop_box: bool, /// The password of an encrypted PDF. pub password: Option, /// The colour mode the document opens in, its colours converted as Document Color Mode does @@ -67,6 +69,7 @@ impl Default for LoadOptions { Self { pages: None, crop: CropTo::default(), + explicit_crop_box: false, password: None, color_mode: None, grays: Grays::default(), @@ -147,6 +150,7 @@ impl LoadOptions { Ok(Self { pages, crop, + explicit_crop_box: crop == CropTo::Crop && crop_to.or(crop_alias).is_some(), password, color_mode, grays, @@ -173,14 +177,14 @@ impl LoadOptions { } /// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible - /// `.ai`, or a PDF saved with its editing data, asked for its crop box opens on its trim boxes, - /// its editor's artboards, with the bleed round them (its crop box takes the bleed in). + /// `.ai`, or a PDF saved with its editing data, opens on its trim boxes by default, + /// with the bleed around them. An explicit crop-box request uses its crop box. fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result { let pages = match &self.pages { None => None, Some(range) => Some(parse_range(range, opened.page_count()).map_err(|e| err(format!("pages: {e}")))?), }; - let is_ai = self.crop == CropTo::Crop && opened.has_illustrator_data(); + let is_ai = !self.explicit_crop_box && self.crop == CropTo::Crop && opened.has_illustrator_data(); Ok(ImportOptions { pages, crop: if is_ai { CropTo::Trim } else { self.crop }, diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 9106158e60..09c438040c 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -939,8 +939,12 @@ const SAVES_SOME_ARTBOARDS: &str = /// Whether the file that saving `st` with its remembered options writes would omit artboards. A /// PDF with `useArtboards: false` holds one page of the art's bounds. A native file, or a `.ai` /// file other than a legacy version 7 one, with `separateArtboards` holds every artboard, and its -/// `range` names only the separate files. +/// `range` names only the separate files. An EPS file embeds the whole document in its main file, +/// so its `artboardRange` never omits an artboard from what reopens. fn picks_artboards(st: &crate::doc_state::DocState) -> bool { + if st.format == "eps" { + return false; + } let options = Value::Object(crate::cmd::fileio::remembered_save_options(st)); if matches!(st.format, "svg" | "svgz") && crate::cmd::fileio::svg_lost_artboards_warning(&st.doc, &options, st.format).is_some() { return true; diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index da96519b6e..68183e8637 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -741,6 +741,34 @@ fn crop_only_options_apply_to_an_editable_pdf() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn explicit_crop_box_opens_the_bleed_outside_an_editable_files_trim_box() { + let base = folder("explicitcropbox"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + for extension in ["ai", "pdf"] { + let file = dir.join(format!("editable.{extension}")); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + s.execute( + "file.saveAs", + &json!({"path": file.to_string_lossy(), "format": "ai", "preserveEditing": true, + "bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}), + ) + .unwrap(); + assert!(vectorcraft_pdf::has_illustrator_data(&std::fs::read(&file).unwrap(), None)); + let path = quoted(&file); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}));")); + let default = s.active().unwrap().doc.artboards[0].rect; + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}), undefined, {{pDFCropToBox: PDFBoxType.PDFTRIMBOX}});")); + let trim = s.active().unwrap().doc.artboards[0].rect; + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}), undefined, {{pDFCropToBox: PDFBoxType.PDFCROPBOX}});")); + let crop = s.active().unwrap().doc.artboards[0].rect; + assert_eq!((default.width(), default.height()), (trim.width(), trim.height()), "{extension}"); + assert!(crop.width() > trim.width() && crop.height() > trim.height(), "{extension}"); + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn script_document_open_rejects_files_over_the_read_limit() { let base = folder("openreadlimit"); @@ -1046,6 +1074,43 @@ fn closing_with_save_changes_checks_the_artboards_the_file_keeps() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn closing_with_save_changes_keeps_all_eps_artboards_for_subset_ranges() { + let base = folder("closeepsboards"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + for (name, range) in [("single", "2"), ("several", "1-2")] { + let file = dir.join(format!("{name}.eps")); + let path = quoted(&file); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 100, 50);\n\ + vc.run('artboard.new', {{x: 150, y: 0, width: 100, height: 50}});\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 100, height: 50}});\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 20, height: 20}});\n\ + var o = new EPSSaveOptions(); o.saveMultipleArtboards = true; o.artboardRange = '{range}';\n\ + d.saveAs(new File({path}), o);" + ), + ); + let before = std::fs::read(&file).unwrap(); + let nodes = s.active().unwrap().doc.node_count(); + logged( + &mut s, + &base, + "Folder.userData; vc.run('shape.rectangle', {x: 40, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(s.documents().is_empty(), "{range}"); + assert_ne!(std::fs::read(&file).unwrap(), before, "{range}"); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}));")); + assert_eq!(s.active().unwrap().doc.artboards.len(), 3, "{range}"); + assert!(s.active().unwrap().doc.node_count() > nodes, "{range}"); + logged(&mut s, &base, "app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);"); + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn closing_with_save_changes_refuses_svg_artboard_loss_before_writing() { let base = folder("closesvgboards"); diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index 9079c352ef..03ad43ab10 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -22,6 +22,33 @@ const HEADS: &[&str] = &["if", "while", "for", "with", "switch"]; /// brackets that spells a longer one sets [`Declared::unsure`]. const PROPERTY_CHARS: usize = 256; +#[cfg(not(test))] +type LoopSpans = Vec<(usize, usize)>; + +#[cfg(test)] +#[derive(Default)] +pub(super) struct LoopSpans { + spans: Vec<(usize, usize)>, + reads: std::cell::Cell, +} + +#[cfg(test)] +impl std::ops::Deref for LoopSpans { + type Target = Vec<(usize, usize)>; + + fn deref(&self) -> &Self::Target { + self.reads.set(self.reads.get() + 1); + &self.spans + } +} + +#[cfg(test)] +impl std::ops::DerefMut for LoopSpans { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.spans + } +} + /// The names a file's function bodies and its global code declare, read before the analysis. A /// function's `var` statements and the function declarations directly in its body make the names /// they declare the function's own before any statement in it runs, and the function declarations @@ -46,7 +73,7 @@ pub(crate) struct Declared<'s> { pub(super) looped: HashMap<(Option, &'s str), Vec>, /// For each outermost loop, the offsets in the text where it starts and ends (`usize::MAX`: at /// the end of the text). - pub(super) loop_spans: Vec<(usize, usize)>, + pub(super) loop_spans: LoopSpans, /// `looped` or `loop_spans` ran out of room, or loops nest past [`crate::Limits::nesting`]: any /// variable may be assigned in a loop. pub(super) looped_full: bool, @@ -60,6 +87,13 @@ pub(crate) struct Declared<'s> { pub(super) unsure: bool, } +#[cfg(test)] +impl Declared<'_> { + pub(crate) fn loop_span_reads(&self) -> usize { + self.loop_spans.reads.get() + } +} + /// A function body [`Declarations`] is reading: the bracket depth inside it, its entry in /// [`Declared::bodies`], the names it declares so far, and the bracket depth of the `var` statement /// the body is in, which goes on when the body closes, and the names assigned in a loop inside it @@ -169,6 +203,10 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { d.settle_looped(body); } let mut out = d.out; + for ids in out.looped.values_mut() { + ids.sort_unstable(); + ids.dedup(); + } out.unsure |= out.rebound.contains(catalog::FOLDER); acc.steps = acc.steps.saturating_add(lexer.steps); out diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 8b6b4c5f1d..48db72caad 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -373,13 +373,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn writer_bits(&self, receiver: Option>, before: Option>, at: Option) -> u8 { match receiver { Some(r) if !self.unsure && r.kind == T::Ident && !member_mark(before) => { + let Some(bits) = self.writers.get(r.text).copied() else { return 0 }; + if at.is_some() && !self.scopes.is_empty() && !self.declared_in_body(r.text) { + return 0; + } let looped = at.is_some_and(|at| { self.declared.looped_full || self.declared.looped.get(&(self.scopes.last().map(|s| s.start), r.text)).is_some_and(|ids| { - ids.iter().any(|id| self.declared.loop_spans.get(*id).is_some_and(|(start, end)| *start <= at && at < *end)) + let next = self.declared.loop_spans.partition_point(|(start, _)| *start <= at); + next.checked_sub(1).is_some_and(|id| at < self.declared.loop_spans[id].1 && ids.binary_search(&id).is_ok()) }) }); - if looped { 0 } else { self.writers.get(r.text).copied().unwrap_or(0) } + if looped { 0 } else { bits } } _ => 0, } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index a580c3d311..2991b1c23f 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -790,6 +790,34 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..])); } +#[test] +fn writer_calls_after_many_assignment_loops_have_bounded_work() { + for reinitialize in [false, true] { + let mut src = "var d = {saveAs: function () {}};\n".to_string(); + for _ in 0..512 { + src.push_str("while (n--) { d = next(); }\n"); + } + if reinitialize { + src.push_str("var d = {saveAs: function () {}};\n"); + } + src.push_str("var local = {saveAs: function () {}};\n"); + for _ in 0..2048 { + src.push_str("d.saveAs(f); local.saveAs(f);\n"); + } + let limits = Limits::default(); + let mut acc = report::Acc::new(&limits); + let declared = analyze::declarations(&src, &mut acc); + let before = declared.loop_span_reads(); + analyze::scan(&src, &declared, &[], None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc); + let reads = declared.loop_span_reads() - before; + if reinitialize { + assert!(reads < 16 * 2048, "{reads} span accesses for 2048 calls on d"); + } else { + assert_eq!(reads, 0); + } + } +} + /// A function body read before the literal that assigns its variable without declaring it may run /// after the literal, so the literal's `saveAs` keeps reporting the write; a body that declares the /// name assigns its own variable. @@ -810,6 +838,25 @@ fn a_function_read_earlier_that_assigns_the_variable_keeps_save_as_writing() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..])); } +#[test] +fn captured_writer_receivers_can_change_before_each_call() { + for method in ["saveAs", "exportFile"] { + for call in [format!("d.{method}(f)"), format!("d['{method}'](f)")] { + for (prefix, suffix) in [("", ""), ("function outer() {\n", "}\nouter();\n")] { + let src = format!( + "{prefix}var d = {{{method}: function () {{}}}};\n\ + function save(f) {{ {call}; }}\n\ + d = app.activeDocument; save(f);\n{suffix}" + ); + let r = report(&src); + let line = if prefix.is_empty() { 2 } else { 3 }; + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[line][..]), "{src}"); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[line][..])], "{src}"); + } + } + } +} + #[test] fn captured_reassignments_keep_save_as_writing_after_a_later_initializer() { let r = report(concat!( From 616987fdec1c901900e0d74ba3e0f333a74436f7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 19:20:11 -0800 Subject: [PATCH 32/69] Properties: the Document sections replay whole, header and body The craft-libs pin moves to current craft-libs main, 19805ced1e, which has craft-libs#4359: a MemoView's content keeps the flow start and gap of the Stack around it. Each memoized Document section now shows in its MemoView with its header, so an idle frame replays the header as well as the body. Before that change in craft-libs, the Document section stood 18 pt lower in a MemoView and each later memoized section 5 pt lower again. The pin also moves the craft-web-api dependency of vectorcraft-web, the rev that `cargo xtask pdf-deps` checks, and the winit rev to 0dfcec0eb6, the one craft-libs pins. Cargo.lock takes brotli 9.1.3 for craft-i18n, objc2-core-graphics for craft-appkit and craft-platform, and drops core-graphics2 and block. memoized_sections_land_where_direct_ones_do draws the whole panel with nothing selected and compares where its text lands with the sections in their MemoViews and shown directly. It fails at the old pin. --- Cargo.lock | 211 +++++++++--------- Cargo.toml | 76 +++---- apps/vectorcraft-web/Cargo.toml | 2 +- .../panels/properties/document_sections.rs | 121 +++++++--- xtask/src/pdf_deps.rs | 2 +- 5 files changed, 240 insertions(+), 172 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3cb674e4ae..3655542d18 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -626,12 +626,6 @@ dependencies = [ "cpufeatures 0.3.1", ] -[[package]] -name = "block" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" - [[package]] name = "block-buffer" version = "0.10.4" @@ -725,6 +719,17 @@ dependencies = [ "brotli-decompressor 5.0.3", ] +[[package]] +name = "brotli" +version = "9.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9071f285ed78f04f37d675abaaef5de7689e2f30a216c8dc6795465d81910a13" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", + "brotli-decompressor 6.3.2", +] + [[package]] name = "brotli-decompressor" version = "5.0.3" @@ -1184,19 +1189,6 @@ dependencies = [ "libc", ] -[[package]] -name = "core-graphics2" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b65858d95344d2711161cd92196732f67d6c5fea238cf12f994584828731a5c" -dependencies = [ - "bitflags 2.13.2", - "block", - "cfg-if", - "core-foundation 0.10.1", - "libc", -] - [[package]] name = "core_detect" version = "1.0.0" @@ -1239,7 +1231,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-automation", "craft-behavior", @@ -1280,7 +1272,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "crc32fast", "flate2", @@ -1291,18 +1283,19 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "block2 0.6.2", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-core-graphics", "objc2-foundation 0.3.2", ] [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "rustix 1.1.6", ] @@ -1310,7 +1303,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1335,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1353,7 +1346,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-docpath", @@ -1371,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "crc32fast", "flate2", @@ -1380,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "egui", ] @@ -1388,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "md-5", "rayon", @@ -1397,12 +1390,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-cms", @@ -1422,7 +1415,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-control-protocol", "craft-platform", @@ -1433,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1443,7 +1436,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "rayon", ] @@ -1451,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1477,7 +1470,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "blake3", "craft-ecproj-format", @@ -1493,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "serde", ] @@ -1501,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1520,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-codepage", "encoding_rs", @@ -1532,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "serde", "serde_json", @@ -1542,12 +1535,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1562,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1581,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1590,7 +1583,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "cap-primitives", "craft-atomic", @@ -1613,12 +1606,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "gif", ] @@ -1626,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "flate2", ] @@ -1634,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1647,8 +1640,10 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ + "brotli 9.1.3", + "brotli-decompressor 6.3.2", "chrono", "fixed_decimal", "icu_calendar", @@ -1675,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-dds", "craft-jpeg", @@ -1702,7 +1697,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1720,7 +1715,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "thiserror 2.0.21", ] @@ -1728,7 +1723,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1739,7 +1734,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-host", "craft-i18n", @@ -1754,7 +1749,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-i18n", @@ -1768,7 +1763,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-host", @@ -1786,7 +1781,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1798,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "encoding_rs", "image", @@ -1809,7 +1804,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "chrono", "craft-codepage", @@ -1819,7 +1814,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-keymap", @@ -1835,7 +1830,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "flate2", "serde", @@ -1846,7 +1841,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1858,12 +1853,12 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "async-channel", "async-io", "async-process", - "core-graphics2", + "craft-appkit", "craft-atomic", "craft-docpath", "craft-host", @@ -1873,6 +1868,8 @@ dependencies = [ "js-sys", "log", "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", "rfd", "serde", "serde_json", @@ -1889,7 +1886,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1898,7 +1895,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-host", @@ -1922,7 +1919,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1933,7 +1930,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-eps", "flate2", @@ -1947,7 +1944,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "encoding_rs", "flate2", @@ -1958,7 +1955,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "dispatch2", "egui", @@ -1971,7 +1968,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1990,7 +1987,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-atomic", "craft-host", @@ -2007,7 +2004,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "fax", "hayro-ccitt", @@ -2018,7 +2015,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2039,7 +2036,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-keymap", @@ -2051,7 +2048,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2076,7 +2073,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2091,7 +2088,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-atomic", "craft-behavior", @@ -2106,7 +2103,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "serde", "thiserror 2.0.21", @@ -2116,7 +2113,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "serde", "thiserror 2.0.21", @@ -2125,7 +2122,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-keymap", @@ -2140,12 +2137,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2159,7 +2156,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-i18n", @@ -2175,7 +2172,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "accesskit", "craft-behavior", @@ -2213,7 +2210,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2224,7 +2221,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-host", @@ -2242,7 +2239,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-host", @@ -2263,7 +2260,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-host", @@ -2284,7 +2281,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-host", @@ -2303,7 +2300,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "base64 0.22.1", "chrono", @@ -2335,7 +2332,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "flate2", "serde", @@ -2346,7 +2343,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2356,7 +2353,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "js-sys", "serde_json", @@ -2367,7 +2364,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "winsafe", ] @@ -2375,7 +2372,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-appkit", "craft-atomic", @@ -2407,7 +2404,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3762,16 +3759,16 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ - "brotli", + "brotli 8.0.4", "hayro-postscript", ] [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3789,7 +3786,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3807,12 +3804,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "flate2", "hayro-ccitt", @@ -4795,7 +4792,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4952,7 +4949,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -10067,7 +10064,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winit" version = "0.30.13" -source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc" +source = "git+https://github.com/storytold/winit.git?rev=0dfcec0eb62fda5904137a63a6dd0c3d83295f45#0dfcec0eb62fda5904137a63a6dd0c3d83295f45" dependencies = [ "ahash", "android-activity", diff --git a/Cargo.toml b/Cargo.toml index 7ad3e4cfeb..f32179e124 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,49 +10,49 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # 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 = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # 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 = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # 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 = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -192,13 +192,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } @@ -210,4 +210,4 @@ egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed1817 egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } +winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index ce4d1d3d44..98a00a7ca6 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 = "186a229c8da8db5916f8a863dfd894f1879af735", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/ui-egui/src/panels/properties/document_sections.rs b/crates/ui-egui/src/panels/properties/document_sections.rs index cff44b4f44..ca142a9172 100644 --- a/crates/ui-egui/src/panels/properties/document_sections.rs +++ b/crates/ui-egui/src/panels/properties/document_sections.rs @@ -24,35 +24,27 @@ use crate::panels::transform; /// Appearance fill and stroke, the view's rulers, grids, guides and snapping, the keyboard /// increment and Scale Strokes & Effects, and Quick Actions. /// -/// The body of every section but Appearance shows in a `MemoView` keyed on what it reads, so a -/// frame that changes none of it replays the body. What a body picks comes back through an `Outbox` -/// and runs after its section. +/// Every section but Appearance shows in a `MemoView` keyed on what it reads, header and body together, +/// so a frame that changes none of it replays the whole section. What a section picks comes back +/// through an `Outbox` and runs after it. pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { let lang = crate::i18n::current(); let units = app.session.general_unit(); let unit = Unit::ALL.iter().position(|u| *u == units).unwrap_or(usize::MAX); let artboards = app.session.active().map_or(0, |d| d.doc.artboards.len()); let mut picked_units = Vec::new(); - super::section(tl!("Document")).show(ui, |ui, _| { - let document = DocumentProps { unit, units, artboards, lang, picked: Outbox::new(&mut picked_units) }; - let _ = MemoView::new("properties-document", document, document_body).show(ui); - }); + let document = DocumentProps { unit, units, artboards, lang, picked: Outbox::new(&mut picked_units) }; + memoized("properties-document", document, document_section, ui); if let Some(u) = picked_units.pop() { app.run("document.setUnits", json!({ "units": u.label() })).ok(); } super::section(tl!("Appearance")).show(ui, |ui, _| super::appearance_section::fill_stroke_rows(app, ui)); - super::section(tl!("Rulers & Grids")).show(ui, |ui, _| { - let _ = MemoView::new("properties-rulers", Language { lang }, rulers_body).show(ui); - }); - super::section(tl!("Guides")).show(ui, |ui, _| { - let _ = MemoView::new("properties-guides", Language { lang }, guides_body).show(ui); - }); + memoized("properties-rulers", Language { lang }, rulers_section, ui); + memoized("properties-guides", Language { lang }, guides_section, ui); let mut snaps = Vec::new(); let (point, grid) = (app.ui.view.snap_to_point, app.ui.view.snap_to_grid); - super::section(tl!("Snap Options")).show(ui, |ui, _| { - let snap = SnapProps { point, grid, lang, picked: Outbox::new(&mut snaps) }; - let _ = MemoView::new("properties-snap", snap, snap_body).show(ui); - }); + let snap = SnapProps { point, grid, lang, picked: Outbox::new(&mut snaps) }; + memoized("properties-snap", snap, snap_section, ui); for command in snaps { app.run(command, json!({})).ok(); } @@ -62,11 +54,9 @@ pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { let unit = Unit::ALL.iter().position(|u| *u == general).unwrap_or(usize::MAX); let (increment, scale) = (app.session.prefs.keyboard_increment, app.session.prefs.scale_strokes); let (bare_points, lengths) = (app.session.prefs.numbers_without_units_are_points, crate::canvas::rulers::general_lengths(app)); - super::section(tl!("Preferences")).show(ui, |ui, _| { - let picked = Outbox::new(&mut prefs); - let preferences = PreferencesProps { increment, unit, bare_points, lengths, scale, lang, picked }; - let _ = MemoView::new("properties-preferences", preferences, preferences_body).show(ui); - }); + let picked = Outbox::new(&mut prefs); + let preferences = PreferencesProps { increment, unit, bare_points, lengths, scale, lang, picked }; + memoized("properties-preferences", preferences, preferences_section, ui); for pick in prefs { match pick { PreferencePick::Increment(event) => { @@ -79,9 +69,49 @@ pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { PreferencePick::ScaleStrokes(on) => transform::set_pref(app, "scaleStrokes", on), } } - super::section(tl!("Quick Actions")).show(ui, |ui, _| { - let _ = MemoView::new("properties-quick-actions", Language { lang }, quick_actions_body).show(ui); - }); + memoized("properties-quick-actions", Language { lang }, quick_actions_section, ui); +} + +/// Shows `section` in a `MemoView` with `id`, keyed on `props`. Tests can show it directly instead, to compare where +/// the memoized sections land with where direct ones do. +fn memoized(id: &'static str, props: P, section: fn(&mut P, &mut Ui), ui: &mut Ui) { + #[cfg(test)] + if tests::shown_directly() { + let mut props = props; + section(&mut props, ui); + return; + } + let _ = MemoView::new(id, props, section).show(ui); +} + +/// The Document section: its header and [`document_body`]. +fn document_section(p: &mut DocumentProps<'_>, ui: &mut Ui) { + super::section(tl!("Document")).show(ui, |ui, _| document_body(p, ui)); +} + +/// The Rulers & Grids section: its header and [`rulers_body`]. +fn rulers_section(p: &mut Language, ui: &mut Ui) { + super::section(tl!("Rulers & Grids")).show(ui, |ui, _| rulers_body(p, ui)); +} + +/// The Guides section: its header and [`guides_body`]. +fn guides_section(p: &mut Language, ui: &mut Ui) { + super::section(tl!("Guides")).show(ui, |ui, _| guides_body(p, ui)); +} + +/// The Snap Options section: its header and [`snap_body`]. +fn snap_section(p: &mut SnapProps<'_>, ui: &mut Ui) { + super::section(tl!("Snap Options")).show(ui, |ui, _| snap_body(p, ui)); +} + +/// The Preferences section: its header and [`preferences_body`]. +fn preferences_section(p: &mut PreferencesProps<'_>, ui: &mut Ui) { + super::section(tl!("Preferences")).show(ui, |ui, _| preferences_body(p, ui)); +} + +/// The Quick Actions section: its header and [`quick_actions_body`]. +fn quick_actions_section(p: &mut Language, ui: &mut Ui) { + super::section(tl!("Quick Actions")).show(ui, |ui, _| quick_actions_body(p, ui)); } /// What a section that reads only command states reads besides them: the interface language of its labels. @@ -248,6 +278,47 @@ mod tests { SECTION_RUNS.with(std::cell::Cell::get) } + thread_local! { + /// This thread shows the memoized sections directly, outside their `MemoView`s. + static DIRECT: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + pub(super) fn shown_directly() -> bool { + DIRECT.with(std::cell::Cell::get) + } + + /// The runs of text the whole Properties panel paints with nothing selected, after idle frames that replay the + /// memoized sections, with the sections shown in their `MemoView`s or, with `direct`, directly. + fn panel_texts(direct: bool) -> Vec<(String, egui::Rect)> { + DIRECT.with(|d| d.set(direct)); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let mut panel = Panel::new(app, super::super::show); + panel.frame(); + let before = runs(); + panel.frame(); + panel.frame(); + if !direct { + assert_eq!(runs(), before, "the last frames replay the memoized sections"); + } + let texts = panel.texts(); + DIRECT.with(|d| d.set(false)); + texts + } + + /// Whole sections shown in `MemoView`s, header and body, land where the same sections shown directly do under the + /// app's `SectionRhythm::Spaced` and `QuietHeader::Heads`: the Document section under the panel's heading draws no + /// rule above it, and each later section keeps the stack's gap. + #[test] + fn memoized_sections_land_where_direct_ones_do() { + let direct = panel_texts(true); + for heading in ["Document", "Rulers & Grids", "Guides", "Snap Options", "Preferences", "Quick Actions", "Snap to Point"] { + assert!(direct.iter().any(|(text, _)| text == heading), "the panel shows {heading:?}: {direct:?}"); + } + let memoized = panel_texts(false); + assert_eq!(memoized, direct, "memoized sections land where direct ones do"); + } + #[test] fn canceling_the_units_popup_leaves_the_document_unchanged() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index f4f02f8627..d3e0f6e1df 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 = "186a229c8da8db5916f8a863dfd894f1879af735"; +const REV: &str = "19805ced1eee99a0667facfc3e02ca909e7df348"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From 7a799a1bc48c16f66957032c21eb01e835e53ddc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 20:21:31 -0800 Subject: [PATCH 33/69] Properties: Document sections below the fold keep their controls A MemoView in a scroll area skips a view that is out of view, so in a Properties panel too short for every Document section, the sections below the fold registered no focus stops or accessibility nodes until the panel scrolled: Tab and a screen reader did not reach Keyboard Increment, Scale Strokes & Effects or Snap to Grid. Each section's MemoView now shows out of view too, as the sections did before they were memoized. sections_below_the_fold_keep_their_controls draws the panel 200 pt high and finds those controls below it. It fails without shown_out_of_view. --- .../panels/properties/document_sections.rs | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/document_sections.rs b/crates/ui-egui/src/panels/properties/document_sections.rs index ca142a9172..d702cbf899 100644 --- a/crates/ui-egui/src/panels/properties/document_sections.rs +++ b/crates/ui-egui/src/panels/properties/document_sections.rs @@ -72,7 +72,8 @@ pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { memoized("properties-quick-actions", Language { lang }, quick_actions_section, ui); } -/// Shows `section` in a `MemoView` with `id`, keyed on `props`. Tests can show it directly instead, to compare where +/// Shows `section` in a `MemoView` with `id`, keyed on `props`. A section scrolled out of view still runs or replays, so +/// its controls keep their focus stops and accessibility nodes. Tests can show it directly instead, to compare where /// the memoized sections land with where direct ones do. fn memoized(id: &'static str, props: P, section: fn(&mut P, &mut Ui), ui: &mut Ui) { #[cfg(test)] @@ -81,7 +82,7 @@ fn memoized(id: &'static str, props: P, section: fn(&mut P, &mut U section(&mut props, ui); return; } - let _ = MemoView::new(id, props, section).show(ui); + let _ = MemoView::new(id, props, section).shown_out_of_view().show(ui); } /// The Document section: its header and [`document_body`]. @@ -319,6 +320,22 @@ mod tests { assert_eq!(memoized, direct, "memoized sections land where direct ones do"); } + /// In a panel too short for every section, the sections below the fold still register their controls, so Tab + /// and a screen reader reach them before the panel scrolls. + #[test] + fn sections_below_the_fold_keep_their_controls() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let mut panel = Panel::new(app, super::super::show); + panel.room(egui::vec2(300.0, 200.0)); + panel.frame(); + panel.frame(); + for name in ["Keyboard Increment", "Scale Strokes & Effects", "Snap to Grid"] { + assert!(panel.shows(name), "the panel registers {name:?} below the fold"); + assert!(panel.rect(name).top() > 200.0, "{name:?} is below the fold of a 200 pt panel"); + } + } + #[test] fn canceling_the_units_popup_leaves_the_document_unchanged() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); From d9609ce53ca8085c8013de84779852e2beeef5e7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 20:45:12 -0800 Subject: [PATCH 34/69] Dependencies: pin craft-libs 5190e08ab, current main craft-libs main took eight more pull requests after 19805ced1e (raster 3D, mesh ops, SVG group ancestry, image dimensions, footer bar wrapping). Every craft-libs rev, the craft-web-api line and the rev `cargo xtask pdf-deps` checks move to it. Its egui and winit revs are the ones VectorCraft already pins, and Cargo.lock changes only the craft-libs source lines. --- Cargo.lock | 170 ++++++++++++++++---------------- Cargo.toml | 74 +++++++------- apps/vectorcraft-web/Cargo.toml | 2 +- xtask/src/pdf_deps.rs | 2 +- 4 files changed, 124 insertions(+), 124 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1e38ca2a4f..fbe934ae2c 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "egui", ] @@ -1381,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "rayon", ] @@ -1444,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "serde", ] @@ -1494,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "gif", ] @@ -1619,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "flate2", ] @@ -1627,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "chrono", "craft-codepage", @@ -1822,7 +1822,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-keymap", @@ -1838,7 +1838,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "flate2", "serde", @@ -1849,7 +1849,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1861,7 +1861,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "async-channel", "async-io", @@ -1894,7 +1894,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1903,7 +1903,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-host", @@ -1927,7 +1927,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1938,7 +1938,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-eps", "flate2", @@ -1952,7 +1952,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "encoding_rs", "flate2", @@ -1963,7 +1963,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "dispatch2", "egui", @@ -1976,7 +1976,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1995,7 +1995,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-atomic", "craft-host", @@ -2012,7 +2012,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "fax", "hayro-ccitt", @@ -2023,7 +2023,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2044,7 +2044,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-keymap", @@ -2056,7 +2056,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2081,7 +2081,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2096,7 +2096,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-atomic", "craft-behavior", @@ -2111,7 +2111,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "serde", "thiserror 2.0.21", @@ -2121,7 +2121,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "serde", "thiserror 2.0.21", @@ -2130,7 +2130,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-keymap", @@ -2145,12 +2145,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2164,7 +2164,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-i18n", @@ -2180,7 +2180,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "accesskit", "craft-behavior", @@ -2218,7 +2218,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2229,7 +2229,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-host", @@ -2247,7 +2247,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-host", @@ -2268,7 +2268,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-host", @@ -2289,7 +2289,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-host", @@ -2308,7 +2308,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "base64 0.22.1", "chrono", @@ -2340,7 +2340,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "flate2", "serde", @@ -2351,7 +2351,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2361,7 +2361,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "js-sys", "serde_json", @@ -2372,7 +2372,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "winsafe", ] @@ -2380,7 +2380,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-appkit", "craft-atomic", @@ -2412,7 +2412,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3767,7 +3767,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3776,7 +3776,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3794,7 +3794,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3812,12 +3812,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "flate2", "hayro-ccitt", @@ -4800,7 +4800,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4957,7 +4957,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index 4ec887ba19..0c31608537 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,49 +10,49 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # 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 = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # 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 = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # 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 = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # Nightly profile isolation, launch protocol, and security fence. craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" } # internal @@ -194,13 +194,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 98a00a7ca6..e72a7f26ed 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 = "19805ced1eee99a0667facfc3e02ca909e7df348", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6", 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 d3e0f6e1df..668abfea2e 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 = "19805ced1eee99a0667facfc3e02ca909e7df348"; +const REV: &str = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From 87005e7ae710410022062cfb0f11f61c9e671c5d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 22:58:55 -0800 Subject: [PATCH 35/69] Docs: readiness and depth scores match what main ships Rescore the area, dimension and audience tables against the code on main, using each doc's own formulas: feature depth 8342/105 (~79%), breadth ~96% (menu items 815 of 816 wired, tools 91 of 92, vector effects 50 of 50), full readiness ~67%, mainstream ~65%, essentials ~77%, UI/UX ~60%. File formats stay at ~75%. Stability, Raster effects in ROADMAP, and Export/print in the essentials table go down where open crash reports or the area table say so. Hours are not recomputed. --- README.md | 4 +- ROADMAP.md | 54 ++++++++-------- docs/effects-parity.md | 2 +- docs/file-format-parity.md | 6 +- docs/target-app-parity.md | 123 +++++++++++++++++++------------------ docs/ui-parity.md | 20 +++--- 6 files changed, 105 insertions(+), 104 deletions(-) diff --git a/README.md b/README.md index 8e51d4930e..366b0711a8 100644 --- a/README.md +++ b/README.md @@ -233,8 +233,8 @@ VectorCraft is under active development. [**ROADMAP.md**](ROADMAP.md) has the st and what's next; [`docs/target-app-parity.md`](docs/target-app-parity.md) the full parity assessment and [`docs/gaps.md`](docs/gaps.md) the ranked list of what's missing. -**Where we are (2026-10-10): alpha.** About 88% of core menu items, tools, effects and formats exist -(92.5% of menu items do something), feature depth is ~75%, and we estimate ~65% ready for real work for a mainstream illustrator (~62% across all tracked features): everyday +**Where we are (2026-11-30): alpha.** About 96% of core menu items, tools, effects and formats exist +(99.9% of menu items do something), feature depth is ~79%, and we estimate ~65% ready for real work for a mainstream illustrator (~67% across all tracked features): everyday vector illustration is close to usable: drawing and path tools, Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out, PSD/PSB opened with their layers and placed as their merged image, JPEG XL in, Print, Package). diff --git a/ROADMAP.md b/ROADMAP.md index 752a457682..90e36ed940 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -10,7 +10,7 @@ control channel. This page is the summary; the evidence is in [`docs/target-app- and the work list in [`docs/gaps.md`](docs/gaps.md). **Why alpha:** the core workflows exist end to end (drawing and path editing, Pathfinder, paint and appearance, -type, SVG/PDF/EPS, print, export) and feature depth is ~75%, but a professional can't yet switch: Illustrator's +type, SVG/PDF/EPS, print, export) and feature depth is ~79%, but a professional can't yet switch: Illustrator's own `.ai` files open with a wrong layer structure in real cases and are saved back with an editing copy that keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), and writes live objects as their art, the interaction details have never been checked side by side, and some machines fail to start the app. Beta needs those closed (the beta list in [gaps.md](docs/gaps.md)). It passes the core-workflow @@ -24,8 +24,8 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)). | | Value | Kind | |---|---|---| -| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 717/719 wired (99.7%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, graphics on the Materials page (#6960), no base materials) | -| **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated | +| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~96%** | measured in part: menu items 815/816 wired (99.9%), tools 91/92, Illustrator effects 50/50, Photoshop effects 57/57, 3D 4/4 plus 3 Classic (initial types, graphics on the Materials page (#6960), no base materials) | +| **Feature depth** (weighted by use, scored by behaviour) | **~79%** | estimated | | **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated | | **To full parity** | **~360–590 h** one agent · ~95–165 h with 4–6 agents | estimated | @@ -33,9 +33,9 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)). | Audience | Ready % | Opus 5.5 agent hours to ~95% (one agent) | With 4–6 agents | Work that dominates | |---|---:|---:|---:|---| -| **Full Illustrator** (ready for real work; decides the stage) | **~62%** (57–67%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (23–39 h), advanced type (20–28 h), generative AI (30–60 h), localization (50–85 h) and ecosystem | +| **Full Illustrator** (ready for real work; decides the stage) | **~67%** (62–72%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (23–39 h), advanced type (20–28 h), generative AI (30–60 h), localization (50–85 h) and ecosystem | | **Mainstream illustrator** | **~65%** (60–70%) | **~230–380 h** | ~65–110 h | the interaction-fidelity pass (60–90 h), hardening and QA (30–50 h), stability (20–35 h), performance budgets (15–25 h), `.ai` exchange (10–20 h), the remaining depth of the everyday areas | -| **Essentials user** | **~75%** (70–80%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), in-app help and onboarding (8–15 h), basic QA (10–15 h), Shape Builder depth (4–8 h; #937's reproduced case is fixed, unconfirmed on the reporter's file), UI polish | +| **Essentials user** | **~77%** (72–82%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), the Windows print crashes (#8021, #9261), help articles and onboarding (8–15 h), basic QA (10–15 h), Shape Builder depth (4–8 h; #937's reproduced case is fixed, unconfirmed on the reporter's file), UI polish | Hours are Opus 5.5 agent wall-clock hours, calibrated from this repo's merged-PR timestamps (e.g. 0.7–1.2 h per Photoshop-style filter, ~0.8 h per medium feature); see [calibration](docs/target-app-parity.md#calibration). @@ -46,15 +46,15 @@ everything is measured from our code against Illustrator's public documentation. | Dimension | % | One agent (h) | Doc | |---|---:|---:|---| -| Features (depth) | 75% | 220–360 | [target-app-parity.md](docs/target-app-parity.md) | -| UI/UX fidelity | 55% | 70–110 | [ui-parity.md](docs/ui-parity.md) | +| Features (depth) | 79% | 220–360 | [target-app-parity.md](docs/target-app-parity.md) | +| UI/UX fidelity | 60% | 70–110 | [ui-parity.md](docs/ui-parity.md) | | File formats | 75% | 15–30 | [file-format-parity.md](docs/file-format-parity.md) | -| Hardware (GPU, pen, touch, displays) | 35% | 25–45 | [hardware-parity.md](docs/hardware-parity.md) | -| Localization (12 key languages) | 74% (measured) | 50–85 | [localization-parity.md](docs/localization-parity.md) | +| Hardware (GPU, pen, touch, displays) | 45% | 25–45 | [hardware-parity.md](docs/hardware-parity.md) | +| Localization (12 key languages) | 87% (measured) | 50–85 | [localization-parity.md](docs/localization-parity.md) | | Performance | ~60% | 15–25 | [gaps.md › G15](docs/gaps.md#g15-performance-budgets-and-a-gpu-renderer) | -| Stability | ~60% | 30–50 | [gaps.md › G10](docs/gaps.md#g10-launch-and-stability-on-real-machines) | -| Platforms | 80% | 15–25 | [gaps.md › G8](docs/gaps.md#g8-hardening-at-scale) | -| Ecosystem and plug-ins | 15% | 30–60 | [gaps.md › G17](docs/gaps.md#g17-ecosystem-third-party-plug-ins) | +| Stability | ~55% | 30–50 | [gaps.md › G10](docs/gaps.md#g10-launch-and-stability-on-real-machines) | +| Platforms | 82% | 15–25 | [gaps.md › G8](docs/gaps.md#g8-hardening-at-scale) | +| Ecosystem and plug-ins | 30% | 30–60 | [gaps.md › G17](docs/gaps.md#g17-ecosystem-third-party-plug-ins) | | AI features (generative) | 0% | 30–60 + owner decision | [gaps.md › G18](docs/gaps.md#g18-generative-ai-features) | | Agent automation | beyond Illustrator | — | [mcp.md](docs/mcp.md) | @@ -64,26 +64,26 @@ The dimension hours overlap (feature rows hold some UI, format and AI work), so | Area | % | One agent (h) | |---|---:|---:| -| Selection, transform & align | 85% | 4–6 | -| Drawing tools | 85% | 8–13 | -| Path operations, Pathfinder, Shape Builder, Live Paint | 80% | 4–8 | +| Selection, transform & align | 86% | 4–6 | +| Drawing tools | 88% | 8–13 | +| Path operations, Pathfinder, Shape Builder, Live Paint | 85% | 4–8 | | Colour, swatches, gradients, patterns, mesh, recolor | 92% | 4–7 | -| Strokes, brushes, width profiles | 88% | 8–15 | +| Strokes, brushes, width profiles | 90% | 8–15 | | Appearance, transparency, graphic styles, masks | 97% | 1–2 | -| Live vector effects | 85% | 4–8 | -| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 88% | — | -| 3D and Materials | ~25% | 30–55 | -| Type core — [type-parity.md](docs/type-parity.md) | 80% | 14–19 | -| Type advanced (CJK, spelling, Touch Type) | 50% | 20–28 | -| Symbols, blends, envelopes, Repeat, perspective | 88% | 4–7 | -| Image Trace, graphs, image tools | 75% | 5–8 | -| Layers, artboards, document setup | 78% | 5–8 | -| View & navigation | 70% | 9–14 | +| Live vector effects | 90% | 4–8 | +| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 55% | — | +| 3D and Materials | ~35% | 30–55 | +| Type core — [type-parity.md](docs/type-parity.md) | 83% | 14–19 | +| Type advanced (CJK, spelling, Touch Type) | 60% | 20–28 | +| Symbols, blends, envelopes, Repeat, perspective | 90% | 4–7 | +| Image Trace, graphs, image tools | 78% | 5–8 | +| Layers, artboards, document setup | 82% | 5–8 | +| View & navigation | 80% | 9–14 | | Guides, grids, smart guides, snapping | 80% | 4–7 | | File formats — [file-format-parity.md](docs/file-format-parity.md) | 75% | 10–20 | -| Export for Screens, Asset Export, slices | 85% | 2–4 | +| Export for Screens, Asset Export, slices | 87% | 2–4 | | Print, colour management, separations | 80% | 2–4 | -| Automation (Actions, Variables, scripting) | 60% | 8–14 | +| Automation (Actions, Variables, scripting) | 80% | 8–14 | | UI chrome (panels, Properties, preferences) | 80% | 13–20 | | Libraries, Links, Package | 82% | 2–3 | | Generative AI | 0% | 30–60 | diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 2e4ef4dd15..0adea74366 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -13,7 +13,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md]( |---|---:|---:|---:|---:| | Illustrator effects (vector and stylize) | 50 | 50 | 100% | — | | Photoshop effects (raster, Effect Gallery) | 57 | 57 | 100% | — | -| 3D and Materials | 4 (+3 Classic) | 4 (+3 Classic; initial: Extrude & Bevel, Revolve, Inflate, Rotate, Extrude & Bevel (Classic), Revolve (Classic), Rotate (Classic)) | ~25% | 25–45 | +| 3D and Materials | 4 (+3 Classic) | 4 (+3 Classic; initial: Extrude & Bevel, Revolve, Inflate, Rotate, Extrude & Bevel (Classic), Revolve (Classic), Rotate (Classic)) | ~35% | 25–45 | | Beyond Illustrator: Effect › Color Adjustments (6), effect plug-ins (WebAssembly) | — | 6 + plug-ins | — | — | ## Illustrator effects diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6287e13f47..53cedd94cc 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -59,9 +59,9 @@ Ordinary File > Save offers Save As when its own location refuses writes with a | | Illustrator | VectorCraft | Notes | |---|---:|---:|---| -| Formats opened or placed | ~30 | 34 | missing: FreeHand, DWG | +| Formats opened or placed | ~30 | 36 | missing: FreeHand, DWG | | 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 | 18 | missing: DWG; extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | +| 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 | EPS editing-data follow-up (2026-10-16): both mesh-corner layouts (with and without opacity) @@ -331,7 +331,7 @@ private editing data. VectorCraft: An image whose color space `XC` sets to one ink (`n [… (name) /Separation] XC`) comes in as a grayscale image of its tints (black at 100 %) colorized by the ink (its spot swatch, or a process plate's CMYK color), its alpha channel as its opacity mask (#6350). -- Estimate: **~65%** for real exchange with Illustrator users (open: ~75%; save: PDF-compatible, or legacy +- Estimate: **~65%** for real exchange with Illustrator users (open: ~75%; save: PDF-compatible with an editing copy of the art (`editingData`, on by default), or legacy version 7 with layers and groups; not yet tested by users who hand files back). Closing the open-side issues: 10–20 h with users' files. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4df379b998..af80231adb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -286,11 +286,11 @@ the work list made from it. Deep areas have their own checklists: [UI and intera | 2026-10-22 | minor | PDF import: a gap between glyphs of two sizes reads as a space measured against the smaller size (#3623); mixed-size regression. Scores and hours unchanged. | | 2026-10-21 | minor | PDF import: letter-spaced type keeps its word spaces and gains none between letters; synthetic Tc and glyph-by-glyph regressions. Scores and hours unchanged. | | 2026-10-15 | minor | Image Trace retains nonzero positioned boundaries when a fixed-end returning piece has fewer than two fitted cubics. Source-generated tests check survival, winding, shared-edge reversal and Noise controls; see `image-trace-quality.md`. Scores and hours unchanged. | -| **Feature breadth** (does each Illustrator menu item, tool, effect and format exist?) | **~88%** | measured in part: menu tree 717 of 719 items wired (99.7%), tools 89 of 92 (97%), vector effects 44 of 50 (88%), Photoshop-style effects 57 of 57 (100%), 3D 4 of 4 (initial: Extrude & Bevel, Revolve, Inflate, Rotate); blended by the area weights below | -| **Feature depth** (each area scored by behaviour, weighted) | **~75%** | estimated, area table below | +| **Feature breadth** (does each Illustrator menu item, tool, effect and format exist?) | **~96%** | measured in part: menu tree 815 of 816 items wired (99.9%; only Effect › 3D and Materials › Materials… is a stub), tools 91 of 92 (99%), vector effects 50 of 50 (100%), Photoshop-style effects 57 of 57 (100%), 3D 4 of 4 (Extrude & Bevel, Revolve, Inflate, Rotate) plus 3 of 3 Classic, no base materials or Turntable; blended by the area weights below (presence per area × weight / 105) | +| **Feature depth** (each area scored by behaviour, weighted) | **~79%** | estimated, area table below | | **Ready for real work, mainstream illustrator** | **~65%** (60–70%) | estimated, see [Ready for real work](#ready-for-real-work) | -| **Ready for real work, full Illustrator** (decides the stage) | **~62%** (57–67%) | estimated: additive weighted sum over the dimensions, see [Ready for real work](#ready-for-real-work) | -| **Ready for real work, essentials user** (core features only, see [Essentials user](#essentials-user)) | **~75%** (70–80%) | estimated | +| **Ready for real work, full Illustrator** (decides the stage) | **~67%** (62–72%) | estimated: additive weighted sum over the dimensions, see [Ready for real work](#ready-for-real-work) | +| **Ready for real work, essentials user** (core features only, see [Essentials user](#essentials-user)) | **~77%** (72–82%) | estimated | | **Remaining to beta** | **~170–270 h** one agent | estimated, [gaps.md](gaps.md) beta list | | **Remaining to full parity** | **~360–590 h** one agent · ~95–165 h wall clock with 4–6 agents | estimated, sum of the area table + fidelity pass + hardening | @@ -346,49 +346,49 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Area | Weight | Done | Main gaps | One agent (h) | Kind | |---|---:|---:|---|---:|---| -| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | -| Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options; Touch Type (#2469) and the Dimension tool (#1788) are done; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; 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 and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged | -| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; 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 (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | +| Selection, transform & align tools | 6 | 86% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | +| Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 88% | Shaper construction widget, Pencil/Pen nuances; Touch Type (#2469), the Dimension tool (#1788) and the Blob Brush options (#2367) are done; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; 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 and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged | +| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 85% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; 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; compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005); the Color Wheel panel's Show Opacity sets the opacity of the fill, stroke, gradient stop or freeform point it edits (part of #978), score and hours unchanged; gradient stop editor color-mode menu (#7918) | -| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | +| Strokes, brushes, width profiles | 5 | 90% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Appearance panel row context menus (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with unselected-row targeting, Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | -| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | -| Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, 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, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); Ignore Color canvas sampling reads the original pixels without changing View, keeps a missed pick armed, and retains the manual picker and Preview controls (#8068; scores, gaps and hours unchanged); Create Object Mosaic's dialog with New Size, Constrain Ratio, Resize Using Percentages and Use Ratio is covered by `dialogs::object_mosaic::tests` (score, gaps and hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged 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; runtime pending). | -| Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | -| 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| 3D and Materials (and Turntable) | 4 | ~35% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | +| Type core | 9 | 83% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | +| Image Trace, graphs, image tools | 3 | 78% | Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, 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, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); Ignore Color canvas sampling reads the original pixels without changing View, keeps a missed pick armed, and retains the manual picker and Preview controls (#8068; scores, gaps and hours unchanged); Create Object Mosaic's dialog with New Size, Constrain Ratio, Resize Using Percentages and Use Ratio is covered by `dialogs::object_mosaic::tests` (score, gaps and hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged 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; runtime pending). | +| Live vector effects | 5 | 90% | depth of individual effects | 4–8 | measured count 50/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | +| 3D and Materials (and Turntable) | 4 | ~35% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | CJK vertical composition (mojikumi), variable font axes, tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | CJK vertical composition (mojikumi), tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | -| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | -| Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers row menu commands beyond Collect for Export and menus on blend spine rows (guide row menus are done; click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | -| View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours 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, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document 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, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours 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, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document 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, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours 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, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document 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, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | -| View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | -| View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged) | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | +| Image Trace, graphs, image tools | 3 | 78% | Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | +| Layers, artboards, document setup | 5 | 82% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: managing artboards from the canvas (artboard locking and colors, #2532 and #2403, Layers row menus and blend spine row menus are done; guide row menus are done; click-to-fit objects is done, #1227) | 5–8 | estimated; Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | +| View & navigation | 3 | 80% | depth of floating-window interactions; floating windows on Wayland drawn inside the main window | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/DWG import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours 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, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document 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, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/DWG import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours 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, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document 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, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/DWG import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours 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, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document 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, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | +| View & navigation | 3 | 80% | depth of floating-window interactions; floating windows on Wayland drawn inside the main window | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | +| View & navigation | 3 | 80% | depth of floating-window interactions; floating windows on Wayland drawn inside the main window | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged) | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658) | 4–7 | estimated (lowered from 85%: target moved); View › Snapping groups five existing toggles and Pixel Snapping Options… (G13), retaining top-level commands and shortcuts; Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged | -| Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | +| Export for Screens, Asset Export, slices, Save for Web | 3 | 87% | TIFF choices and settings are implemented; anti-aliasing ghost borders are fixed (#983) | 2–4 | estimated; depth not measured | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated | -| Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | +| Automation (Actions, Variables, scripting, batch) | 3 | 80% | script DOM classes for layers, artboards and gradient stops, `#engine` (#1183), Batch option depth (scripting, #9019, Batch, #1938, and image and graph variables are done) | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | | UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Document Info Selection Only (`ui.docInfo.selectionOnly`) counts the selection through `document.info`, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show (`panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard`, `test_doc_info_panel_menu_toggles_state`); Properties Quick Actions offer Ungroup for any selected group, Isolate Group only for one group, and Unite only for selections of at least two objects, each a non-guide path or a compound path (`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 item context menus implemented (G12); Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the remaining panels that have none (History rows implemented, #8845), accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; Character Styles and Paragraph Styles item context menus have focused regressions (panels::text_styles::tests::right_click_context_menu_*); scores and estimates unchanged; History row context menus have snapshot, pending-edit, typing and clear-history headless regressions (panels::history::tests, #8845); swatches dropped on New Swatch or Delete Swatch carry the selected swatches the find field or kind filter hides (#8620); scores and estimates unchanged; the Artboards panel's list fills the panel, so it resizes with the window (#6085), score and hours unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated; #5804: private native-picked raster editor (scores unchanged) | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | -| **Feature depth** | **105** | **~75%** | | **~250–420** | | +| **Feature depth** | **105** | **~79%** | | **~250–420** | | | Interaction-fidelity pass (every tool's modifiers, cursors, Properties per context) | | | [ui-parity.md](ui-parity.md) | 60–90 | estimated | | Hardening (real-file corpus, cross-platform and browser QA, launch failures, performance budgets) | | | [gaps.md](gaps.md) | 50–80 | estimated; PngSuite fetch integrity and size budgets regression-tested (#1729) | -| **Full parity** | | **~55%** | | **~360–590** | | +| **Full parity** | | **~58%** | | **~360–590** | | -Excluding the generative-AI row (the old table had none), depth is ~76% and the remaining feature work +Excluding the generative-AI row (the old table had none), depth is ~81% and the remaining feature work ~220–360 h. With 4–6 agents on disjoint crates, wall-clock time divides by about 3.5–4 (shared files such as `menus.rs` and the i18n catalogs serialize some work): ~95–165 h to full parity. @@ -407,9 +407,9 @@ review parallelize less and need humans. | Audience | Ready % | Opus 5.5 agent hours to ~95% (one agent) | With 4–6 agents | Work that dominates | |---|---:|---:|---:|---| -| **Full Illustrator** (ready for real work; decides the stage) | **~62%** (57–67%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (24–40 h), advanced type (20–28 h), generative AI (30–60 h), localization (55–90 h) and ecosystem | +| **Full Illustrator** (ready for real work; decides the stage) | **~67%** (62–72%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (24–40 h), advanced type (20–28 h), generative AI (30–60 h), localization (55–90 h) and ecosystem | | **Mainstream illustrator** | **~65%** (60–70%) | **~230–380 h** | ~65–110 h | the interaction-fidelity pass (60–90 h), hardening and QA (30–50 h), stability (20–35 h), performance budgets (15–25 h), `.ai` exchange (10–20 h), the remaining depth of the everyday areas | -| **Essentials user** | **~75%** (70–80%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), in-app help and onboarding (8–15 h), basic QA (10–15 h), Shape Builder depth (4–8 h; #937's reproduced case is fixed, unconfirmed on the reporter's file), UI polish | +| **Essentials user** | **~77%** (72–82%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), the Windows print crashes (#8021, #9261), help articles and onboarding (8–15 h), basic QA (10–15 h), Shape Builder depth (4–8 h; #937's reproduced case is fixed, unconfirmed on the reporter's file), UI polish | ### Full Illustrator: additive weighted sum over the dimensions @@ -418,17 +418,17 @@ Values are from [By dimension](#by-dimension). | Dimension | Weight | Value | Contribution | |---|---:|---:|---:| -| Features (depth) | 35 | 75% | 26.3 | -| UI/UX fidelity | 15 | 55% | 8.3 | +| Features (depth) | 35 | 79% | 27.8 | +| UI/UX fidelity | 15 | 60% | 9.0 | | File formats | 12 | 75% | 9.0 | -| Stability | 10 | 60% | 6.0 | +| Stability | 10 | 55% | 5.5 | | Performance | 8 | 60% | 4.8 | -| Platforms | 5 | 80% | 4.0 | -| Hardware | 4 | 35% | 1.4 | -| Localization | 4 | 74% | 3.0 | -| Ecosystem and plug-ins | 4 | 15% | 0.6 | +| Platforms | 5 | 82% | 4.1 | +| Hardware | 4 | 45% | 1.8 | +| Localization | 4 | 87% | 3.5 | +| Ecosystem and plug-ins | 4 | 30% | 1.2 | | AI features | 3 | 0% | 0.0 | -| **Ready for real work** | **100** | | **~62%** | +| **Ready for real work** | **100** | | **~67%** | The weights put most of the number on what professionals use daily (features, interaction, files, stability). Generative AI also sits inside the features row at weight 2 of 105, so it is counted slightly twice; that costs @@ -436,11 +436,11 @@ under a point. ### Mainstream illustrator and essentials user -Both start from feature depth over the areas concerned. **Mainstream:** ~83% over 16 areas (weight 83 of 105: +Both start from feature depth over the areas concerned. **Mainstream:** ~86% over 16 areas (weight 83 of 105: selection, drawing, path operations, colour, strokes, appearance, live effects, type core, symbols and blends, layers and artboards, view, guides, file formats, Export for Screens, UI chrome, print). That is discounted ×0.9 for interaction fidelity, ×0.92 for stability on real machines and ×0.92 for Illustrator-file exchange -(83 × 0.9 × 0.92 × 0.92 ≈ 63). The dimensions a typical illustrator rarely hits (plug-in ecosystem, +(86 × 0.9 × 0.92 × 0.92 ≈ 65). The dimensions a typical illustrator rarely hits (plug-in ecosystem, generative AI, pen tilt, languages beyond their own) are left out. **Essentials:** see [Essentials user](#essentials-user). The discounts, with the evidence: @@ -488,11 +488,11 @@ Depth here is "does the basic use work", not the area's full score. | Gradients, basic | 4 | 90% | Gradient panel and on-canvas annotator | | Type: point and area text, font, size | 8 | 88% | font menu with previews; Hyphenation… and Justification… options per paragraph (#2310, #2755) | | Align, group, arrange | 6 | 95% | | -| Layers, basic | 4 | 85% | Layers panel rework; selected guide rows keep their highlight (#7344); row context menus offer only Collect for Export | -| Shape Builder | 5 | 70% | beginners lean on it; region detection failed on art of thousands of segments (#937's reproduced case, fixed, and its edge-source grid is bounded in memory; unconfirmed on the reporter's file) | +| Layers, basic | 4 | 90% | Layers panel rework; selected guide rows keep their highlight (#7344); row context menus offer Options, Duplicate, Delete, Lock and Hide Others, Locate and Collect for Export | +| Shape Builder | 5 | 78% | beginners lean on it; region detection failed on art of thousands of segments (#937's reproduced case, fixed, and its edge-source grid is bounded in memory; unconfirmed on the reporter's file) | | Pathfinder | 4 | 95% | exact booleans | | Place images, Image Trace | 4 | 85% | 13 trace presets | -| Export PNG/JPG/SVG/PDF, print | 8 | 92% | Art Optimized supersample closes Asset Export ghost borders (#983 / #1037) | +| Export PNG/JPG/SVG/PDF, print | 8 | 88% | Art Optimized supersample closes Asset Export ghost borders (#983 / #1037); printing crashes on some Windows machines (#8021, #9261) | | Undo and redo | 4 | 100% | unlimited, property-tested | | Zoom, pan, fit | 4 | 95% | | | Artboards, basic | 4 | 88% | | @@ -501,13 +501,14 @@ Depth here is "does the basic use work", not the area's full score. The discounts a beginner actually hits: - **Launch and stability, ×0.93:** fine on macOS, but some Windows machines fail to start (#858, #620, #818). -- **Discoverability and UI clarity, ×0.92:** the layout follows Illustrator's and comes in 11 languages, but - there is no in-app help (Help › VectorCraft Help… is a stub), no Learn panel or tutorials, and a newcomer +- **Discoverability and UI clarity, ×0.95:** the layout follows Illustrator's and comes in 11 languages; + Help › VectorCraft Help… (F1) searches tools, menu commands and tutorials, and Window › Learn has 12 + tutorials, but there are no help articles, and a newcomer meets Illustrator's density without Illustrator's learning material. - **Opening files people send them, ×0.96:** PDF, SVG, images and most `.ai` files open as editable art. Layer-structure problems (#951) matter less to a beginner. -91 × 0.93 × 0.92 × 0.96 ≈ 75: **~75% (70–80%), estimated.** +91 × 0.93 × 0.95 × 0.96 ≈ 77: **~77% (72–82%), estimated.** ### User sentiment (measured 2026-10-10) @@ -531,15 +532,15 @@ what keeps it from beta, not from alpha. | Dimension | % | One agent (h) | Kind | Doc | |---|---:|---:|---|---| -| Features (depth, weighted) | 75% | 220–360 | estimated | this file | -| UI/UX fidelity (look ~80%, interaction ~45%) | 55% | 70–110 | estimated | [ui-parity.md](ui-parity.md); Tools sits inside left-side panels beside the canvas (layout choice; no rescoring); held spinner arrows keep stepping (#6307); Vector Halftone Preview keeps the selection box without the dot marks (#6369) | +| Features (depth, weighted) | 79% | 220–360 | estimated | this file | +| UI/UX fidelity (look ~80%, interaction ~50%) | 60% | 70–110 | estimated | [ui-parity.md](ui-parity.md); Tools sits inside left-side panels beside the canvas (layout choice; no rescoring); held spinner arrows keep stepping (#6307); Vector Halftone Preview keeps the selection box without the dot marks (#6369) | | File formats | 75% | 15–30 | estimated | [file-format-parity.md](file-format-parity.md) | -| Hardware (GPU, pen, touch, displays) | 35% | 25–45 | estimated | [hardware-parity.md](hardware-parity.md) | -| Localization (the 12 key languages, equally weighted) | 74% | 50–85 | measured from catalogs | [localization-parity.md](localization-parity.md) | +| Hardware (GPU, pen, touch, displays) | 45% | 25–45 | estimated | [hardware-parity.md](hardware-parity.md) | +| Localization (the 12 key languages, equally weighted) | 87% | 50–85 | measured from catalogs | [localization-parity.md](localization-parity.md) | | Performance | ~60% | 15–25 | estimated (unverified budgets; measured long-path hits, large-selection nudges and text thread filtering) | [gaps.md](gaps.md) | -| Stability | ~60% | 30–50 | estimated | [gaps.md](gaps.md) | -| Platforms (macOS, Windows x64/arm64, Linux, FreeBSD, web) | 80% | 15–25 | estimated | [gaps.md](gaps.md) | -| Ecosystem and plug-ins (scripting, third-party plug-ins) | 15% | 30–60 | estimated | [gaps.md](gaps.md) | +| Stability | ~55% | 30–50 | estimated | [gaps.md](gaps.md) | +| Platforms (macOS, Windows x64/arm64, Linux, FreeBSD, web) | 82% | 15–25 | estimated | [gaps.md](gaps.md) | +| Ecosystem and plug-ins (scripting, third-party plug-ins) | 30% | 30–60 | estimated | [gaps.md](gaps.md) | | AI features (generative) | 0% | 30–60 (+ owner decision) | measured (absent) | [gaps.md](gaps.md) | | Agent automation (MCP, CLI, control channel) | beyond Illustrator | — | measured | [mcp.md](mcp.md) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d131053a67..acc82c77a5 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -168,18 +168,18 @@ forbids launching or measuring Illustrator, so there has been **no side-by-side | Area | % | Remaining (h) | Kind | |---|---:|---:|---| -| Pen, Curvature and anchor tools | 85% | 6–10 | estimated | -| Direct Selection, handles and anchors | 85% | 5–8 | estimated | -| Smart guides and snapping | 70% | 8–12 | estimated | -| Transform handles, bounding box, Free Transform | 80% | 5–8 | estimated | +| Pen, Curvature and anchor tools | 90% | 6–10 | estimated | +| Direct Selection, handles and anchors | 90% | 5–8 | estimated | +| Smart guides and snapping | 85% | 8–12 | estimated | +| Transform handles, bounding box, Free Transform | 90% | 5–8 | estimated | | Nudging, numeric entry, precision, units | 85% | 3–5 | estimated | -| Modifier keys and temporary tools | 80% | 5–8 | estimated | -| Keyboard shortcuts (default set) | 70% | 6–10 | estimated; optional Switch Selection Tools is user-bindable with no default key (#7645), so default-set coverage is unchanged | -| Cursors | 75% | 3–5 | estimated | -| Panels, Control bar, Properties, context menus | 70% | 15–25 | estimated | +| Modifier keys and temporary tools | 85% | 5–8 | estimated | +| Keyboard shortcuts (default set) | 75% | 6–10 | estimated; optional Switch Selection Tools is user-bindable with no default key (#7645), so default-set coverage is unchanged | +| Cursors | 80% | 3–5 | estimated | +| Panels, Control bar, Properties, context menus | 80% | 15–25 | estimated | | Look and feel (layout, theme, metrics) | 80% | 5–10 | measured once against public screenshots on 2026-10-02; panels added since not re-measured | -| Accessibility (screen reader, keyboard-only canvas) | 20% | 15–25 | estimated: AccessKit on by default for egui widgets; canvas and custom panels not described, never tested with a screen reader | -| **UI/UX overall** | **~55%** | **~70–110** (overlaps the feature areas) | estimated | +| Accessibility (screen reader, keyboard-only canvas) | 25% | 15–25 | estimated: AccessKit on by default for egui widgets; canvas and custom panels not described, never tested with a screen reader | +| **UI/UX overall** | **~60%** | **~70–110** (overlaps the feature areas) | estimated | The overall figure is lower than the rows because what users notice first (small differences across many tools, never checked side by side) isn't captured row by row. From 8e7e326e6ca25e9c9267fcbe7ed7765d63bacc67 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 00:23:42 -0800 Subject: [PATCH 36/69] Docs: one Feature areas row per area, with gaps that match main The Feature areas table in docs/target-app-parity.md listed Type advanced, Symbols, Image Trace, 3D, View and File formats more than once. Each area now has one row that merges the evidence of its copies, so the weights sum to the stated 105; feature depth stays ~79% (~81% without generative AI). The gaps no longer list work that main ships: rotated-box transforms and Global Edit of rotated copies, Touch Type, ruby, variable font axes, tab leaders, editable 9-slice guides in native saves, and mapped textures in 3D export. The remaining limits are named instead. --- docs/target-app-parity.md | 26 ++++++-------------------- 1 file changed, 6 insertions(+), 20 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index af80231adb..54957e08b7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -346,36 +346,22 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Area | Weight | Done | Main gaps | One agent (h) | Kind | |---|---:|---:|---|---:|---| -| Selection, transform & align tools | 6 | 86% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | +| Selection, transform & align tools | 6 | 86% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 88% | Shaper construction widget, Pencil/Pen nuances; Touch Type (#2469), the Dimension tool (#1788) and the Blob Brush options (#2367) are done; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; 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 and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 85% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; 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; compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005); the Color Wheel panel's Show Opacity sets the opacity of the fill, stroke, gradient stop or freeform point it edits (part of #978), score and hours unchanged; gradient stop editor color-mode menu (#7918) | | Strokes, brushes, width profiles | 5 | 90% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Appearance panel row context menus (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with unselected-row targeting, Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | -| 3D and Materials (and Turntable) | 4 | ~35% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type core | 9 | 83% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Image Trace, graphs, image tools | 3 | 78% | Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, 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, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); Ignore Color canvas sampling reads the original pixels without changing View, keeps a missed pick armed, and retains the manual picker and Preview controls (#8068; scores, gaps and hours unchanged); Create Object Mosaic's dialog with New Size, Constrain Ratio, Resize Using Percentages and Use Ratio is covered by `dialogs::object_mosaic::tests` (score, gaps and hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged 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; runtime pending). | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | editable ruby text in standard SVG and PDF artwork (written as outlines; see [type-parity.md](type-parity.md)), custom Mojikumi sets and the Mojikumi Settings dialog, Retype from images, Retype panel matching depth and fused glyphs (see [type-parity.md](type-parity.md)), Touch Type along a line for a character with no immediately preceding logical character on the same line in the same direction (movement along the baseline is disabled; baseline shift still works) | 20–28 | estimated; Retype (`type.retype`, exact and tolerance-based outline matches, #4934); No Break suppresses automatic breaks within the marked run (a forced line break still breaks); upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | remaining: other apps ignore dynamic symbol instance overrides in the `.ai` editing copy, and VectorCraft restores them, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guide settings in the standard SVG data and in the `.ai` editing data written for other apps (the scaled appearance is kept, and `.ai` or SVG saves that embed the VectorCraft document reopen with editable guides); Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | +| Image Trace, graphs, image tools | 3 | 78% | Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, 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, so Paths is monotone on the code-drawn sweep; large images trace with a warning or are downsampled, and images beyond the size and decode limits in `crates/trace/src/raster.rs` are rejected; Auto Color keeps rare distinct colors in coherent regions when the Automatic palette classifies the image as flat artwork) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); Ignore Color canvas sampling reads the original pixels without changing View, keeps a missed pick armed, and retains the manual picker and Preview controls (#8068; scores, gaps and hours unchanged); Create Object Mosaic's dialog with New Size, Constrain Ratio, Resize Using Percentages and Use Ratio is covered by `dialogs::object_mosaic::tests` (score, gaps and hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged 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; runtime pending). | | Live vector effects | 5 | 90% | depth of individual effects | 4–8 | measured count 50/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | -| 3D and Materials (and Turntable) | 4 | ~35% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | CJK vertical composition (mojikumi), variable font axes, tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | CJK vertical composition (mojikumi), tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| 3D and Materials (and Turntable) | 4 | ~35% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows from lights after the first and in Classic effects (only the first light can cast a shadow in Revolve, Extrude & Bevel, Inflate and Rotate), ray tracing, Turntable views, shading and paint fidelity in 3D export (gradient stops are averaged, pattern paint is replaced with gray, and graphics mapped onto the sides of Extrude & Bevel objects and Map Art on the Classic effects are left out of Export 3D Object) | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); Revolve (Classic) is covered by the `revolve::classic` tests; `a_3d_row_sets_its_param_previews_and_applies_in_one_step` in `crates/ui-egui/src/dialogs/revolve/tests.rs` checks its Angle preview, OK, Cancel and single-step undo; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | -| Image Trace, graphs, image tools | 3 | 78% | Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 82% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: managing artboards from the canvas (artboard locking and colors, #2532 and #2403, Layers row menus and blend spine row menus are done; guide row menus are done; click-to-fit objects is done, #1227) | 5–8 | estimated; Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 80% | depth of floating-window interactions; floating windows on Wayland drawn inside the main window | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/DWG import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours 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, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document 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, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/DWG import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours 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, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document 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, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/DWG import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours 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, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document 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, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | -| View & navigation | 3 | 80% | depth of floating-window interactions; floating windows on Wayland drawn inside the main window | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | -| View & navigation | 3 | 80% | depth of floating-window interactions; floating windows on Wayland drawn inside the main window | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged) | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, envelopes and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), images with Warp effects keep the effect editable when they qualify, FreeHand/DWG import, shading and paint fidelity in 3D export (gradient stops are averaged, pattern paint is replaced with gray, and graphics mapped onto the sides of Extrude & Bevel objects and Map Art on the Classic effects are left out of Export 3D Object); see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; aligned type lies as far from its path as the file lays it out (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`); the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours 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, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document 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, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658) | 4–7 | estimated (lowered from 85%: target moved); View › Snapping groups five existing toggles and Pixel Snapping Options… (G13), retaining top-level commands and shortcuts; Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged | | Export for Screens, Asset Export, slices, Save for Web | 3 | 87% | TIFF choices and settings are implemented; anti-aliasing ghost borders are fixed (#983) | 2–4 | estimated; depth not measured | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated | From 580417f85caf23cc90eb0a02e624a6951d07c673 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 02:31:09 -0800 Subject: [PATCH 37/69] Docs: .ai editing-copy limits for symbols and meshes, 9-slice guides on reopen The File formats row now names the copy the limits apply to (the editing data for other apps, which VectorCraft reads only when it does not reopen the embedded VectorCraft document) and lists symbols with their instances and gradient meshes among the live objects that copy keeps, with their limits. The 9-slice guides note says the guides return when an .ai, or an SVG saved with Preserve Editing Capabilities, reopens from the embedded document. file-format-parity.md describes how the .ai writer keeps dynamic symbol instances live: their dynamic type and changes go in VectorCraft's own entries, changes past 1 MiB are left out without a warning, and changes that name a part by its place can miss when the copy writes type as outlines or leaves out an earlier part. --- docs/file-format-parity.md | 13 ++++++++++--- docs/target-app-parity.md | 4 ++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 53cedd94cc..8a65db4d4a 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -139,8 +139,15 @@ private editing data. VectorCraft: instances written as their art, shapes with rounded live corners or strokes written as outlines or brush art, instances that scale their symbol more than 100 times and instances on the layers of a large canvas are written as their art, pattern fills in a symbol's art are written as their tiles cut to the shape, symbols past 4,096 are written only as their - instances' art, and symbols' 9-slice guides, export types and dynamic type are left out, each with a - warning. Paths, compound paths and groups with live effects keep them as art styles: the drawn look, the object + instances' art, and symbols' 9-slice guides and export types are left out, each with a + warning. A dynamic symbol instance whose only changes of its own are its parts' changes is not written as its + art when it otherwise qualifies: it stays a live instance. The symbol's dynamic type and the instance's changes + are written in VectorCraft's own entries, which VectorCraft reads back and other apps leave out; writing the + changes gives a warning, and writing the dynamic type alone does not. The changes name the symbol's parts by + their place, so they are reproduced only where the editing copy keeps the symbol's parts as they are: fill and + stroke changes to type, which the copy holds as outlines, are not reproduced (opacity and blend changes are), and + when the copy leaves out an earlier part, such as an empty path, a change applies to a different part or to none. When an instance's + changes together take more than 1 MiB, none of them is written, without a warning. Paths, compound paths and groups with live effects keep them as art styles: the drawn look, the object itself and the style it names, for a fill and a stroke at most in solid colors or the object's gradient (a stroke with its variable-width profile), filled by the non-zero rule, with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Convert to Shape, Offset Path, Outline Object or Outline Stroke, and groups with Pathfinder › @@ -337,7 +344,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data -The app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping (several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection, and a compound path of clipping paths stays one clip, its clipping paths grouped in it, at any depth, included; a filled clipping path keeps its fill, which paints under the art it clips, except the path of a mask that covers several layers, whose fill is read as a path of its own in the layer that holds the mask's path, and a compound clipping path whose subpaths paint differently, whose filled subpaths are read as a compound path of their own under the art it clips; clipping paths that would nest the art past the document's 32 levels stop the editing data from being read: #5789), object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), gradient and pattern names in the file up to their first newline (a name that another swatch, or a gradient or pattern defined earlier, already has is numbered "Sky 2"; a name without a newline is kept, and when another swatch has it, the pattern's swatch, or a named color sharing a gradient or pattern swatch's name, is numbered the same way), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, placed PDF and `.ai` pages as placed documents of the [page and Crop to box](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/adobe-pdf-placement-options.html) their dictionary names (`AI11 PlacedPDFPageIndex`, `AI11 PlacedPDFCropTo`; a value VectorCraft doesn't read, or a binding to an image variable, leaves a linked image), guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. VectorCraft reads `CropAreaActive`, an `/Int` in the dictionary that holds the artboard array, as the index of the active artboard in that array, and the file opens with that artboard active; without it, or when it names no artboard that opens, the first artboard is active. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile on a Stroke Offset stroke or written as each side's widths) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke, Convert to Shape, Tweak (only when it moves nothing), Pucker & Bloat at 0 or Bas Relief (read from its settings block: [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [layered image file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646)) comes in as itself with them and their saved settings. A path, compound path or group (not a clipping group) whose only effect is Transform (not with copies or Random) or a Free Distort whose corners make a parallelogram comes in as itself with it too, when neither it nor anything in it paints with a gradient or pattern and everything in it is a path, compound path or group with no opacity mask and no effects of its own; Transform that scales, rotates or reflects needs nothing in it to be stroked and, with Transform Objects on, no guide in it that reaches past the rest of its art (hidden members count as art), and a Free Distort that moves a corner of a group needs no guide in the group that reaches past the rest of its art. Twist as the only effect is read the same way when nothing in the object is stroked: up to 180° either way (a limit VectorCraft sets) on a path or compound path whose segments are all straight, except a compound path with a guide member that reaches past its other members at an angle other than 0°, and up to 90° either way (a limit VectorCraft sets) on another path, compound path or group with no guide in it. One with more, other effects (Zig Zag, a Pucker & Bloat of another amount, a Free Distort with other corners), an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a variable-width stroke with one centered width array, dashes aligned to corners, a brush other than a Calligraphic or Art one, a Calligraphic brush with settings of its own, an entry that isn't read, a variable width or an angle that follows the path, a path followed by samples of the pen (`(…) Xt n XD`) whose Calligraphic brush varies with the pen, or an Art brush other than the ones described next comes in as its drawn look (a group named after it). Objects in a symbol defined before the file's art styles section, as newer files write it, take the same styles as the layers' objects. A path with a Calligraphic brush otherwise comes in as the path, the brush on its stroke at the stroke's weight, which scales the brush (#372), and so does a path with an Art brush, whose weight scales the art across the path, when all of these hold: the brush is in Tints or None, at a fixed width from 1% to 1,000%, stretched to the path or stretched between guides that leave art between them, flipped along or across or not ([Art brush options](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf), printed page 193), with `Spacing` 0, `Adjustment` 1 and `FoldAdjustment` 1 (VectorCraft's own reading of these numbers; a brush that scales its art proportionately comes into the Brushes panel with that option, and its paths keep their drawn look); the path's settings are the brush's own (apart from the lowest and highest width of a fixed width and the guides' lengths without Stretch Between Guides, which don't draw), with no entry that isn't read, no variable width and no effects; a stroke in Tints isn't a swatch; and the art is paths, compound paths and groups in solid fills, with no strokes, masks or effects, and has some length along the path. A stroke takes the brush the Brushes panel keeps under its name, and one whose name the panel doesn't keep comes in as its drawn look. Type with an Art brush keeps its drawn look under the type. A Calligraphic brush's Pressure, Stylus Wheel, Tilt, Bearing and Rotation come in as those channels (a 6D Art Pen's brushes vary with the pressure, the bearing and the barrel's rotation). The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. When the file opens from its layers, the spot colors in the art of each brush that comes in become swatches, and that art's colors count toward the document's color mode, as a pattern's do. The swatches take at most 20,000 color names in all across the brush art, and each brush-art section keeps at most 20,000 names. Each name keeps its first definition, with the color operators' names before the gradient stops' names. A spot color past those limits makes no swatch, and its color still counts toward the color mode. A spot color that the page's art, a pattern or a symbol also defines keeps the value defined there. Type keeps its art style as a live appearance whatever its stack (an Art brush aside), so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its detail, smoothness and light direction from its settings block, or the effect's defaults when the style holds no settings block; a settings block that isn't read keeps the drawn look) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an EPS with editing data from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; type on a path keeps its frame's Type on a Path effect, Align to Path and Flip (a frame whose options set key 6 to true keeps their defaults), and the first frame's Spacing is fitted from the file's layout, not read from the dialog's value; the distance from the path under Align to Path is measured for each character at its size and vertical scale (in vertical type, its horizontal scale), from the top of its font's em box (Ascender), half the height of the top of its font's H (Center) or the bottom of its font's bounding box (Descender); the fit under Gravity does not reproduce the file's layout, and its glyphs can lie up to 7.4 pt from the positions the file keeps; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). In a PDF saved with some of its artboards, the type on each page after the first goes to an artboard of that page's size after the previous page's artboard, and only to one that leaves an artboard for each later page; the first page's artboard also leaves one for each later page. When several artboards fit a later page, VectorCraft takes the one whose art draws most like the page, and compares at most 16 artboards for all the later pages together. Symbols are read into the Symbols panel, in the file's symbol list order, with their art, their registration point and the instances in their art, and their instances come in live with their matrix, name, hide, lock, opacity, blending mode, isolation, knockout and opacity mask; a symbol whose art isn't read whole (type, placed files, an image it leaves out or anything else it doesn't read) isn't kept. A file that comes in as its page or PDF part because its editing data has no layers (a symbol library), or because its layers can't be read or used (any of the cases below), gets the symbols its editing data defines before its first layer, in the symbol list's order, while its page art stays as the page draws it. Instances of symbols it can't read, instances with appearance changes of their own (a dynamic symbol's), pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). A `.ai` is not compared with its page, and its PDF part is not imported, when its text document makes the type of every text object (at least one shows, and none is drawn by the appearance of the layer or group it is in), no object is unread, no placed file has a second placement, no live envelope keeps its drawn art, it declares no large canvas, and its artboards are its pages' trim boxes one for one, in points or in the first page's `UserUnit`: it opens from its layers, with the bleed of its pages' bleed boxes. When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so live objects that only the editing data holds arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (the PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068); the page of the artboard `CropAreaActive` names is then the active artboard. A `.ai` whose editing data has artboards but no layers also opens on that page under the same check, and its pages stay where they are. A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +The app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping (several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection, and a compound path of clipping paths stays one clip, its clipping paths grouped in it, at any depth, included; a filled clipping path keeps its fill, which paints under the art it clips, except the path of a mask that covers several layers, whose fill is read as a path of its own in the layer that holds the mask's path, and a compound clipping path whose subpaths paint differently, whose filled subpaths are read as a compound path of their own under the art it clips; clipping paths that would nest the art past the document's 32 levels stop the editing data from being read: #5789), object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), gradient and pattern names in the file up to their first newline (a name that another swatch, or a gradient or pattern defined earlier, already has is numbered "Sky 2"; a name without a newline is kept, and when another swatch has it, the pattern's swatch, or a named color sharing a gradient or pattern swatch's name, is numbered the same way), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, placed PDF and `.ai` pages as placed documents of the [page and Crop to box](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/adobe-pdf-placement-options.html) their dictionary names (`AI11 PlacedPDFPageIndex`, `AI11 PlacedPDFCropTo`; a value VectorCraft doesn't read, or a binding to an image variable, leaves a linked image), guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. VectorCraft reads `CropAreaActive`, an `/Int` in the dictionary that holds the artboard array, as the index of the active artboard in that array, and the file opens with that artboard active; without it, or when it names no artboard that opens, the first artboard is active. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile on a Stroke Offset stroke or written as each side's widths) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke, Convert to Shape, Tweak (only when it moves nothing), Pucker & Bloat at 0 or Bas Relief (read from its settings block: [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [layered image file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646)) comes in as itself with them and their saved settings. A path, compound path or group (not a clipping group) whose only effect is Transform (not with copies or Random) or a Free Distort whose corners make a parallelogram comes in as itself with it too, when neither it nor anything in it paints with a gradient or pattern and everything in it is a path, compound path or group with no opacity mask and no effects of its own; Transform that scales, rotates or reflects needs nothing in it to be stroked and, with Transform Objects on, no guide in it that reaches past the rest of its art (hidden members count as art), and a Free Distort that moves a corner of a group needs no guide in the group that reaches past the rest of its art. Twist as the only effect is read the same way when nothing in the object is stroked: up to 180° either way (a limit VectorCraft sets) on a path or compound path whose segments are all straight, except a compound path with a guide member that reaches past its other members at an angle other than 0°, and up to 90° either way (a limit VectorCraft sets) on another path, compound path or group with no guide in it. One with more, other effects (Zig Zag, a Pucker & Bloat of another amount, a Free Distort with other corners), an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a variable-width stroke with one centered width array, dashes aligned to corners, a brush other than a Calligraphic or Art one, a Calligraphic brush with settings of its own, an entry that isn't read, a variable width or an angle that follows the path, a path followed by samples of the pen (`(…) Xt n XD`) whose Calligraphic brush varies with the pen, or an Art brush other than the ones described next comes in as its drawn look (a group named after it). Objects in a symbol defined before the file's art styles section, as newer files write it, take the same styles as the layers' objects. A path with a Calligraphic brush otherwise comes in as the path, the brush on its stroke at the stroke's weight, which scales the brush (#372), and so does a path with an Art brush, whose weight scales the art across the path, when all of these hold: the brush is in Tints or None, at a fixed width from 1% to 1,000%, stretched to the path or stretched between guides that leave art between them, flipped along or across or not ([Art brush options](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf), printed page 193), with `Spacing` 0, `Adjustment` 1 and `FoldAdjustment` 1 (VectorCraft's own reading of these numbers; a brush that scales its art proportionately comes into the Brushes panel with that option, and its paths keep their drawn look); the path's settings are the brush's own (apart from the lowest and highest width of a fixed width and the guides' lengths without Stretch Between Guides, which don't draw), with no entry that isn't read, no variable width and no effects; a stroke in Tints isn't a swatch; and the art is paths, compound paths and groups in solid fills, with no strokes, masks or effects, and has some length along the path. A stroke takes the brush the Brushes panel keeps under its name, and one whose name the panel doesn't keep comes in as its drawn look. Type with an Art brush keeps its drawn look under the type. A Calligraphic brush's Pressure, Stylus Wheel, Tilt, Bearing and Rotation come in as those channels (a 6D Art Pen's brushes vary with the pressure, the bearing and the barrel's rotation). The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. When the file opens from its layers, the spot colors in the art of each brush that comes in become swatches, and that art's colors count toward the document's color mode, as a pattern's do. The swatches take at most 20,000 color names in all across the brush art, and each brush-art section keeps at most 20,000 names. Each name keeps its first definition, with the color operators' names before the gradient stops' names. A spot color past those limits makes no swatch, and its color still counts toward the color mode. A spot color that the page's art, a pattern or a symbol also defines keeps the value defined there. Type keeps its art style as a live appearance whatever its stack (an Art brush aside), so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its detail, smoothness and light direction from its settings block, or the effect's defaults when the style holds no settings block; a settings block that isn't read keeps the drawn look) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an EPS with editing data from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; type on a path keeps its frame's Type on a Path effect, Align to Path and Flip (a frame whose options set key 6 to true keeps their defaults), and the first frame's Spacing is fitted from the file's layout, not read from the dialog's value; the distance from the path under Align to Path is measured for each character at its size and vertical scale (in vertical type, its horizontal scale), from the top of its font's em box (Ascender), half the height of the top of its font's H (Center) or the bottom of its font's bounding box (Descender); the fit under Gravity does not reproduce the file's layout, and its glyphs can lie up to 7.4 pt from the positions the file keeps; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). In a PDF saved with some of its artboards, the type on each page after the first goes to an artboard of that page's size after the previous page's artboard, and only to one that leaves an artboard for each later page; the first page's artboard also leaves one for each later page. When several artboards fit a later page, VectorCraft takes the one whose art draws most like the page, and compares at most 16 artboards for all the later pages together. Symbols are read into the Symbols panel, in the file's symbol list order, with their art, their registration point and the instances in their art, and their instances come in live with their matrix, name, hide, lock, opacity, blending mode, isolation, knockout and opacity mask; a symbol whose art isn't read whole (type, placed files, an image it leaves out or anything else it doesn't read) isn't kept. A file that comes in as its page or PDF part because its editing data has no layers (a symbol library), or because its layers can't be read or used (any of the cases below), gets the symbols its editing data defines before its first layer, in the symbol list's order, while its page art stays as the page draws it. Instances of symbols it can't read, instances with appearance changes of their own (a dynamic symbol's, other than the changes VectorCraft writes in its own entries), pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). A `.ai` is not compared with its page, and its PDF part is not imported, when its text document makes the type of every text object (at least one shows, and none is drawn by the appearance of the layer or group it is in), no object is unread, no placed file has a second placement, no live envelope keeps its drawn art, it declares no large canvas, and its artboards are its pages' trim boxes one for one, in points or in the first page's `UserUnit`: it opens from its layers, with the bleed of its pages' bleed boxes. When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so live objects that only the editing data holds arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (the PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068); the page of the artboard `CropAreaActive` names is then the active artboard. A `.ai` whose editing data has artboards but no layers also opens on that page under the same check, and its pages stay where they are. A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. A run of type in the editing data whose baseline direction is 1 opens with Standard Vertical Roman Alignment (https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) on, which is VectorCraft's own mapping: its half-width characters stand upright in vertical type, and horizontal type keeps the mark with no change to its layout. A run whose baseline direction is 2 or 3 (Tate-chu-yoko), or that names none in the run, its character style or the document's defaults, opens with it off. The scripting reference lists 1, 2 and 3 as the Standard, vertical rotated and Tate-chu-yoko baseline directions (https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf, page 256). A Scatter brush in the editing data whose last 15 numbers start with 1 comes into the Brushes panel in Tints. A Scatter brush's art comes in turned over from its section, as an Art brush's does: in each copy the side of the section with y up goes down the page before the copy's rotation, and the writer writes the art back the same way. Each brush art section is read without its frame: an unnamed, unpainted rectangle with no settings of its own at the art's bounds (within 1/1000 pt), closed, or open with its first corner again at the end. A wider frame stays in the art, and an art group with a state or look of its own (hidden, locked, isolated, knockout, an opacity, a blend mode, a name, a mask, a note or an appearance) stays a group. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 54957e08b7..4ea4e2d775 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -361,7 +361,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | | Layers, artboards, document setup | 5 | 82% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: managing artboards from the canvas (artboard locking and colors, #2532 and #2403, Layers row menus and blend spine row menus are done; guide row menus are done; click-to-fit objects is done, #1227) | 5–8 | estimated; Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 80% | depth of floating-window interactions; floating windows on Wayland drawn inside the main window | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, envelopes and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), images with Warp effects keep the effect editable when they qualify, FreeHand/DWG import, shading and paint fidelity in 3D export (gradient stops are averaged, pattern paint is replaced with gray, and graphics mapped onto the sides of Extrude & Bevel objects and Map Art on the Classic effects are left out of Export 3D Object); see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; aligned type lies as far from its path as the file lays it out (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`); the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours 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, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document 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, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), the editing copy that Include Editing Data for Other Apps writes in a saved `.ai` (VectorCraft reopens the embedded VectorCraft document instead when it is current and readable, unless `document.open` chooses pages or sets `linkPages: true` or `editingData: false`) without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, envelopes, blends, symbols with their instances (except instances the writer writes as their art, with a warning; symbols' 9-slice guides and export types are left out, and a dynamic symbol instance that otherwise qualifies stays live with its parts' fill, stroke, opacity and blend changes, which other apps leave out; the writer keeps them for VectorCraft only when the instance's changes fit in 1 MiB, and fill and stroke changes to type, held as outlines, are not reproduced, and when the copy leaves out an earlier part, such as an empty path, a change applies to a different part or to none) and gradient meshes (except meshes with a Lab point, more than 128 rows or columns, folded meshes, meshes the reader would open otherwise, meshes in pattern tiles or in art cut to a clipping object, and meshes on a large canvas) the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), images with Warp effects keep the effect editable when they qualify, FreeHand/DWG import, shading and paint fidelity in 3D export (gradient stops are averaged, pattern paint is replaced with gray, and graphics mapped onto the sides of Extrude & Bevel objects and Map Art on the Classic effects are left out of Export 3D Object); see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; aligned type lies as far from its path as the file lays it out (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`); the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours 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, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document 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, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658) | 4–7 | estimated (lowered from 85%: target moved); View › Snapping groups five existing toggles and Pixel Snapping Options… (G13), retaining top-level commands and shortcuts; Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged | | Export for Screens, Asset Export, slices, Save for Web | 3 | 87% | TIFF choices and settings are implemented; anti-aliasing ghost borders are fixed (#983) | 2–4 | estimated; depth not measured | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated | @@ -1370,7 +1370,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Dynamic symbol instances on the canvas** ([Symbols, archived copy](https://web.archive.org/web/20240206075757/https://helpx.adobe.com/illustrator/using/symbols.html)): each instance of a dynamic symbol can have an appearance of its own while it shares the symbol's shape. The rest of this entry is VectorCraft's own rules. A Direct Selection click on an instance of a dynamic symbol selects the path, compound path or type object of the symbol's art under the pointer and outlines it (`symbol.instance.selectPart`); the Swatches and Color panels, the Control bar, the Eyedropper and the other fill and stroke controls then change that object's fill or stroke (solid, none, gradient or pattern) for this instance only, each as one undo step, and `transparency.set` changes its opacity and blend the same way; the symbol's art and its other instances stay as they were. Alt or Shift picks the instance whole. An Eyedropper source that is not a path, compound path or type, a click on any other object of the art (a group, image, blend or nested instance) and the commands that change the selected objects (moving, Delete, Group, Hide, Lock, Arrange, Expand, the gradient annotator, isolate/knockout on Transparency, the Appearance panel's rows and others) are refused with a status message. Copy, Export Selection, Fit to Selection, Liquify, Isolate, Add to Library and Save Selection use the whole instance (`docs/mcp.md`), and another selection tool selects the instance whole again. Tests: `crates/engine/src/tests/dynamic_symbols.rs` (`gradients_and_patterns_on_a_picked_object_are_taken`, `opacity_and_blend_on_a_picked_object_go_through_transparency_set`), `direct::tests::a_click_on_a_dynamic_instance_picks_the_object_under_the_pointer`. - **Stained symbol instances in export** ([the help page](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=136), Stain symbol instances): an instance colored with the Symbol Stainer is exported in the colors the canvas draws it in. The mix is VectorCraft's own rule: after a dynamic symbol's own changes, the instance's visible fill mixes the solid fills and strokes of the symbol's art, type included, toward the fill's color by the fill's opacity; a hidden fill or one at 0% leaves the art's colors as they are. SVG, PDF (printing to PDF included), EPS, legacy `.ai`, DXF, EMF and WMF write the stained colors for an instance on its own, in a group, placed through 9-slice guides or reshaped by its geometry effects, and a color adjustment on the instance recolors the stained art. Tests: `bake::tests::a_stained_instance_is_baked_in_its_stained_colors` (vectorcraft-effects), `tests::a_stained_instance_keeps_its_stain` (vectorcraft-pdf), `symbols_layers::a_stained_instance_with_a_geometry_effect_keeps_its_stain` (vectorcraft-svg), and `a_stained_instance_is_written_in_its_stained_color` in vectorcraft-eps (EPS and legacy `.ai`), vectorcraft-cad and vectorcraft-metafile (EMF and WMF). - **9-slice guides on the canvas** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/maintain-proportions-while-scaling-symbols.html)): while a symbol with Enable Guides for 9-Slice Scaling on is edited in symbol editing mode, the canvas draws its two horizontal and two vertical guides as dotted lines across its art, with any tool and with ruler guides hidden. With the Selection tool the pointer near a guide shows the Move cursor, and dragging the guide moves it (`symbol.options`'s `nineSliceGuides`) as one undo step; Escape during the drag puts it back. VectorCraft's own rules: a guide within 4 screen pixels takes the press before the art and the bounding box; it may pass the art's edges (see the next entry) and stops short of the opposite guide; the drag does not snap. Tests: `nineslice::tests`, `symbol_nine_slice::tests::the_edited_symbols_guides_cross_its_art_where_the_editing_layer_shows_it`, `a_moved_guide_passes_the_arts_edges_and_stops_short_of_the_opposite_guide`, `canvas::tests::the_edited_symbols_nine_slice_guides_are_drawn_and_dragged_on_the_canvas`. - - **9-slice guides outside the art** ([the help page](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), Use 9-slice scaling section): a guide may lie outside the symbol's art, set by dragging it past the art's edge in symbol editing mode, by `symbol.options`'s `nineSliceGuides` or by a Symbol Options field below 0% or above 100%, and a scaled instance still scales, by the cells its art falls in. VectorCraft's own rules: each guide lies within 16 times the art's width or height of its edge (`-16..16` as a fraction, `-1600..1600` in percent) and the two guides of an axis keep their order; a guide past an edge of the art cuts the art at that edge, so the outer cell on its side holds no art; with both guides of an axis past opposite edges the art scales as a whole along it; with both past the same edge the art lies in the outer cell at the other edge and keeps its size, from that edge of the instance, or shrinks to the instance's width or height when the instance is smaller than the art; Symbol Options shows and keeps the guides unrounded. Native files keep the guides exactly; SVG and `.ai` write such an instance as its placed art and keep no guides. Tests: `symbol_nine_slice::tests::guides_outside_the_art_are_accepted_in_order_and_within_the_limit`, `art_scales_by_the_cells_it_falls_in_when_guides_lie_outside_it`, `the_map_with_guides_outside_the_art_is_continuous_and_monotone` in `crates/doc`, `guides_outside_the_art_are_set_by_command_and_scale_by_the_cells_that_hold_art`, `a_guide_dragged_past_the_arts_edge_lies_outside_it`, `guides_outside_the_art_survive_saving_and_reopening_a_native_file` in `crates/engine`, `nineslice::tests::a_guide_outside_the_art_is_taken_and_dragged_past_the_arts_edge`, `a_nine_slice_instance_with_a_guide_outside_its_art_is_written_as_drawn` (SVG and `.ai`). + - **9-slice guides outside the art** ([the help page](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf), Use 9-slice scaling section): a guide may lie outside the symbol's art, set by dragging it past the art's edge in symbol editing mode, by `symbol.options`'s `nineSliceGuides` or by a Symbol Options field below 0% or above 100%, and a scaled instance still scales, by the cells its art falls in. VectorCraft's own rules: each guide lies within 16 times the art's width or height of its edge (`-16..16` as a fraction, `-1600..1600` in percent) and the two guides of an axis keep their order; a guide past an edge of the art cuts the art at that edge, so the outer cell on its side holds no art; with both guides of an axis past opposite edges the art scales as a whole along it; with both past the same edge the art lies in the outer cell at the other edge and keeps its size, from that edge of the instance, or shrinks to the instance's width or height when the instance is smaller than the art; Symbol Options shows and keeps the guides unrounded. Native files keep the guides exactly; SVG and `.ai` write such an instance as its placed art, and their standard SVG data and `.ai` editing data for other apps keep no guides; when VectorCraft reopens an `.ai`, or an SVG saved with Preserve Editing Capabilities (`preserveEditing`), from the VectorCraft document embedded in it (the embedded document must be current and readable), the guides return. Tests: `symbol_nine_slice::tests::guides_outside_the_art_are_accepted_in_order_and_within_the_limit`, `art_scales_by_the_cells_it_falls_in_when_guides_lie_outside_it`, `the_map_with_guides_outside_the_art_is_continuous_and_monotone` in `crates/doc`, `guides_outside_the_art_are_set_by_command_and_scale_by_the_cells_that_hold_art`, `a_guide_dragged_past_the_arts_edge_lies_outside_it`, `guides_outside_the_art_survive_saving_and_reopening_a_native_file` in `crates/engine`, `nineslice::tests::a_guide_outside_the_art_is_taken_and_dragged_past_the_arts_edge`, `a_nine_slice_instance_with_a_guide_outside_its_art_is_written_as_drawn` (SVG and `.ai`). - **Delete Symbol asks first** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Alt-click Delete](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): the Symbols panel's Delete Symbol button and menu item ask "Delete the selected symbol?" with Yes and No for a symbol no instance uses. For a symbol with placed instances they ask with Expand Instances (the instances become ordinary art), Delete Instances and Cancel; either Instances button deletes the symbol in one undo step. Alt-click on the button deletes an unused symbol without asking and still asks about one with instances. A question left open while another document became active deletes nothing. `symbol.delete` itself does not ask. Tests: `panels::symbols::tests::delete_symbol_asks_first_and_alt_click_deletes_an_unused_symbol_at_once`, `the_in_use_question_expands_or_deletes_the_instances`, `a_stale_delete_symbol_question_deletes_nothing`, `the_delete_symbol_questions_show_their_buttons`. - **Symbols panel context menu** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): right-clicking a symbol in thumbnail view or list view displays a context menu with Place Symbol Instance (passes view center or artboard center), Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol (enabled when canvas selection includes instances of this symbol), and Select All Instances. Right-clicking an unselected symbol selects it first (`symbol.setCurrent`). Tests: `panels::symbols::tests::right_click_context_menu_in_symbols_panel_runs_actions`. - **Drag a symbol onto New Symbol to duplicate it** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=197), Duplicate a symbol in the panel section): a symbol dragged from the Symbols panel, in thumbnail view or a list view, and released on the New Symbol button is copied as Duplicate Symbol copies it (`symbol.duplicate`), with no Symbol Options dialog, even while no art is selected and the button is disabled for clicks. VectorCraft's own rules: the copy is made of the dragged symbol, not the current one, under Duplicate Symbol's default name, in one undo step; the current symbol and the selection stay as they were and no instance is placed; the button is outlined while a symbol of the document is held over it; a library symbol, art, a name the document no longer has or a symbol dragged from another document is ignored. Tests: `panels::symbols::tests::symbol_dropped_on_new_button_duplicates_the_dragged_symbol_in_both_views`, `new_symbol_button_ignores_other_drops_and_releases_outside`, `a_symbol_dragged_from_another_document_is_not_duplicated`. From da881e42cb286dc623974c8b837ec637fb4f4e67 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 02:34:56 -0800 Subject: [PATCH 38/69] Docs: the .ai editing-copy limit names qualifying images with Warp as kept live --- 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 4ea4e2d775..2ece89214b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -361,7 +361,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | | Layers, artboards, document setup | 5 | 82% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: managing artboards from the canvas (artboard locking and colors, #2532 and #2403, Layers row menus and blend spine row menus are done; guide row menus are done; click-to-fit objects is done, #1227) | 5–8 | estimated; Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 80% | depth of floating-window interactions; floating windows on Wayland drawn inside the main window | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), the editing copy that Include Editing Data for Other Apps writes in a saved `.ai` (VectorCraft reopens the embedded VectorCraft document instead when it is current and readable, unless `document.open` chooses pages or sets `linkPages: true` or `editingData: false`) without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, envelopes, blends, symbols with their instances (except instances the writer writes as their art, with a warning; symbols' 9-slice guides and export types are left out, and a dynamic symbol instance that otherwise qualifies stays live with its parts' fill, stroke, opacity and blend changes, which other apps leave out; the writer keeps them for VectorCraft only when the instance's changes fit in 1 MiB, and fill and stroke changes to type, held as outlines, are not reproduced, and when the copy leaves out an earlier part, such as an empty path, a change applies to a different part or to none) and gradient meshes (except meshes with a Lab point, more than 128 rows or columns, folded meshes, meshes the reader would open otherwise, meshes in pattern tiles or in art cut to a clipping object, and meshes on a large canvas) the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), images with Warp effects keep the effect editable when they qualify, FreeHand/DWG import, shading and paint fidelity in 3D export (gradient stops are averaged, pattern paint is replaced with gray, and graphics mapped onto the sides of Extrude & Bevel objects and Map Art on the Classic effects are left out of Export 3D Object); see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; aligned type lies as far from its path as the file lays it out (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`); the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours 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, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document 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, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), the editing copy that Include Editing Data for Other Apps writes in a saved `.ai` (VectorCraft reopens the embedded VectorCraft document instead when it is current and readable, unless `document.open` chooses pages or sets `linkPages: true` or `editingData: false`) without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (images with a Warp effect keep it editable when they qualify), and with live objects other than grouped column, stacked column, line and area graphs, envelopes, blends, symbols with their instances (except instances the writer writes as their art, with a warning; symbols' 9-slice guides and export types are left out, and a dynamic symbol instance that otherwise qualifies stays live with its parts' fill, stroke, opacity and blend changes, which other apps leave out; the writer keeps them for VectorCraft only when the instance's changes fit in 1 MiB, and fill and stroke changes to type, held as outlines, are not reproduced, and when the copy leaves out an earlier part, such as an empty path, a change applies to a different part or to none) and gradient meshes (except meshes with a Lab point, more than 128 rows or columns, folded meshes, meshes the reader would open otherwise, meshes in pattern tiles or in art cut to a clipping object, and meshes on a large canvas) the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/DWG import, shading and paint fidelity in 3D export (gradient stops are averaged, pattern paint is replaced with gray, and graphics mapped onto the sides of Extrude & Bevel objects and Map Art on the Classic effects are left out of Export 3D Object); see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; aligned type lies as far from its path as the file lays it out (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`); the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours 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, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document 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, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658) | 4–7 | estimated (lowered from 85%: target moved); View › Snapping groups five existing toggles and Pixel Snapping Options… (G13), retaining top-level commands and shortcuts; Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged | | Export for Screens, Asset Export, slices, Save for Web | 3 | 87% | TIFF choices and settings are implemented; anti-aliasing ghost borders are fixed (#983) | 2–4 | estimated; depth not measured | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated | From dcdbd3cc1b3f7747e63d1ae96d6338905074f4ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 02:38:02 -0800 Subject: [PATCH 39/69] CI: declare the files each crate reads in other crates, for test selection Test selection in the shared gate (`select-tests`) runs the tests of the crates a change reaches. A crate that compiles or reads another crate's files lists them under `[package.metadata.craft]` in its Cargo.toml: - vectorcraft-plugins sets `reads-every-member = true`, because `tests/grant_sites.rs` reads the sources of every crate. - vectorcraft-cli, vectorcraft-affinity, vectorcraft-engine, vectorcraft-mcp, vectorcraft-ui-egui and xtask list the files they compile through `#[path]` or read with `include_str!`/`include_bytes!` or from `CARGO_MANIFEST_DIR`. Cargo ignores this table. Only the gate's selection step reads it, and that step fails when a read is missing from it. --- apps/vectorcraft-cli/Cargo.toml | 11 +++++++++++ crates/affinity/Cargo.toml | 4 ++++ crates/engine/Cargo.toml | 11 +++++++++++ crates/mcp/Cargo.toml | 4 ++++ crates/plugins/Cargo.toml | 4 ++++ crates/ui-egui/Cargo.toml | 4 ++++ xtask/Cargo.toml | 4 ++++ 7 files changed, 42 insertions(+) diff --git a/apps/vectorcraft-cli/Cargo.toml b/apps/vectorcraft-cli/Cargo.toml index 376f431903..25cffe599e 100644 --- a/apps/vectorcraft-cli/Cargo.toml +++ b/apps/vectorcraft-cli/Cargo.toml @@ -48,3 +48,14 @@ objc2-core-text = { version = "0.3", default-features = false, features = ["std" tempfile = "3" vectorcraft-testkit = { workspace = true } serde_json = { workspace = true } + +# The files of other crates that this crate compiles or its tests read, for CI's test selection. +[package.metadata.craft] +reads = [ + "apps/vectorcraft/src/mac_fonts.rs", + "apps/vectorcraft/src/prefs_dir.rs", + "apps/vectorcraft/src/profile.rs", + "apps/vectorcraft/src/system_fonts.rs", + "apps/vectorcraft/src/windows_cores.rs", + "crates/plugins/tests/fixtures/desaturate.wasm", +] diff --git a/crates/affinity/Cargo.toml b/crates/affinity/Cargo.toml index 92977884cf..80876c409a 100644 --- a/crates/affinity/Cargo.toml +++ b/crates/affinity/Cargo.toml @@ -24,3 +24,7 @@ craft-image-codecs = { workspace = true } # tests/it's `import_limits`, `outline_limits` and `text` modules need `synth`, also when this crate # is tested without vectorcraft-engine (`cargo xtask ci shard`). vectorcraft-affinity = { path = ".", features = ["synth"] } + +# The files of other crates that this crate's tests compile or read, for CI's test selection. +[package.metadata.craft] +reads = ["xtask/affinity-corpus.sha256", "xtask/src/sha256.rs"] diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 027ae10251..1e74ecb5d2 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -143,3 +143,14 @@ ruzstd = { workspace = true } vectorcraft-js = { workspace = true } # A bundled font's own glyph boxes, for the glyph bounds tests. skrifa = { workspace = true } + +# The files of other crates that this crate compiles or its tests read, for CI's test selection. +[package.metadata.craft] +reads = [ + "crates/affinity/tests/support/corpus.rs", + "crates/affinity/tests/support/text_fixture.rs", + "crates/apischema/src/conformance.rs", + "crates/plugins/tests/fixtures/desaturate.wasm", + "xtask/affinity-corpus.sha256", + "xtask/src/sha256.rs", +] diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index 8aa221b4a6..b5544b958c 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -33,3 +33,7 @@ craft-image-codecs = { workspace = true } vectorcraft-testkit = { workspace = true } proptest = { workspace = true } socket2 = { workspace = true } + +# The files of other crates that this crate's tests compile, for CI's test selection. +[package.metadata.craft] +reads = ["crates/apischema/src/conformance.rs"] diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml index 621f5e79bc..aecb0bd533 100644 --- a/crates/plugins/Cargo.toml +++ b/crates/plugins/Cargo.toml @@ -44,3 +44,7 @@ vectorcraft-plugins = { path = ".", features = ["test-steady"] } [features] # `vectorcraft_plugins::steady` for other crates' tests (dev-dependencies only). test-steady = [] + +# For CI's test selection: `tests/grant_sites.rs` reads the sources of every crate. +[package.metadata.craft] +reads-every-member = true diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 95487e91c0..d0bb345b44 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -109,3 +109,7 @@ wat = { workspace = true } [build-dependencies] serde_json = { workspace = true } toml = "1" + +# The files of other crates that this crate's tests read, for CI's test selection. +[package.metadata.craft] +reads = ["crates/engine/src/cmd/addons/cutting/banner.rs", "crates/plugins/tests/fixtures/desaturate.wasm"] diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 6d935ae8fd..7a5c83e8b5 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -10,3 +10,7 @@ workspace = true [dependencies] serde_json = { workspace = true } + +# The files of other crates that this crate compiles, for CI's test selection. +[package.metadata.craft] +reads = ["crates/text/build/web_fonts.rs"] From e166987050d7d62aba2aa91ca5dd45007e35b442 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 02:59:32 -0800 Subject: [PATCH 40/69] Docs: the Symbols row names the .ai editing-copy limits for dynamic symbol changes The Symbols row now says that VectorCraft restores dynamic symbol instance changes on instances the editing copy keeps live, within the limits the File formats row lists: fill and stroke changes to type are not reproduced, none of an instance's changes is written when they take more than 1 MiB together, and a change can apply to a different part when the copy leaves out an earlier one. --- 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 2ece89214b..c19c35b4f3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -354,7 +354,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Appearance panel row context menus (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with unselected-row targeting, Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | Type core | 9 | 83% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | editable ruby text in standard SVG and PDF artwork (written as outlines; see [type-parity.md](type-parity.md)), custom Mojikumi sets and the Mojikumi Settings dialog, Retype from images, Retype panel matching depth and fused glyphs (see [type-parity.md](type-parity.md)), Touch Type along a line for a character with no immediately preceding logical character on the same line in the same direction (movement along the baseline is disabled; baseline shift still works) | 20–28 | estimated; Retype (`type.retype`, exact and tolerance-based outline matches, #4934); No Break suppresses automatic breaks within the marked run (a forced line break still breaks); upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | remaining: other apps ignore dynamic symbol instance overrides in the `.ai` editing copy, and VectorCraft restores them, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guide settings in the standard SVG data and in the `.ai` editing data written for other apps (the scaled appearance is kept, and `.ai` or SVG saves that embed the VectorCraft document reopen with editable guides); Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | remaining: other apps ignore dynamic symbol instance overrides in the `.ai` editing copy, and VectorCraft restores them on instances the copy keeps live, within the limits the File formats row lists (fill and stroke changes to type are not reproduced, none of an instance's changes is written when they take more than 1 MiB together, and a change can apply to a different part when the copy leaves out an earlier one), further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guide settings in the standard SVG data and in the `.ai` editing data written for other apps (the scaled appearance is kept, and `.ai` or SVG saves that embed the VectorCraft document reopen with editable guides); Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | | Image Trace, graphs, image tools | 3 | 78% | Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, 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, so Paths is monotone on the code-drawn sweep; large images trace with a warning or are downsampled, and images beyond the size and decode limits in `crates/trace/src/raster.rs` are rejected; Auto Color keeps rare distinct colors in coherent regions when the Automatic palette classifies the image as flat artwork) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); Ignore Color canvas sampling reads the original pixels without changing View, keeps a missed pick armed, and retains the manual picker and Preview controls (#8068; scores, gaps and hours unchanged); Create Object Mosaic's dialog with New Size, Constrain Ratio, Resize Using Percentages and Use Ratio is covered by `dialogs::object_mosaic::tests` (score, gaps and hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged 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; runtime pending). | | Live vector effects | 5 | 90% | depth of individual effects | 4–8 | measured count 50/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | | 3D and Materials (and Turntable) | 4 | ~35% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows from lights after the first and in Classic effects (only the first light can cast a shadow in Revolve, Extrude & Bevel, Inflate and Rotate), ray tracing, Turntable views, shading and paint fidelity in 3D export (gradient stops are averaged, pattern paint is replaced with gray, and graphics mapped onto the sides of Extrude & Bevel objects and Map Art on the Classic effects are left out of Export 3D Object) | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); Revolve (Classic) is covered by the `revolve::classic` tests; `a_3d_row_sets_its_param_previews_and_applies_in_one_step` in `crates/ui-egui/src/dialogs/revolve/tests.rs` checks its Angle preview, OK, Cancel and single-step undo; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | From f553ddfa67646ffd711f89eb783b88c15aa3b841 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 03:12:48 -0800 Subject: [PATCH 41/69] xtask: test-lint fails on weak tests in the lines a change touches `cargo xtask test-lint` reads the Rust files changed since a base and fails on tests that a wrong result can pass: `.all()` with no length or emptiness check, only is_ok/is_some/non-empty checks, `assert_eq!(x, x)`, a process test that checks only the exit status, no assertion and no asserting helper, a silent early return on a value from the code under test, `#[ignore]` without a reason, an environment variable that no CI leg sets, `thread::sleep` in test code, and test code that reads Rust source outside the listed source audits. Only hits on changed lines, or in a test with a changed line for the rules about a whole test, fail it; older hits in the same files are counted. The base is --base or TEST_LINT_BASE, the first parent of the checked-out commit in CI (a shallow checkout fetches it), else the merge base with upstream/main or origin/main. `// test-lint: allow ` exempts a line. `--all` lists every hit by crate and rule and does not fail. `cargo xtask ci` runs it after cursors, so it runs in the checks shard. --- docs/development.md | 4 + xtask/src/main.rs | 9 +- xtask/src/test_lint.rs | 2574 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 2586 insertions(+), 1 deletion(-) create mode 100644 xtask/src/test_lint.rs diff --git a/docs/development.md b/docs/development.md index 5a1b6efd95..26058129e7 100644 --- a/docs/development.md +++ b/docs/development.md @@ -349,6 +349,10 @@ The app decides which cursors exist; whoever draws them works from the list. For `cargo xtask brands` (part of `cargo xtask ci`) fails when user-visible text names another vendor's products or company: string literals in Rust sources (command labels and params docs, menus, panels, MCP tool definitions), `Cargo.toml` descriptions and packaging files. Comments, test files and `#[cfg(test)]` modules are not checked. Say "the reference app" or name the feature itself. A line that must keep an old name, such as an alias that files or preferences from earlier versions still use, or a name another project defines, such as a shared MIME type, carries a `brand-ok` comment. In the Linux desktop entry, whose comments take whole lines, the comment goes on the `#` line just above it; `MARK_ABOVE` in `xtask/src/brands.rs` lists the files that accept a mark there. +## Test lint + +`cargo xtask test-lint` (part of `cargo xtask ci`) fails on tests that a wrong result can pass, in the lines and tests changed since a base: `assert!(….all(…))` with no length or emptiness check, a test whose only checks are `is_ok`, `is_some` or `!is_empty`, `assert_eq!(x, x)`, a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, `#[ignore]` without a reason, an environment variable that no CI leg sets, `thread::sleep` in test code, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. + ## Tests - `cargo xtask test` runs the workspace's unit and integration tests with diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 08a55df09a..f48f088aa8 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -18,6 +18,7 @@ mod sha256; mod shards; mod stats; mod test262; +mod test_lint; mod ui_commands; mod version; mod web_fonts; @@ -32,6 +33,10 @@ commands: assets check that every icon/image/font/asset is attributed in ASSETS.md brands check that user-visible text (labels, params docs, MCP, docs, packaging) names no other vendor's products cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails) + test-lint [--base ] [--all] + fail on weak tests (unguarded .all(), only is_ok/is_some checks, no assertion, early + returns, unset env gates, sleeps...) in the lines changed since the base + (xtask/src/test_lint.rs); --all lists every hit by crate and never fails i18n-report list the strings each language's catalog lacks, shown in English (fails only on a broken scan; ci runs it too) ui-commands regenerate crates/mcp/src/ui_catalog.rs from desktop UI_COMMANDS; --check fails on drift @@ -39,7 +44,7 @@ commands: layers enforce the crate dependency layering (plan/architecture.md §3) 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, cursors (warnings only), ui-commands --check, layers, wasm (stops at first failure) + ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, 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 @@ -74,6 +79,7 @@ fn main() -> ExitCode { Some("assets") => assets::run(&root()), Some("brands") => brands::run(&root()), Some("cursors") => cursors::run(&root()), + Some("test-lint") => test_lint::run(&root(), &rest), Some("i18n-report") => cmd_i18n_report(), Some("ui-commands") => ui_commands::run(&root(), rest.contains(&"--check")), Some("layers") => cmd_layers(), @@ -515,6 +521,7 @@ fn ci_steps() -> Vec { ("assets", Box::new(|| assets::run(&root()))), ("brands", Box::new(|| brands::run(&root()))), ("cursors", Box::new(|| cursors::run(&root()))), + ("test-lint", Box::new(|| test_lint::run(&root(), &[]))), ("i18n-report", Box::new(cmd_ci_i18n_report)), ("ui-commands", Box::new(|| ui_commands::run(&root(), true))), ("layers", Box::new(cmd_layers)), diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs new file mode 100644 index 0000000000..8664403997 --- /dev/null +++ b/xtask/src/test_lint.rs @@ -0,0 +1,2574 @@ +//! `cargo xtask test-lint`: tests that a wrong result can pass, in the tests a change touches. +//! +//! Rules, checked in `#[test]` functions (and `#[tokio::test]`, `#[test_case]`, +//! `#[wasm_bindgen_test]`, and `#[test]` inside `proptest!`): +//! * `all-unguarded`: `assert!(….all(…))` in a test that neither checks a length, emptiness, +//! count, first item or `any` in an assertion's condition or compared operands, nor takes a +//! first item by indexing, unwrapping or a panicking `let … else`: `.all()` is true for an empty +//! collection (negated `.all(…)`, including `== false`, and predicates saying that no item +//! matches, with whole negations or `!=` comparisons joined only by `&&`, are left out). An earlier +//! `assert_eq!`, `debug_assert_eq!` or `prop_assert_eq!` comparing a plain local receiver +//! (optionally borrowed or viewed through `.as_slice()` or `[..]`) with a non-empty array +//! literal or `vec![…]` guards only that receiver. Non-empty array literals and plain local +//! names bound to them in the test, optionally through `.map(…)`, are also left out. Empty arrays +//! still count. A change anywhere in the test counts as a change to the hit; +//! * `only-weak`: every assertion is `is_ok()`, `is_some()`, `!is_empty()` or `len() > 0`, and the +//! test calls no asserting helper; +//! * `self-compare`: `assert_eq!(x, x)` or `assert_ne!(x, x)` on the same expression, when that +//! expression calls nothing with arguments (two calls with arguments check determinism); +//! * `exit-status-only`: a test that runs a process and checks only its exit status, reading no +//! output, with a status check in any condition or compared operand of a standard assertion; +//! * `no-assertion`: no assertion macro, `panic!`, `unwrap_err`, `expect_err` or asserting helper, +//! and no `#[should_panic]`; +//! * `early-return`: a silent bare `return` before the end of the test whose guard tests a value +//! from the code under test. Left out: a return after an assertion in its block, one whose +//! statement or line has a comment or a printed note saying why, and guards on files, fonts, +//! corpora, environment variables, the platform or a child process; +//! * `ignore-without-reason`: `#[ignore]` with no `= "reason"`; +//! * `env-gate-unset`: `env::var("NAME")` in a test where no CI workflow, the shared gate or the +//! file itself sets `NAME`; workflow mapping keys and `NAME=` assignments count, but comments +//! and variable reads do not; +//! * `sleep`: `thread::sleep` in test code; +//! * `reads-source`: test code that reads Rust source (`include_str!` of a `.rs` file, or a walk +//! that keeps files ending in `.rs`), outside the source audits in [`SOURCE_AUDITS`]. +//! +//! Test code is a test file (`tests.rs`, `tests_*.rs`, `*_tests.rs`, a file in a `tests` or +//! `benches` folder, `crates/testkit`), an item under `#[cfg(test)]`, or a test function. +//! +//! An asserting helper is a function or macro in the crate's test code (or in `crates/testkit`) +//! that asserts, panics or calls one that does, or a call whose name starts with `assert`, +//! `check`, `verify`, `ensure` or `expect_`. +//! +//! `// test-lint: allow ` exempts the line it is on and the line below it; for the +//! rules about a whole test it can be on any line from the line above the test attribute to the +//! `fn` line. An allow without a reason exempts nothing. +//! +//! `cargo xtask test-lint` fails on the hits in the lines and tests changed since a base: `--base +//! ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's +//! merge commit is checked out, and a shallow checkout fetches that parent); elsewhere the merge +//! base of `HEAD` and `upstream/main` or `origin/main`. Uncommitted and untracked files count as +//! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the +//! workspace by crate and rule, and does not fail. + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::path::Path; +use std::process::Command; + +/// Test files that read Rust source on purpose: they audit the source tree. +pub const SOURCE_AUDITS: &[&str] = &[ + "crates/plugins/tests/grant_sites.rs", + "crates/ui-egui/src/i18n/tests.rs", + "crates/ui-egui/src/icons.rs", + "crates/eps/src/import/tests_generators.rs", +]; + +/// Variables the shared gate workflow and its setup action set on every leg, besides those named +/// in `.github/workflows/*.yml`. +const SHARED_GATE_ENV: &[&str] = + &["CRAFT_FONTS_DIR", "CRAFT_FONTS_REQUIRED", "GATE_SHARD", "GATE_SHARDS", "NEXTEST_PARTITION", "NEXTEST_ARCHIVE_FILE"]; + +/// Variables the runner, the operating system or cargo set. +const SYSTEM_ENV: &[&str] = &[ + "HOME", + "PATH", + "USER", + "USERNAME", + "LOGNAME", + "TMPDIR", + "TEMP", + "TMP", + "APPDATA", + "LOCALAPPDATA", + "USERPROFILE", + "PROGRAMDATA", + "PROGRAMFILES", + "WINDIR", + "SYSTEMROOT", + "CI", + "LANG", + "SHELL", + "PWD", + "OUT_DIR", +]; +const SYSTEM_ENV_PREFIXES: &[&str] = &["CARGO_", "NEXTEST", "RUST", "GITHUB_", "RUNNER_", "XDG_"]; + +/// Larger source files are refused rather than read. +const MAX_FILE: u64 = 16 << 20; + +/// The marker of an exemption comment. +const ALLOW: &str = "test-lint: allow "; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Rule { + AllUnguarded, + OnlyWeak, + SelfCompare, + ExitStatusOnly, + NoAssertion, + EarlyReturn, + IgnoreWithoutReason, + EnvGateUnset, + Sleep, + ReadsSource, +} + +impl Rule { + pub const ALL: [Rule; 10] = [ + Rule::AllUnguarded, + Rule::OnlyWeak, + Rule::SelfCompare, + Rule::ExitStatusOnly, + Rule::NoAssertion, + Rule::EarlyReturn, + Rule::IgnoreWithoutReason, + Rule::EnvGateUnset, + Rule::Sleep, + Rule::ReadsSource, + ]; + + pub fn id(self) -> &'static str { + match self { + Rule::AllUnguarded => "all-unguarded", + Rule::OnlyWeak => "only-weak", + Rule::SelfCompare => "self-compare", + Rule::ExitStatusOnly => "exit-status-only", + Rule::NoAssertion => "no-assertion", + Rule::EarlyReturn => "early-return", + Rule::IgnoreWithoutReason => "ignore-without-reason", + Rule::EnvGateUnset => "env-gate-unset", + Rule::Sleep => "sleep", + Rule::ReadsSource => "reads-source", + } + } + + fn advice(self) -> &'static str { + match self { + Rule::AllUnguarded => "also assert the expected length (or that the collection is not empty)", + Rule::OnlyWeak => "assert the value itself (assert_eq! on the result), not only that there is one", + Rule::SelfCompare => "compare with an expected value written out, or with a second, independent computation", + Rule::ExitStatusOnly => "also check the output (stdout, stderr or the files written)", + Rule::NoAssertion => "assert what the code returns or changes", + Rule::EarlyReturn => "assert the condition instead of returning, so a wrong value fails the test", + Rule::IgnoreWithoutReason => "write #[ignore = \"why\"]", + Rule::EnvGateUnset => "set the variable in a CI leg, or make the test run without it", + Rule::Sleep => "wait on a handshake (channel, barrier) or a controllable clock", + Rule::ReadsSource => "test the behavior, or add the file to SOURCE_AUDITS in xtask/src/test_lint.rs if it audits the source tree", + } + } + + fn from_id(id: &str) -> Option { + Rule::ALL.into_iter().find(|r| r.id() == id) + } +} + +/// A rule broken in a file. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Hit { + pub path: String, + /// 1-based: the line of the finding, or of `fn` for a rule about a whole test. + pub line: usize, + pub rule: Rule, + /// The test it is in; empty for test code outside a test function. + pub test: String, + pub note: String, + /// The first and last line of what the hit covers: the test, from its attribute to its closing + /// brace, for a rule about a whole test or `all-unguarded`, through the second operand for + /// `self-compare`, else `line`. This span controls changed-line detection; `all-unguarded` + /// and `self-compare` exemptions still apply only near `line`. + pub first: usize, + pub last: usize, +} + +impl Hit { + fn show(&self) -> String { + let test = if self.test.is_empty() { String::new() } else { format!(" `{}`", self.test) }; + format!("{}:{}: [{}]{test}: {}", self.path, self.line, self.rule.id(), self.note) + } +} + +/// What the rules need beyond the file: asserting helper names by crate and the variables CI sets. +pub struct Ctx { + pub helpers: HashMap>, + pub ci_env: HashSet, +} + +pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { + let opts = Options::parse(args)?; + let repo = crate::repo_files(root)?; + let ci_env = ci_env(root, &repo)?; + let files: Vec = repo.into_iter().filter(|p| is_scanned(p)).collect(); + if opts.all { + let sources = read_all(root, &files)?; + let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env }; + let hits: Vec = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); + print!("{}", report(&hits, sources.len())); + return Ok(()); + } + let base = resolve_base(root, opts.base)?; + let changed = changed_lines(root, &base)?; + let changed: BTreeMap>> = changed.into_iter().filter(|(p, _)| is_scanned(p)).collect(); + let crates: BTreeSet = changed.keys().map(|p| crate_of(p)).chain([TESTKIT.to_owned()]).collect(); + let helper_files: Vec = files.iter().filter(|p| crates.contains(&crate_of(p))).cloned().collect(); + let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env }; + let present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); + let (mut counted, mut older) = (vec![], 0usize); + for (path, src) in read_all(root, &present)? { + for hit in lint_file(&path, &src, &ctx) { + if touches(&hit, changed.get(&path).and_then(Option::as_ref)) { + counted.push(hit); + } else { + older += 1; + } + } + } + finish(&counted, older, present.len(), &base) +} + +/// The command line: `--all`, `--base `. +#[derive(Debug, Default, PartialEq)] +struct Options { + all: bool, + base: Option, +} + +impl Options { + fn parse(args: &[&str]) -> Result { + let mut opts = Options::default(); + let mut it = args.iter(); + while let Some(&arg) = it.next() { + match arg { + "--all" if !opts.all => opts.all = true, + "--base" if opts.base.is_none() => match it.next() { + Some(rev) if !rev.is_empty() && !rev.starts_with('-') => opts.base = Some((*rev).to_owned()), + _ => return Err("test-lint: --base takes a revision".into()), + }, + _ => return Err(format!("test-lint: unexpected argument `{arg}` (usage: cargo xtask test-lint [--all] [--base ])")), + } + } + if opts.all && opts.base.is_some() { + return Err("test-lint: --all checks every file and takes no --base".into()); + } + Ok(opts) + } +} + +fn finish(counted: &[Hit], older: usize, files: usize, base: &str) -> Result<(), String> { + let older = if older == 0 { String::new() } else { format!("; {older} hit(s) on unchanged lines of those files are not counted") }; + if counted.is_empty() { + println!("test-lint: no hits in the changed lines of {files} Rust file(s) since {base}{older}"); + return Ok(()); + } + let mut out: Vec = counted.iter().map(Hit::show).collect(); + let rules: BTreeSet = counted.iter().map(|h| h.rule).collect(); + out.extend(rules.iter().map(|r| format!("{}: {}", r.id(), r.advice()))); + Err(format!( + "{} test-lint hit(s) in the lines changed since {base}{older} (exempt a line with `// {ALLOW} `):\n {}", + counted.len(), + out.join("\n ") + )) +} + +/// `--all`: counts by crate and rule, then every hit. +fn report(hits: &[Hit], files: usize) -> String { + let mut by_crate: BTreeMap> = BTreeMap::new(); + for h in hits { + *by_crate.entry(crate_of(&h.path)).or_default().entry(h.rule).or_default() += 1; + } + let mut out = format!("test-lint --all: {} hit(s) in {files} Rust file(s)\n\nby rule:\n", hits.len()); + for rule in Rule::ALL { + out += &format!(" {:<22} {}\n", rule.id(), hits.iter().filter(|h| h.rule == rule).count()); + } + out += "\nby crate:\n"; + for (krate, rules) in &by_crate { + let list: Vec = rules.iter().map(|(r, n)| format!("{} {n}", r.id())).collect(); + out += &format!(" {krate}: {}\n", list.join(", ")); + } + out += "\nhits:\n"; + for h in hits { + out += &format!(" {}\n", h.show()); + } + out +} + +/// Rust files the lint reads. +fn is_scanned(path: &str) -> bool { + path.ends_with(".rs") && ["crates/", "apps/", "xtask/"].iter().any(|d| path.starts_with(d)) +} + +/// `crates/` or `apps/` for a file in one, else its first path component. +fn crate_of(path: &str) -> String { + let parts: Vec<&str> = path.split('/').collect(); + match parts.as_slice() { + [top @ ("crates" | "apps"), name, _, ..] => format!("{top}/{name}"), + [first, ..] => (*first).to_owned(), + [] => String::new(), + } +} + +fn read_all(root: &Path, paths: &[String]) -> Result, String> { + paths + .iter() + .map(|p| { + let full = root.join(p); + let len = std::fs::metadata(&full).map_err(|e| format!("{p}: {e}"))?.len(); + if len > MAX_FILE { + return Err(format!("{p}: {len} bytes, over test-lint's limit of {MAX_FILE}")); + } + Ok((p.clone(), std::fs::read_to_string(&full).map_err(|e| format!("{p}: {e}"))?)) + }) + .collect() +} + +// ---- Git: the base and the changed lines ---- + +fn git(root: &Path, args: &[&str]) -> Result { + let out = Command::new("git").current_dir(root).args(args).output().map_err(|e| format!("git {}: {e}", args.join(" ")))?; + if !out.status.success() { + return Err(format!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim())); + } + Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned()) +} + +fn resolve_base(root: &Path, explicit: Option) -> Result { + if let Some(rev) = explicit.or_else(|| std::env::var("TEST_LINT_BASE").ok().filter(|v| !v.is_empty())) { + return git(root, &["rev-parse", "--verify", "--quiet", &format!("{rev}^{{commit}}")]) + .map_err(|_| format!("test-lint: base `{rev}` is not a commit")); + } + if std::env::var_os("GITHUB_ACTIONS").is_some() { + if let Ok(parent) = git(root, &["rev-parse", "--verify", "--quiet", "HEAD^1^{commit}"]) { + return Ok(parent); + } + let head = git(root, &["rev-parse", "HEAD"])?; + git(root, &["fetch", "--no-tags", "--quiet", "--depth=2", "origin", &head])?; + return git(root, &["rev-parse", "--verify", "--quiet", "HEAD^1^{commit}"]) + .map_err(|_| "test-lint: HEAD has no parent to compare with (set TEST_LINT_BASE)".into()); + } + for main in ["upstream/main", "origin/main"] { + if let Ok(base) = git(root, &["merge-base", "HEAD", main]) { + return Ok(base); + } + } + Err("test-lint: no upstream/main or origin/main to compare with; pass --base or set TEST_LINT_BASE".into()) +} + +/// The changed files since `base` with their changed lines (new numbering); `None` for a file that +/// is new or untracked. A pure deletion marks the lines before and after it, or line 1 at the top +/// of the file. +fn changed_lines(root: &Path, base: &str) -> Result>>, String> { + let diff = git( + root, + &["-c", "core.quotepath=off", "diff", "-U0", "--no-color", "--no-ext-diff", "--src-prefix=a/", "--dst-prefix=b/", base, "--", "*.rs"], + )?; + let mut out = parse_diff(&diff); + for path in git(root, &["-c", "core.quotepath=off", "ls-files", "--others", "--exclude-standard", "--", "*.rs"])?.lines() { + out.insert(path.to_owned(), None); + } + Ok(out) +} + +/// The changed new-side lines in each file. A pure deletion includes its anchor and the following +/// line, or just line 1 when the anchor is 0. +fn parse_diff(diff: &str) -> BTreeMap>> { + let mut out: BTreeMap>> = BTreeMap::new(); + let mut current: Option = None; + // Inside a file's header (from `diff --git` to its first hunk), where `+++ ` names the file. + let (mut header, mut new_file) = (false, false); + for line in diff.lines() { + if line.starts_with("diff --git ") { + (header, new_file) = (true, false); + } else if header && line.starts_with("new file mode") { + new_file = true; + } else if let Some(path) = line.strip_prefix("+++ ").filter(|_| header) { + current = path.strip_prefix("b/").map(str::to_owned); + if let Some(p) = ¤t { + out.insert(p.clone(), if new_file { None } else { Some(BTreeSet::new()) }); + } + } else if let (Some(hunk), Some(path)) = (line.strip_prefix("@@ "), ¤t) { + header = false; + if let (Some((start, count)), Some(Some(lines))) = (hunk_range(hunk), out.get_mut(path)) { + if count == 0 { + lines.extend(start.max(1)..=start.saturating_add(1)); + } else { + lines.extend(start..start + count); + } + } + } + } + out +} + +/// `(start, count)` of the new side of a hunk header's `-a,b +c,d @@`. A pure deletion has count 0 +/// and sits between lines c and c + 1; c = 0 places it before line 1. +fn hunk_range(hunk: &str) -> Option<(usize, usize)> { + let new = hunk.split_whitespace().find(|w| w.starts_with('+'))?.trim_start_matches('+'); + match new.split_once(',') { + Some((s, c)) => Some((s.parse().ok()?, c.parse().ok()?)), + None => Some((new.parse().ok()?, 1)), + } +} + +/// Whether `hit` covers a changed line (`None`: the whole file is new). +fn touches(hit: &Hit, changed: Option<&BTreeSet>) -> bool { + changed.is_none_or(|lines| lines.range(hit.first..=hit.last).next().is_some()) +} + +// ---- What CI sets ---- + +fn ci_env(root: &Path, files: &[String]) -> Result, String> { + let mut names: HashSet = SHARED_GATE_ENV.iter().map(|s| (*s).to_owned()).collect(); + for path in files.iter().filter(|p| p.starts_with(".github/workflows/") && (p.ends_with(".yml") || p.ends_with(".yaml"))) { + let text = std::fs::read_to_string(root.join(path)).map_err(|e| format!("{path}: {e}"))?; + names.extend(upper_words(&text)); + } + Ok(names) +} + +/// Workflow mapping keys and assignments with capitalized environment variable names. +fn upper_words(text: &str) -> impl Iterator + '_ { + text.lines().flat_map(|line| { + let line = workflow_code(line); + let start = line.trim_start().strip_prefix("- ").unwrap_or(line.trim_start()).trim_start(); + let mapping = + start.split_once(':').filter(|(name, rest)| env_assignment_name(name) && (rest.is_empty() || rest.starts_with(char::is_whitespace))); + let assignments = line.match_indices('=').filter_map(move |(at, _)| { + let name = line[..at].rsplit(|c: char| !(c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')).next().unwrap_or_default(); + let from = at - name.len(); + let boundary = from == 0 || line.as_bytes().get(from - 1).is_some_and(|c| c.is_ascii_whitespace() || matches!(c, b'\'' | b'"' | b';')); + (boundary && env_assignment_name(name) && !line[at + 1..].starts_with(['=', '>'])).then(|| name.to_owned()) + }); + mapping.map(|(name, _)| name.to_owned()).into_iter().chain(assignments) + }) +} + +fn env_assignment_name(name: &str) -> bool { + name.len() > 1 + && name.starts_with(|c: char| c.is_ascii_uppercase()) + && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_') +} + +/// Removes comment text outside quotes from a workflow line. +fn workflow_code(line: &str) -> &str { + let (mut quote, mut escaped) = (None, false); + for (at, c) in line.char_indices() { + if escaped { + escaped = false; + } else if c == '\\' && quote != Some('\'') { + escaped = true; + } else if quote == Some(c) { + quote = None; + } else if quote.is_none() { + match c { + '\'' | '"' => quote = Some(c), + '#' => return &line[..at], + _ => {} + } + } + } + line +} + +fn set_by_system(name: &str) -> bool { + SYSTEM_ENV.contains(&name) || SYSTEM_ENV_PREFIXES.iter().any(|p| name.starts_with(p)) +} + +// ---- Lexing ---- + +fn is_ident(c: u8) -> bool { + c.is_ascii_alphanumeric() || c == b'_' +} + +/// `src` with the text of comments and of string and character literals replaced by spaces (line +/// breaks and quotes kept), at the same byte offsets. +fn mask(src: &str) -> Vec { + mask_with(src, true) +} + +/// [`mask`], keeping comments when `comments` is false. +fn mask_with(src: &str, comments: bool) -> Vec { + mask_parts(src, comments, true) +} + +/// Blanks comments while keeping code and literal contents at the same byte offsets. +fn mask_comments(src: &str) -> Vec { + mask_parts(src, true, false) +} + +/// Blanks the selected comments and literal contents, preserving line breaks and literal quotes. +fn mask_parts(src: &str, comments: bool, literals: bool) -> Vec { + let b = src.as_bytes(); + let mut out = b.to_vec(); + let mut i = 0; + while i < b.len() { + let next = match b[i] { + b'/' if b.get(i + 1) == Some(&b'/') => { + let end = find(b, b"\n", i).unwrap_or(b.len()); + if comments { + blank(&mut out, i, end); + } + end + } + b'/' if b.get(i + 1) == Some(&b'*') => { + let end = block_comment_end(b, i); + if comments { + blank(&mut out, i, end); + } + end + } + b'"' => { + let end = string_end(b, i + 1); + if literals { + blank(&mut out, i + 1, end.saturating_sub(1)); + } + end + } + b'\'' => { + let end = after_char_or_lifetime(src, i); + if literals { + blank(&mut out, i + 1, end.saturating_sub(1).max(i + 1)); + } + end + } + c if c.is_ascii_alphabetic() || c == b'_' => after_ident(b, &mut out, i, literals), + _ => i + 1, + }; + i = next.max(i + 1); + } + out +} + +fn blank(out: &mut [u8], from: usize, to: usize) { + for c in out.iter_mut().take(to).skip(from) { + if *c != b'\n' { + *c = b' '; + } + } +} + +fn block_comment_end(b: &[u8], mut i: usize) -> usize { + let mut nest = 0usize; + while i < b.len() { + if b[i..].starts_with(b"/*") { + nest += 1; + i += 2; + } else if b[i..].starts_with(b"*/") { + nest = nest.saturating_sub(1); + i += 2; + if nest == 0 { + return i; + } + } else { + i += 1; + } + } + b.len() +} + +/// The index after the closing quote of a `"…"` literal whose body starts at `i`. +fn string_end(b: &[u8], mut i: usize) -> usize { + while i < b.len() && b[i] != b'"' { + i += if b[i] == b'\\' { 2 } else { 1 }; + } + (i + 1).min(b.len()) +} + +/// The index after a char literal (`'x'`, `'\n'`, `'\u{…}'`) at `i`, or after the quote of a +/// lifetime or label. +fn after_char_or_lifetime(src: &str, i: usize) -> usize { + let b = src.as_bytes(); + if b.get(i + 1) == Some(&b'\\') { + let close = (i + 3..b.len()).find(|&j| b[j] == b'\'').unwrap_or(b.len()); + return (close + 1).min(b.len()); + } + match src.get(i + 1..).and_then(|s| s.chars().next()) { + Some(c) if b.get(i + 1 + c.len_utf8()) == Some(&b'\'') => i + 2 + c.len_utf8(), + _ => i + 1, + } +} + +/// Skips the identifier at `start`; a raw string prefix (`r`, `br`, `cr`) also skips the raw +/// string after it and blanks its contents when `literals` is true. +fn after_ident(b: &[u8], out: &mut [u8], start: usize, literals: bool) -> usize { + let mut i = start; + while i < b.len() && is_ident(b[i]) { + i += 1; + } + if start > 0 && is_ident(b[start - 1]) { + return i; + } + let hashes = b[i..].iter().take_while(|&&h| h == b'#').count(); + if !matches!(&b[start..i], b"r" | b"br" | b"cr") || b.get(i + hashes) != Some(&b'"') { + return i; + } + let body = i + hashes + 1; + let close: Vec = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let end = find(b, &close, body).unwrap_or(b.len()); + if literals { + blank(out, body, end); + } + (end + close.len()).min(b.len()) +} + +fn find(hay: &[u8], needle: &[u8], from: usize) -> Option { + if needle.is_empty() || from >= hay.len() { + return None; + } + hay[from..].windows(needle.len()).position(|w| w == needle).map(|p| p + from) +} + +fn contains(hay: &[u8], needle: &[u8]) -> bool { + find(hay, needle, 0).is_some() +} + +fn skip_ws(b: &[u8], mut i: usize) -> usize { + while i < b.len() && b[i].is_ascii_whitespace() { + i += 1; + } + i +} + +/// Every start of `word` in `b[from..to]` with no identifier character on either side. +fn words(b: &[u8], word: &[u8], from: usize, to: usize) -> Vec { + let mut out = vec![]; + let mut i = from; + while let Some(at) = find(&b[..to.min(b.len())], word, i) { + let before = at.checked_sub(1).and_then(|j| b.get(j)).copied().is_some_and(is_ident); + let after = b.get(at + word.len()).copied().is_some_and(is_ident); + if !before && !after { + out.push(at); + } + i = at + 1; + } + out +} + +/// The index of the bracket closing the one at `open`. +fn matching(m: &[u8], open: usize) -> Option { + let (o, c) = match m.get(open)? { + b'(' => (b'(', b')'), + b'[' => (b'[', b']'), + b'{' => (b'{', b'}'), + _ => return None, + }; + let mut depth = 0usize; + for (j, &ch) in m.iter().enumerate().skip(open) { + if ch == o { + depth += 1; + } else if ch == c { + depth = depth.saturating_sub(1); + if depth == 0 { + return Some(j); + } + } + } + None +} + +/// The ranges of the top-level comma-separated parts of `m[from..to]`. +fn split_args(m: &[u8], from: usize, to: usize) -> Vec<(usize, usize)> { + let (mut out, mut depth, mut start) = (vec![], 0i32, from); + let mut angles = 0usize; + for (j, &ch) in m.iter().enumerate().take(to).skip(from) { + match ch { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth -= 1, + b'<' if angles > 0 || m[from..j].trim_ascii_end().ends_with(b"::") => angles += 1, + b'>' if angles > 0 => angles -= 1, + b',' if depth == 0 && angles == 0 => { + out.push((start, j)); + start = j + 1; + } + _ => {} + } + } + if m[start..to].iter().any(|c| !c.is_ascii_whitespace()) { + out.push((start, to)); + } + out +} + +/// `b` without whitespace. +fn norm(b: &[u8]) -> String { + String::from_utf8_lossy(&b.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect::>()).into_owned() +} + +/// Line starts, to turn byte offsets into 1-based lines. +struct Lines(Vec); + +impl Lines { + fn new(src: &str) -> Lines { + Lines(std::iter::once(0).chain(src.match_indices('\n').map(|(i, _)| i + 1)).collect()) + } + + fn of(&self, pos: usize) -> usize { + self.0.partition_point(|&s| s <= pos) + } +} + +// ---- Tests and calls ---- + +/// A test function: its name, the offsets of its first attribute and `fn`, and its body's braces. +#[derive(Debug)] +struct TestFn { + name: String, + /// The first attribute of the function (`#[should_panic]` can come before `#[test]`). + attr: usize, + fn_at: usize, + open: usize, + close: usize, +} + +fn is_test_attr(path: &[u8]) -> bool { + matches!(path, b"test" | b"wasm_bindgen_test" | b"test_case") || path.ends_with(b"::test") || path.ends_with(b"::test_case") +} + +/// The test functions of masked source `m`. +fn tests_in(m: &[u8]) -> Vec { + let mut out: Vec = vec![]; + let mut i = 0; + while let Some(at) = find(m, b"#[", i) { + i = at + 2; + let start = skip_ws(m, at + 2); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c) || c == b':').count(); + if !is_test_attr(&m[start..end]) || !matches!(m.get(skip_ws(m, end)), Some(b']' | b'(')) { + continue; + } + let Some(t) = fn_after(m, at, end) else { continue }; + if out.iter().any(|o| o.fn_at == t.fn_at) { + continue; + } + i = t.open; + out.push(t); + } + out +} + +/// The function an attribute at `attr` (ending at `from`) belongs to. +fn fn_after(m: &[u8], attr: usize, from: usize) -> Option { + let limit = (from + 800).min(m.len()); + let fn_at = *words(m, b"fn", from, limit).first()?; + if m[from..fn_at].iter().any(|&c| c == b'{' || c == b';') { + return None; + } + let name_start = skip_ws(m, fn_at + 2); + let name_end = name_start + m[name_start..].iter().take_while(|&&c| is_ident(c)).count(); + if name_end == name_start { + return None; + } + let open = name_end + m[name_end..].iter().position(|&c| c == b'{' || c == b';')?; + if m[open] != b'{' { + return None; + } + let close = matching(m, open)?; + // The item starts after the previous item or block opening; comments before it are masked. + let item = m[..attr].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let attr = skip_ws(m, item).min(attr); + Some(TestFn { name: String::from_utf8_lossy(&m[name_start..name_end]).into_owned(), attr, fn_at, open, close }) +} + +/// A macro call in a test: its name, offset and argument ranges. +struct MacroCall { + name: String, + at: usize, + args: Vec<(usize, usize)>, +} + +/// The macro calls (`name!(…)`, `name![…]`, `name!{…}`) in `m[from..to]`. +fn macro_calls(m: &[u8], from: usize, to: usize) -> Vec { + let mut out = vec![]; + let mut i = from; + while let Some(bang) = find(&m[..to], b"!", i) { + i = bang + 1; + let start = (from..bang).rev().take_while(|&j| is_ident(m[j])).last().unwrap_or(bang); + let open = skip_ws(m, bang + 1); + if start == bang || start.checked_sub(1).is_some_and(|j| is_ident(m[j])) || !matches!(m.get(open), Some(b'(' | b'[' | b'{')) { + continue; + } + let Some(close) = matching(m, open).filter(|&c| c < to) else { continue }; + out.push(MacroCall { name: String::from_utf8_lossy(&m[start..bang]).into_owned(), at: start, args: split_args(m, open + 1, close) }); + } + out +} + +fn is_assert_macro(name: &str) -> bool { + ["assert", "debug_assert", "prop_assert"].iter().any(|p| name.starts_with(p)) +} + +const KEYWORDS: &[&str] = &["if", "while", "match", "for", "loop", "return", "fn", "in", "as", "let", "else", "move", "Some", "Ok", "Err"]; + +/// Names that helper detection ignores: too common to tell a helper from the code under test. +const COMMON: &[&str] = &[ + "new", "default", "from", "into", "get", "set", "run", "apply", "build", "make", "open", "load", "save", "parse", "read", "write", "draw", + "render", "len", "clone", "push", "vec", "format", "json", "Box", "Arc", "Vec", "String", "main", +]; + +/// The names called in `m[from..to]`: functions (`name(`, also through a path), methods +/// (`.name(`), including calls with turbofish arguments, and macros (`name!`). +fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { + let m = &m[..to]; + let mut out = vec![]; + let mut i = from; + while i < to { + if !(m[i].is_ascii_alphabetic() || m[i] == b'_') || (i > 0 && is_ident(m[i - 1])) { + i += 1; + continue; + } + let end = i + m[i..to].iter().take_while(|&&c| is_ident(c)).count(); + let bang = m.get(end) == Some(&b'!'); + let after = skip_ws(m, end + usize::from(bang)); + let after = if bang { after } else { skip_turbofish(m, after) }; + if matches!(m.get(after), Some(b'(' | b'[' | b'{')) && (bang || m[after] == b'(') { + let name = String::from_utf8_lossy(&m[i..end]).into_owned(); + let method = i > 0 && m[i - 1] == b'.'; + if !KEYWORDS.contains(&name.as_str()) { + out.push((if bang { format!("{name}!") } else { name }, method)); + } + } + i = end; + } + out +} + +/// Skips optional `::<…>` arguments and the whitespace after them. +fn skip_turbofish(m: &[u8], at: usize) -> usize { + if !m[at..].starts_with(b"::") { + return at; + } + let open = skip_ws(m, at + 2); + if m.get(open) != Some(&b'<') { + return at; + } + let (mut i, mut depth) = (open + 1, 1usize); + while i < m.len() { + match m[i] { + b'<' => depth += 1, + b'>' if m[i - 1] != b'-' => { + depth -= 1; + if depth == 0 { + return skip_ws(m, i + 1); + } + } + b'(' | b'[' | b'{' => i = matching(m, i).unwrap_or(m.len()), + _ => {} + } + i += 1; + } + m.len() +} + +/// Whether `name` (a call in a test) is an asserting helper. +fn is_helper_call(name: &str, method: bool, helpers: &HashSet) -> bool { + let base = name.trim_end_matches('!'); + let named = ["assert", "check", "verify", "ensure", "expect_"].iter().any(|p| base.starts_with(p)); + named || (!method && !COMMON.contains(&base) && helpers.contains(name)) +} + +/// Whether the masked text checks something itself: an assertion, `panic!`, `unwrap_err` or +/// `expect_err`. +fn checks_itself(m: &[u8], from: usize, to: usize) -> bool { + let body = &m[from..to]; + contains(body, b"panic!") + || contains(body, b".unwrap_err()") + || contains(body, b".expect_err(") + || macro_calls(m, from, to).iter().any(|c| is_assert_macro(&c.name)) +} + +/// `tests.rs`, `tests_*.rs`, `*_tests.rs`, files in a `tests` or `benches` folder, and +/// `crates/testkit`. +fn is_test_file(path: &str) -> bool { + let mut parts = path.split('/').rev(); + let file = parts.next().unwrap_or_default(); + file == "tests.rs" + || file.starts_with("tests_") + || file.ends_with("_tests.rs") + || parts.any(|d| d == "tests" || d == "benches") + || path.starts_with("crates/testkit/") +} + +/// The byte ranges of test code in a file: all of a test file, else each item under +/// `#[cfg(test)]` that has a body in the file, and each test function. +fn test_regions(path: &str, m: &[u8], tests: &[TestFn]) -> Vec<(usize, usize)> { + if is_test_file(path) { + return vec![(0, m.len())]; + } + let mut out: Vec<(usize, usize)> = tests.iter().map(|t| (t.attr, t.close)).collect(); + for at in words(m, b"cfg", 0, m.len()) { + let attr = skip_ws(m, at + "cfg".len()); + if !m[..at].ends_with(b"#[") || !m[attr..].starts_with(b"(test)]") { + continue; + } + // The item's body: the first `{` before any `;` (`mod tests;` has none here). + let after = attr + "(test)]".len(); + let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; + if let (b'{', Some(close)) = (m[open], matching(m, open)) { + out.push((at, close)); + } + } + out +} + +fn in_regions(regions: &[(usize, usize)], pos: usize) -> bool { + regions.iter().any(|&(from, to)| from <= pos && pos <= to) +} + +/// A function or macro in test code: its name (`name!` for a macro), whether it checks something +/// itself, and the names it calls. +type Def = (String, bool, Vec); + +/// For each crate of `files` ([`crate_of`]), the names of the functions and macros in its test +/// code, or in `crates/testkit`'s, that assert, panic or call one that does. +pub fn asserting_helpers(files: &[(String, String)]) -> HashMap> { + let mut defs: HashMap> = HashMap::new(); + for (path, src) in files { + let m = mask(src); + let regions = test_regions(path, &m, &tests_in(&m)); + let crate_defs = defs.entry(crate_of(path)).or_default(); + for at in words(&m, b"fn", 0, m.len()).into_iter().chain(words(&m, b"macro_rules", 0, m.len())) { + if in_regions(®ions, at) { + crate_defs.extend(definition(&m, at)); + } + } + } + let testkit = defs.get(TESTKIT).cloned().unwrap_or_default(); + defs.iter().map(|(krate, own)| (krate.clone(), checking(own.iter().chain(if krate == TESTKIT { &[][..] } else { &testkit[..] })))).collect() +} + +/// The crate whose test helpers every crate can call. +const TESTKIT: &str = "crates/testkit"; + +/// The names among `defs` that check something, directly or through another of `defs`. +fn checking<'a>(defs: impl Iterator + Clone) -> HashSet { + let mut known: HashSet = defs.clone().filter(|d| d.1).map(|d| d.0.clone()).collect(); + loop { + let more: Vec = + defs.clone().filter(|d| !known.contains(&d.0) && d.2.iter().any(|c| known.contains(c))).map(|d| d.0.clone()).collect(); + if more.is_empty() { + return known; + } + known.extend(more); + } +} + +/// The `fn` or `macro_rules!` at `at`. +fn definition(m: &[u8], at: usize) -> Option { + let is_macro = m[at..].starts_with(b"macro_rules"); + let mut start = skip_ws(m, at + if is_macro { "macro_rules".len() } else { 2 }); + if is_macro { + start = skip_ws(m, start + usize::from(m.get(start) == Some(&b'!'))); + } + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + if end == start { + return None; + } + let open = end + m[end..].iter().position(|&c| c == b'{' || c == b';')?; + if m[open] != b'{' { + return None; + } + let close = matching(m, open)?; + let name = String::from_utf8_lossy(&m[start..end]).into_owned(); + let called = calls(m, open, close).into_iter().filter(|(_, method)| !method).map(|(n, _)| n).collect(); + Some((if is_macro { format!("{name}!") } else { name }, checks_itself(m, open, close), called)) +} + +// ---- The rules ---- + +/// The source, its masked copy and its tests. +struct File<'a> { + path: &'a str, + src: &'a [u8], + m: Vec, + lines: Lines, + tests: Vec, + /// The test code ([`test_regions`]). + regions: Vec<(usize, usize)>, +} + +impl File<'_> { + fn hit(&self, at: usize, rule: Rule, test: &str, note: String) -> Hit { + let line = self.lines.of(at); + Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line } + } + + fn test_at(&self, pos: usize) -> &str { + self.tests.iter().find(|t| t.open <= pos && pos <= t.close).map_or("", |t| t.name.as_str()) + } + + /// The source of `from..to` without whitespace and comments between tokens; string and + /// character literals keep their text. + fn src_norm(&self, (from, to): (usize, usize)) -> String { + let mut out = Vec::with_capacity(to - from); + let mut in_literal = false; + for i in from..to { + let (s, m) = (self.src[i], self.m[i]); + if m == b'"' || (m == b'\'' && !in_literal && self.m.get(i + 1) == Some(&b' ')) { + in_literal = !in_literal; + } else if m == b'\'' && in_literal { + in_literal = false; + } + if in_literal || (m == s && !s.is_ascii_whitespace()) { + out.push(s); + } + } + String::from_utf8_lossy(&out).into_owned() + } +} + +/// Every hit in one file, exemptions applied. +pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { + let m = mask(src); + let tests = tests_in(&m); + let regions = test_regions(path, &m, &tests); + let file = File { path, src: src.as_bytes(), m, lines: Lines::new(src), tests, regions }; + let mut hits: Vec = file.tests.iter().flat_map(|t| test_hits(&file, t, ctx)).collect(); + hits.extend(ignore_hits(&file)); + hits.extend(sleep_hits(&file)); + hits.extend(reads_source_hits(&file)); + let allows = allows(src, &file.m); + hits.retain(|h| { + let first = if h.rule == Rule::AllUnguarded { h.line } else { h.first }; + !allows.iter().any(|&(line, rule)| rule == h.rule && line + 1 >= first && line <= h.line) + }); + hits.sort(); + hits +} + +/// `(line, rule)` of each exemption comment that names a rule and a reason. +/// A marker counts only inside a comment: masked (`m`) there, and kept when only literals are +/// masked. +fn allows(src: &str, m: &[u8]) -> Vec<(usize, Rule)> { + let literals = mask_with(src, false); + let lines = Lines::new(src); + src.match_indices(ALLOW) + .filter(|&(p, _)| m[p] == b' ' && literals[p] == b't') + .filter_map(|(p, _)| { + let rest = src[p + ALLOW.len()..].lines().next()?; + let mut words = rest.split_whitespace(); + let rule = Rule::from_id(words.next()?)?; + words.next().map(|_| (lines.of(p), rule)) + }) + .collect() +} + +/// What the rules read of one test. +struct View<'a> { + file: &'a File<'a>, + t: &'a TestFn, + asserts: Vec, + delegates: bool, + checks: bool, + should_panic: bool, +} + +fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { + let m = &file.m; + let asserts: Vec = macro_calls(m, t.open, t.close).into_iter().filter(|c| is_assert_macro(&c.name)).collect(); + let none = HashSet::new(); + let helpers = ctx.helpers.get(&crate_of(file.path)).unwrap_or(&none); + let delegates = calls(m, t.open, t.close) + .iter() + .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)); + let checks = checks_itself(m, t.open, t.close); + let should_panic = contains(&m[t.attr..t.fn_at], b"should_panic"); + let v = View { file, t, asserts, delegates, checks, should_panic }; + let mut hits = all_unguarded(&v); + hits.extend(self_compare(&v)); + hits.extend(early_returns(&v)); + hits.extend(env_gates(&v, ctx)); + hits.extend([only_weak(&v), exit_status_only(&v), no_assertion(&v)].into_iter().flatten()); + hits +} + +impl View<'_> { + fn hit(&self, at: usize, rule: Rule, note: String) -> Hit { + self.file.hit(at, rule, &self.t.name, note) + } + + /// A hit for the whole test, on its `fn` line. + fn whole(&self, rule: Rule, note: String) -> Hit { + let mut h = self.hit(self.t.fn_at, rule, note); + h.first = self.file.lines.of(self.t.attr); + h.last = self.file.lines.of(self.t.close); + h + } + + fn body(&self) -> &[u8] { + &self.file.m[self.t.open..self.t.close] + } + + /// The masked body with assertion failure-message arguments replaced by spaces. + fn body_without_messages(&self) -> Vec { + let mut body = self.body().to_vec(); + for a in &self.asserts { + for &(from, to) in a.args.iter().skip(guard_arg_count(&a.name)) { + blank(&mut body, from - self.t.open, to - self.t.open); + } + } + body + } + + /// The first argument of an assertion, masked, without whitespace. + fn first_arg(&self, a: &MacroCall) -> String { + a.args.first().map(|&(f, t)| norm(&self.file.m[f..t])).unwrap_or_default() + } +} + +const PLAIN_ASSERTS: &[&str] = &["assert", "debug_assert", "prop_assert"]; + +fn all_unguarded(v: &View) -> Vec { + let mut body = v.body_without_messages(); + strip_all_predicates(&mut body); + let checked = v.asserts.iter().any(|a| { + a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { + let arg = norm(&body[from - v.t.open..to - v.t.open]); + [".len()", ".is_empty()", ".count()", ".first()", ".any(", ".next()", ".last()"].iter().any(|g| arg.contains(g)) + }) + }); + if checked || first_item_guard(&body) { + return vec![]; + } + v.asserts + .iter() + .filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && unguarded_all(&v.first_arg(a), &v.file.m[v.t.open..a.at])) + .map(|a| { + let mut h = v.hit(a.at, Rule::AllUnguarded, format!("{}!(…all(…)) with no length or emptiness check in the test", a.name)); + h.first = v.file.lines.of(v.t.attr); + h.last = v.file.lines.of(v.t.close); + h + }) + .collect() +} + +/// The number of condition or compared operands in a standard assertion macro. +fn guard_arg_count(name: &str) -> usize { + match name { + "assert" | "debug_assert" | "prop_assert" => 1, + "assert_eq" | "assert_ne" | "debug_assert_eq" | "debug_assert_ne" | "prop_assert_eq" | "prop_assert_ne" => 2, + _ => 0, + } +} + +/// Blanks `.all(…)` predicates so their checks do not guard the collection. +fn strip_all_predicates(body: &mut [u8]) { + for at in words(body, b"all", 0, body.len()) { + let method = body[..at].trim_ascii_end().ends_with(b"."); + let open = skip_ws(body, at + 3); + let Some(close) = (method && body.get(open) == Some(&b'(')).then(|| matching(body, open)).flatten() else { continue }; + blank(body, at, close + 1); + } +} + +/// Whether test code accesses a first item in a way that fails on an empty collection. +fn first_item_guard(body: &[u8]) -> bool { + let compact = norm(body); + let unwrapped = [".first().unwrap()", ".first().expect(", ".next().unwrap()", ".next().expect("]; + let indexed = compact.match_indices("[0]").any(|(at, _)| !on_array_literal(&compact[..at + 3])); + indexed || unwrapped.iter().any(|g| compact.contains(g)) || panicking_first_binding(body) +} + +/// Whether a `let Some(…) = ….first() else { panic!(…) }` binding checks for an item. +fn panicking_first_binding(body: &[u8]) -> bool { + words(body, b"let", 0, body.len()).into_iter().any(|at| { + let rest = &body[at + 3..]; + let Some(otherwise) = words(rest, b"else", 0, rest.len()).first().copied() else { return false }; + let binding = norm(&rest[..otherwise]); + let Some(close) = binding.strip_prefix("Some(").and_then(|_| matching(binding.as_bytes(), 4)) else { return false }; + let Some(value) = binding[close + 1..].strip_prefix('=') else { return false }; + let first = value.ends_with(".first()") || value.ends_with(".next()"); + first && !value.contains([';', '{', '}']) && norm(&rest[otherwise + 4..]).starts_with("{panic!(") + }) +} + +/// Whether a (masked, whitespace-free) condition holds an `.all(…)` that an empty collection would +/// pass by mistake. Left out: a negated result, a closure that says no item matches (whole +/// negations or `!=` comparisons joined only by `&&`), and a non-empty array literal or a local +/// name bound to or previously compared equal to one. +fn unguarded_all(cond: &str, body: &[u8]) -> bool { + all_with_polarity(cond, true, body) +} + +/// Tracks negation through boolean operands and comparisons with `false`. +fn all_with_polarity(cond: &str, positive: bool, body: &[u8]) -> bool { + if cond.starts_with('(') && matching(cond.as_bytes(), 0) == Some(cond.len() - 1) { + return all_with_polarity(&cond[1..cond.len() - 1], positive, body); + } + if let Some(at) = boolean_split(cond) { + return all_with_polarity(&cond[..at], positive, body) || all_with_polarity(&cond[at + 2..], positive, body); + } + if let Some(expr) = cond.strip_suffix("==false").or_else(|| cond.strip_prefix("false==")) { + return all_with_polarity(expr, !positive, body); + } + if let Some(expr) = cond.strip_prefix('!') { + return all_with_polarity(expr, !positive, body); + } + positive && positive_all(cond, body) +} + +/// Finds a boolean operator outside parentheses, brackets and braces. +fn boolean_split(cond: &str) -> Option { + let b = cond.as_bytes(); + let mut at = 0; + while at < b.len() { + if b[at..].starts_with(b"&&") || b[at..].starts_with(b"||") { + return Some(at); + } + at = if matches!(b[at], b'(' | b'[' | b'{') { matching(b, at)? + 1 } else { at + 1 }; + } + None +} + +fn positive_all(cond: &str, test_body: &[u8]) -> bool { + cond.match_indices(".all(").any(|(i, _)| { + let rest = &cond[i + ".all(".len()..]; + let arg = &rest[..arg_end(rest)]; + let body = arg.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(arg, |(_, body)| body); + let none_match = not_equal_conjunction(body); + !none_match && !on_array_literal(&cond[..i]) && !on_bound_array(&cond[..i], test_body) && !on_equal_array(&cond[..i], test_body) + }) +} + +/// Whether every boolean operand is a whole negation or `!=` comparison joined only by `&&`. +fn not_equal_conjunction(body: &str) -> bool { + if body.starts_with('(') && matching(body.as_bytes(), 0) == Some(body.len() - 1) { + return not_equal_conjunction(&body[1..body.len() - 1]); + } + if let Some(at) = boolean_split(body) { + return body[at..].starts_with("&&") && not_equal_conjunction(&body[..at]) && not_equal_conjunction(&body[at + 2..]); + } + if whole_negation(body) { + return true; + } + let (mut at, mut comparisons) = (0, 0); + let b = body.as_bytes(); + while at < b.len() { + if b[at..].starts_with(b"!=") { + comparisons += 1; + at += 2; + } else if matches!(b[at], b'=' | b'<' | b'>' | b'&' | b'|') { + return false; + } else if matches!(b[at], b'(' | b'[' | b'{') { + let Some(close) = matching(b, at) else { return false }; + at = close + 1; + } else { + at += 1; + } + } + comparisons == 1 +} + +/// Whether `!` negates the whole operand rather than one side of a binary expression. +fn whole_negation(body: &str) -> bool { + let Some(rest) = body.strip_prefix('!') else { return false }; + let rest = rest.trim_start_matches(['!', '*', '&']); + let b = rest.as_bytes(); + let mut at = 0; + while at < b.len() { + if matches!(b[at], b'=' | b'<' | b'>' | b'&' | b'|' | b'+' | b'-' | b'*' | b'/' | b'%' | b'^') { + return false; + } + at = if matches!(b[at], b'(' | b'[' | b'{') { + let Some(close) = matching(b, at) else { return false }; + close + 1 + } else { + at + 1 + }; + } + !rest.is_empty() +} + +/// Whether an earlier equality assertion compares this plain local receiver with a non-empty literal. +fn on_equal_array(receiver: &str, body: &[u8]) -> bool { + let name = array_receiver(receiver); + if name.is_empty() || name.as_bytes()[0].is_ascii_digit() || !name.bytes().all(is_ident) { + return false; + } + macro_calls(body, 0, body.len()).iter().any(|a| { + if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) { + return false; + } + let Some(&(lf, lt)) = a.args.first() else { return false }; + let Some(&(rf, rt)) = a.args.get(1) else { return false }; + let (left, right) = (norm(&body[lf..lt]), norm(&body[rf..rt])); + (collection_operand(&left) == name && non_empty_literal(&right)) || (collection_operand(&right) == name && non_empty_literal(&left)) + }) +} + +/// Removes one borrow and a slice view from a compared operand. +fn collection_operand(operand: &str) -> &str { + let operand = operand.strip_prefix('&').unwrap_or(operand); + operand.strip_suffix(".as_slice()").or_else(|| operand.strip_suffix("[..]")).unwrap_or(operand) +} + +/// Whether the whole operand is a non-empty array literal or `vec![…]`. +fn non_empty_literal(operand: &str) -> bool { + let b = operand.strip_prefix("vec!").unwrap_or(operand).as_bytes(); + b.first() == Some(&b'[') && matching(b, 0) == Some(b.len() - 1) && non_empty_array(&b[1..b.len() - 1]) +} + +/// The length of a call's arguments in `rest`, the text after its `(`: up to its closing bracket. +fn arg_end(rest: &str) -> usize { + let mut depth = 0i32; + rest.bytes() + .position(|c| { + depth += match c { + b'(' | b'[' | b'{' => 1, + b')' | b']' | b'}' => -1, + _ => 0, + }; + depth < 0 + }) + .unwrap_or(rest.len()) +} + +/// Whether `receiver` (the text before `.all(`) ends with a non-empty array literal, through `.iter()` or +/// `.into_iter()`. +fn on_array_literal(receiver: &str) -> bool { + let r = array_receiver(receiver); + let b = r.as_bytes(); + if b.last() != Some(&b']') { + return false; + } + let mut depth = 0usize; + for (j, &c) in b.iter().enumerate().rev() { + match c { + b']' => depth += 1, + b'[' => { + depth = depth.saturating_sub(1); + if depth == 0 { + let literal = !j.checked_sub(1).and_then(|k| b.get(k)).is_some_and(|&p| is_ident(p) || matches!(p, b')' | b']' | b'.')); + return literal && non_empty_array(&b[j + 1..b.len() - 1]); + } + } + _ => {} + } + } + false +} + +/// Removes the iterator method from an array receiver. +fn array_receiver(receiver: &str) -> &str { + receiver.strip_suffix(".iter()").or_else(|| receiver.strip_suffix(".into_iter()")).unwrap_or(receiver) +} + +/// Whether a plain local receiver's latest preceding binding initializes a non-empty array. +fn on_bound_array(receiver: &str, body: &[u8]) -> bool { + let name = array_receiver(receiver).as_bytes(); + if name.is_empty() || name[0].is_ascii_digit() || !name.iter().copied().all(is_ident) { + return false; + } + words(body, b"let", 0, body.len()).into_iter().rev().find_map(|at| array_binding(&body[at + 3..], name)).unwrap_or(false) +} + +/// Checks a named binding, allowing `mut` and an array type annotation. +fn array_binding(mut rest: &[u8], name: &[u8]) -> Option { + rest = rest.trim_ascii_start(); + if rest.starts_with(b"mut") && rest.get(3).is_some_and(u8::is_ascii_whitespace) { + rest = rest[3..].trim_ascii_start(); + } + let end = rest.iter().copied().take_while(|&c| is_ident(c)).count(); + if &rest[..end] != name { + return None; + } + rest = rest[end..].trim_ascii_start(); + if let Some(annotation) = rest.strip_prefix(b":") { + let annotation = annotation.trim_ascii_start(); + let close = (annotation.first() == Some(&b'[')).then(|| matching(annotation, 0)).flatten(); + let Some(close) = close else { return Some(false) }; + rest = annotation[close + 1..].trim_ascii_start(); + } + Some(rest.strip_prefix(b"=").is_some_and(array_initializer)) +} + +/// Whether an initializer is a non-empty array literal, optionally followed by one `.map(…)`. +fn array_initializer(rest: &[u8]) -> bool { + let rest = rest.trim_ascii_start(); + let Some(close) = (rest.first() == Some(&b'[')).then(|| matching(rest, 0)).flatten() else { return false }; + if !non_empty_array(&rest[1..close]) { + return false; + } + let tail = rest[close + 1..].trim_ascii_start(); + if tail.starts_with(b";") { + return true; + } + let compact = norm(tail); + if !compact.starts_with(".map(") { + return false; + } + let Some(close) = matching(compact.as_bytes(), 4) else { return false }; + compact[close + 1..].starts_with(';') +} + +/// Whether an array's masked contents have an element and, for repetition, a positive literal count. +fn non_empty_array(contents: &[u8]) -> bool { + let mut at = 0; + while at < contents.len() { + match contents[at] { + b';' => return norm(&contents[at + 1..]).parse::().is_ok_and(|count| count > 0), + b'(' | b'[' | b'{' => { + let Some(close) = matching(contents, at) else { return false }; + at = close + 1; + } + _ => at += 1, + } + } + !contents.trim_ascii().is_empty() +} + +/// Whether an assertion's (masked, whitespace-free) condition only says that there is a value. +fn is_weak(cond: &str) -> bool { + let (negated, expr) = match cond.strip_prefix('!') { + Some(rest) => (true, rest), + None => (false, cond), + }; + let plain = |rest: &str| !["&&", "||", "==", "!=", "<", ">"].iter().any(|op| rest.contains(op)); + let suffix = |s: &str| expr.strip_suffix(s).is_some_and(plain); + if negated { + return suffix(".is_empty()"); + } + suffix(".is_ok()") || suffix(".is_some()") || suffix(".len()>0") || suffix(".len()!=0") || suffix(".len()>=1") +} + +fn only_weak(v: &View) -> Option { + let all_weak = v.asserts.iter().all(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && is_weak(&v.first_arg(a))); + let other = contains(v.body(), b"panic!") || contains(v.body(), b".unwrap_err()") || contains(v.body(), b".expect_err("); + if v.asserts.is_empty() || !all_weak || other || v.delegates || v.should_panic { + return None; + } + Some(v.whole(Rule::OnlyWeak, format!("its {} assertion(s) only check is_ok/is_some/non-empty", v.asserts.len()))) +} + +fn self_compare(v: &View) -> Vec { + v.asserts + .iter() + .filter(|a| a.name.ends_with("_eq") || a.name.ends_with("_ne")) + .filter_map(|a| { + let right = *a.args.get(1)?; + let (l, r) = (v.file.src_norm(*a.args.first()?), v.file.src_norm(right)); + let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&')); + let calls_with_args = l.replace("()", "").contains(['(', '!']); + (l == r && !l.is_empty() && !calls_with_args).then(|| { + let mut h = v.hit(a.at, Rule::SelfCompare, format!("{}! compares `{l}` with itself", a.name)); + let end = right.0 + v.file.m[right.0..right.1].trim_ascii_end().len(); + h.last = v.file.lines.of(end.saturating_sub(1)); + h + }) + }) + .collect() +} + +fn exit_status_only(v: &View) -> Option { + let mut body = norm(&v.body_without_messages()).into_bytes(); + let runs = contains(&body, b"Command::new") || contains(&body, b".output()") || contains(&body, b".status()"); + strip_stream_configuration(&mut body); + let reads = + ["stdout", "stderr", "fs::read", "read_to_string", "from_slice", "from_str", "contains("].iter().any(|w| contains(&body, w.as_bytes())); + let status_only = |a: &MacroCall| { + a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { + let c = norm(&v.file.m[from..to]); + c.contains(".success()") || c.contains(".code()") + }) + }; + if !runs || reads || v.asserts.is_empty() || !v.asserts.iter().all(status_only) || v.delegates { + return None; + } + Some(v.whole(Rule::ExitStatusOnly, "runs a process and checks only its exit status".into())) +} + +/// Blanks stream method names that configure a process with `Stdio` in whitespace-free text. +fn strip_stream_configuration(body: &mut [u8]) { + for stream in ["stdout", "stderr", "stdin"] { + for at in words(body, stream.as_bytes(), 0, body.len()) { + let rest = &body[at + stream.len()..]; + let config = rest.starts_with(b"(Stdio::") || rest.starts_with(b"(std::process::Stdio::"); + if body[..at].ends_with(b".") && config { + blank(body, at, at + stream.len()); + } + } + } +} + +fn no_assertion(v: &View) -> Option { + if v.checks || v.delegates || v.should_panic { + return None; + } + Some(v.whole(Rule::NoAssertion, "no assertion and no asserting helper".into())) +} + +/// Guards that mark a skip for a missing resource or another platform, or a test that runs itself +/// in a child process, matched case-sensitively on the guard without whitespace. +const SKIP_GUARDS: &[&str] = &[ + "in_own_process", + "OWN_PROCESS", + "_TEST_CHILD", + "current_exe()", + "skip_without_craft_fonts", + "CRAFT_FONTS", + "japanese_fonts", + "craft_fonts", + "env::var", + "cfg!(", + "target_os", + "geteuid", + "Command::new", + "File::open", + "fs::read", + "read_dir(", + ".exists()", + "which(", +]; + +/// The same, matched without regard to case. +const SKIP_GUARDS_ANY_CASE: &[&str] = &[ + "installed_family", + "kufi", + "library/fonts", + "default_font(", + "arabic_face", + "arabic_test_face", + "devanagari_test_face", + "joiner_test_faces", + "mark_text(", + "arabic_style", + "has_family", + "variable_font", + "fontdb", + ".face(", + "covers(", + "thai", + "cjk", + "corpus", + "suite_dir", + "json2_file", + "read_fixture", + "samples(", + "pinned(", + "platform()", + "is_mac", + "/system/library", +]; + +fn early_returns(v: &View) -> Vec { + let (m, t) = (&v.file.m, v.t); + words(m, b"return", t.open, t.close) + .into_iter() + .filter_map(|at| { + let end = bare_return_end(m, at + "return".len())?; + let rest_empty = m[end..t.close].iter().all(|c| c.is_ascii_whitespace() || matches!(c, b';' | b'}')); + if rest_empty || nested(m, t.open, at) || skip_guard(v.file, t.open, at, end) { + return None; + } + Some(v.hit(at, Rule::EarlyReturn, "returns early on a value from the code under test".into())) + }) + .collect() +} + +/// The end of a bare `return` (`return;`, `return }`, `return Ok(());`) whose keyword ends at `i`. +fn bare_return_end(m: &[u8], i: usize) -> Option { + let mut j = skip_ws(m, i); + if m[j..].starts_with(b"Ok") { + j += 2; + for c in *b"(())" { + j = skip_ws(m, j); + if m.get(j) != Some(&c) { + return None; + } + j += 1; + } + j = skip_ws(m, j); + } + match m.get(j)? { + b';' => Some(j + 1), + b'}' | b',' => Some(j), + _ => None, + } +} + +/// Whether `pos` is inside a closure or a nested function in the body opened at `open`. +fn nested(m: &[u8], open: usize, pos: usize) -> bool { + let mut stack: Vec = vec![]; + for i in open..pos { + match m[i] { + b'{' => stack.push(i > open && opens_closure_or_fn(m, open, i)), + b'}' => { + stack.pop(); + } + _ => {} + } + } + stack.contains(&true) +} + +fn opens_closure_or_fn(m: &[u8], open: usize, brace: usize) -> bool { + let from = brace.saturating_sub(160).max(open + 1); + let head = &m[from..brace]; + let start = head.iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let head = String::from_utf8_lossy(&head[start..]).into_owned(); + let head = head.trim_end(); + let closure = head.ends_with('|') || head.rfind("->").is_some_and(|p| head[..p].trim_end().ends_with('|')); + closure || !words(head.as_bytes(), b"fn", 0, head.len()).is_empty() +} + +/// Whether the return at `at..end` is not a silent skip on a value: the block it ends asserts +/// first; a comment or a printed note from the start of its statement to the end of its line says +/// why it returns; or its guard skips for a resource, a platform or a child process. +fn skip_guard(file: &File, open: usize, at: usize, end: usize) -> bool { + let m = &file.m; + let block = m[open..at].iter().rposition(|&c| c == b'{').map_or(open, |p| p + open); + let stmt = m[open..block].iter().rposition(|&c| c == b';' || c == b'}').map_or(open, |p| p + open); + let line_end = find(m, b"\n", end).unwrap_or(m.len()); + let asserted = macro_calls(m, block, at).iter().any(|c| is_assert_macro(&c.name)); + let printed = macro_calls(m, stmt, at).iter().any(|c| c.name.ends_with("print") || c.name.ends_with("println")); + let commented = (stmt..line_end).any(|i| file.src[i..].starts_with(b"//") && m[i] == b' '); + if asserted || printed || commented { + return true; + } + let guard = norm(&file.src[stmt..end]); + let lower = guard.to_ascii_lowercase(); + let wide = &file.src[stmt.saturating_sub(250).max(open)..end]; + SKIP_GUARDS.iter().any(|g| guard.contains(g)) + || SKIP_GUARDS_ANY_CASE.iter().any(|g| lower.contains(g)) + || (lower.contains("fs::write(") && lower.contains(".is_err()")) + || ["in_own_process", "OWN_PROCESS", "_TEST_CHILD", "current_exe()"].iter().any(|g| contains(wide, g.as_bytes())) + || !words(wide, b"CHILD", 0, wide.len()).is_empty() +} + +fn env_gates(v: &View, ctx: &Ctx) -> Vec { + let (m, src, t) = (&v.file.m, v.file.src, v.t); + let mut out = vec![]; + for at in words(m, b"var", t.open, t.close).into_iter().chain(words(m, b"var_os", t.open, t.close)) { + if !m[..at].ends_with(b"env::") { + continue; + } + let Some(name) = env_name(m, src, at) else { continue }; + if ctx.ci_env.contains(&name) || set_by_system(&name) { + continue; + } + // The whole file is masked and searched only for a name that CI and the system leave unset. + let file = norm(&mask_comments(&String::from_utf8_lossy(src))); + let set_here = file.contains(&format!(".env(\"{name}\"")) + || file.contains(&format!("=\"{name}\";")) + || file.match_indices(&format!("set_var(\"{name}\"")).any(|(at, _)| at == 0 || !is_ident(file.as_bytes()[at - 1])); + if !set_here { + out.push(v.hit(at, Rule::EnvGateUnset, format!("reads {name}, which no CI leg sets"))); + } + } + out +} + +/// The literal name in `env::var("NAME")` whose `var` is at `at`. +fn env_name(m: &[u8], src: &[u8], at: usize) -> Option { + let open = skip_ws(m, at + m[at..].iter().take_while(|&&c| is_ident(c)).count()); + if m.get(open) != Some(&b'(') { + return None; + } + let quote = skip_ws(m, open + 1); + if m.get(quote) != Some(&b'"') { + return None; + } + let end = string_end(src, quote + 1).saturating_sub(1); + let name = std::str::from_utf8(&src[quote + 1..end]).ok()?; + (!name.is_empty() && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')).then(|| name.to_owned()) +} + +fn ignore_hits(file: &File) -> Vec { + let m = &file.m; + let mut out = vec![]; + for at in words(m, b"ignore", 0, m.len()) { + if !m[..at].ends_with(b"#[") { + continue; + } + let j = skip_ws(m, at + "ignore".len()); + let reason = match m.get(j) { + Some(b'=') => { + let q = skip_ws(m, j + 1); + ignore_reason(&file.src[q..]).is_some_and(|body| body.iter().any(|c| !c.is_ascii_whitespace())) + } + _ => false, + }; + if !reason { + let test = file.tests.iter().find(|t| t.fn_at > at).map_or("", |t| t.name.as_str()); + out.push(file.hit(at - 2, Rule::IgnoreWithoutReason, test, "#[ignore] gives no reason".into())); + } + } + out +} + +/// The body of an ordinary or raw string literal used as an ignore reason. +fn ignore_reason(src: &[u8]) -> Option<&[u8]> { + if src.first() == Some(&b'"') { + return src.get(1..string_end(src, 1).saturating_sub(1)); + } + let raw = src.strip_prefix(b"r")?; + let hashes = raw.iter().take_while(|&&c| c == b'#').count(); + if raw.get(hashes) != Some(&b'"') { + return None; + } + let body = hashes + 2; + let close: Vec = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let end = find(src, &close, body)?; + src.get(body..end) +} + +fn sleep_hits(file: &File) -> Vec { + let m = &file.m; + words(m, b"sleep", 0, m.len()) + .into_iter() + .filter(|&at| { + if !in_regions(&file.regions, at) { + return false; + } + let before = m[..at].iter().rposition(|c| !c.is_ascii_whitespace()); + let method = before.is_some_and(|b| m[b] == b'.'); + let definition = m[..at].trim_ascii_end().ends_with(b"fn"); + !method && !definition && m.get(skip_ws(m, at + "sleep".len())) == Some(&b'(') + }) + .map(|at| file.hit(at, Rule::Sleep, file.test_at(at), "sleeps in test code".into())) + .collect() +} + +fn reads_source_hits(file: &File) -> Vec { + if SOURCE_AUDITS.contains(&file.path) { + return vec![]; + } + let m = &file.m; + let mut out = vec![]; + for (word, note) in [(&b"include_str"[..], "includes a .rs file as text"), (&b"ends_with"[..], "keeps files ending in .rs")] { + for at in words(m, word, 0, m.len()).into_iter().filter(|&at| in_regions(&file.regions, at)) { + let open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); + let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; + let arg = norm(&file.src[open + 1..close]); + let rs = if word == b"ends_with" { arg == "\".rs\"" } else { arg.ends_with(".rs\"") }; + if rs { + out.push(file.hit(at, Rule::ReadsSource, file.test_at(at), note.into())); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ctx() -> Ctx { + Ctx { helpers: HashMap::new(), ci_env: ["SET_IN_CI".to_owned()].into_iter().collect() } + } + + /// The rule ids of `src`'s hits, as `(line, rule)`. + fn hits(src: &str) -> Vec<(usize, &'static str)> { + hits_in("crates/x/src/tests.rs", src, &ctx()) + } + + fn hits_in(path: &str, src: &str, ctx: &Ctx) -> Vec<(usize, &'static str)> { + lint_file(path, src, ctx).into_iter().map(|h| (h.line, h.rule.id())).collect() + } + + #[test] + fn all_needs_a_non_empty_guard() { + let bad = "#[test]\nfn t() {\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(bad), [(4, "all-unguarded")]); + let good = "#[test]\nfn t() {\n let xs = f();\n assert_eq!(xs.len(), 3);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(good), []); + let inner = "#[test]\nfn t() {\n assert!(rows().iter().all(|r| r.len() == 3));\n}\n"; + assert_eq!(hits(inner), [(3, "all-unguarded")], "a length inside the predicate is about each item"); + let none = "#[test]\nfn t() {\n assert!(warnings().iter().all(|w| !w.contains(\"lost\")), \"no warning\");\n}\n"; + assert_eq!(hits(none), [], "all(|w| !…) says that no item matches"); + let other = "#[test]\nfn t() {\n assert!(listed().iter().all(|e| e[\"id\"] != id));\n assert!([0, 4, 20].iter().all(|&i| glow[i].a() == 0));\n}\n"; + assert_eq!(hits(other), [], "one != comparison, and an array literal"); + let indexed = "#[test]\nfn t() {\n assert!(rows()[2].iter().all(|r| r.ok && r.n != 0));\n assert!(f().iter().all(|x| x.0 != 1 && x.1 != 2));\n}\n"; + assert_eq!(hits(indexed), [(3, "all-unguarded")]); + let mixed = "#[test]\nfn t() {\n assert!(f().iter().all(|x| x.0 != 1 && x.1 > 2));\n}\n"; + assert_eq!(hits(mixed), [(3, "all-unguarded")]); + } + + #[test] + fn all_equality_guards_match_each_receiver() { + for assertion in ["assert_eq", "debug_assert_eq", "prop_assert_eq"] { + for operand in ["xs", "&xs", "xs.as_slice()", "&xs.as_slice()", "xs[..]", "&xs[..]"] { + for literal in ["[1]", "[1, 2,]", "[1; 2]", "vec![1, 2]", "vec![1; 2]", "[\"[;]\", name]"] { + for (left, right) in [(operand, literal), (literal, operand)] { + let src = format!( + "#[test]\nfn t() {{\n {assertion}!({left}, {right}, \"items\");\n assert!(xs.iter().all(|x| valid(x)));\n assert!(ys.iter().all(|x| valid(x)));\n}}\n" + ); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{assertion}!({left}, {right})"); + let combined = src.replace("valid(x)));\n assert!(ys", "valid(x)) && ys"); + assert_eq!(hits(&combined), [(4, "all-unguarded")], "another receiver in the same condition"); + } + } + } + } + } + + #[test] + fn all_equality_guards_require_non_empty_literals() { + for expected in ["[]", "[1; 0]", "vec![]", "vec![1; 0]", "expected", "items()", "[1].map(f)", "vec![1].clone()"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!(xs, {expected});\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{expected}"); + } + for operand in ["ys", "xs_other", "other.xs", "other::xs", "xs()", "xs.clone()", "xs[1..]", "&&xs"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({operand}, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{operand}"); + } + } + + #[test] + fn all_equality_guards_require_earlier_compared_operands_in_the_test() { + for assertion in ["assert_ne", "debug_assert_ne", "prop_assert_ne"] { + let src = format!("#[test]\nfn t() {{\n {assertion}!(xs, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{assertion}"); + } + let later = "#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n assert_eq!(xs, [1]);\n}\n"; + assert_eq!(hits(later), [(3, "all-unguarded")]); + let outside = "fn helper() { assert_eq!(xs, [1]); }\n#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(outside), [(4, "all-unguarded")]); + let message = "#[test]\nfn t() {\n assert_eq!(a, b, \"items {:?} {:?}\", xs, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(message), [(4, "all-unguarded")]); + } + + #[test] + fn all_skips_conjunctions_of_not_equal_comparisons() { + for predicate in [ + "|(id, _)| id != \"action.batch\" && id != \"flattener.preview\"", + "|x| x.0 != 1 && x.1 != 2", + "|x| x != 1 && x != 2 && x != 3", + "|x| (x != 1) && ((x != 2) && x != 3)", + "|x| value(x) != expected(1, 2) && *x != 3", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(names.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [], "{predicate}"); + let mixed = src.replace("));\n", ") && ys.iter().all(|y| valid(y)));\n"); + assert_eq!(hits(&mixed), [(3, "all-unguarded")], "another positive predicate beside {predicate}"); + } + } + + #[test] + fn all_reports_conjunctions_with_other_predicates() { + for predicate in [ + "|x| x != 1 && x == 2", + "|x| x != 1 && x < 2", + "|x| x.0 != 1 && x.1 > 2", + "|x| x != 1 && valid(x)", + "|x| valid(x) && x != 1", + "|x| x != 1 || x != 2", + "|x| x != 1 && x != 2 || x != 3", + "|x| x != 1 && (x != 2 || x != 3)", + "|x| (x != 1 && x > 2) && x != 3", + "|x| valid(x != 1) && x != 2", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(names.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [(3, "all-unguarded")], "{predicate}"); + } + } + + #[test] + fn all_skips_only_whole_negations_and_not_equal_conjunctions() { + for predicate in [ + "|x| !x.contains(\"lost\")", + "|x| !blocked!(x)", + "|x| !(blocked(x) && invalid(x))", + "|x| !a(x) && !b(x)", + "|x| !a(x) && x != 1", + "|x| x != 1 && (!a(x) && !(b(x)))", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(xs.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [], "{predicate}"); + } + for predicate in [ + "|x| !blocked(x) && valid(x)", + "|x| valid(x) && !blocked(x)", + "|x| !a(x) || b(x)", + "|x| !a(x) == b(x)", + "|x| (!a(x) == b(x)) && x != 1", + "|x| !a(x) && (!b(x) || c(x))", + "|x| !a(x) ^ b(x)", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(xs.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [(3, "all-unguarded")], "{predicate}"); + } + } + + #[test] + fn all_skips_locally_bound_non_empty_arrays() { + for binding in [ + "let xs = [1, 2];", + "let mut xs = [1, 2];", + "let xs: [u8; 2] = [1, 2];", + "let mut xs: [u8; 2] = [1, 2];", + "let xs = [1; 2];", + "let xs = [[1, 2], [3, 4]];", + "let xs = [\"[\", \";\", \"bad ] brackets [\"].map(|s| s.trim());", + "let xs = [1, 2].map(|x| { let pair = [x, x]; pair });", + "let xs /* items */ : [u8; 2] = [1, 2] . map (|x| x + 1);", + ] { + for method in ["iter", "into_iter"] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.{method}().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding} through {method}"); + let mixed = src.replace("valid(x)))", "valid(x)) && ys.iter().all(|y| valid(y)))"); + assert_eq!(hits(&mixed), [(4, "all-unguarded")], "another collection beside {binding}"); + } + } + } + + #[test] + fn all_reports_empty_arrays_and_other_initializers() { + for value in [ + "[]", + "[1; 0]", + "[1; 0].map(|x| x + 1)", + "vec![1, 2]", + "items()", + "items().collect()", + "[1, 2].into_iter().collect()", + "[1, 2].map(|x| x + 1).into_iter().collect()", + "[1, 2].map(|x| x + 1).map(|x| x + 1)", + ] { + for binding in [format!("let xs = {value};"), format!("let mut xs = {value};"), format!("let xs: [u8; 0] = {value};")] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{binding}"); + } + } + } + + #[test] + fn all_array_bindings_match_only_plain_preceding_local_names() { + for (binding, receiver) in [ + ("let xs_other = [1, 2];", "xs"), + ("let other_xs = [1, 2];", "xs"), + ("let (xs, ys) = ([1, 2], items());", "xs"), + ("let xs = [1, 2]; let xs = items();", "xs"), + ("let xs = [1, 2];", "other.xs"), + ("let xs = [1, 2];", "other::xs"), + ("let xs = [1, 2];", "xs()"), + ] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!({receiver}.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{binding} with {receiver}"); + } + let later = "#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n let xs = [1, 2];\n}\n"; + assert_eq!(hits(later), [(3, "all-unguarded")], "a later binding does not initialize the receiver"); + let outside = "fn helper() { let xs = [1, 2]; }\n#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(outside), [(4, "all-unguarded")], "a binding outside the test does not count"); + } + + #[test] + fn all_direct_array_literals_must_be_non_empty() { + for method in ["iter", "into_iter"] { + for array in ["[]", "[1; 0]", "[items(); 0]", "[1; 0usize]"] { + let src = format!("#[test]\nfn t() {{\n assert!({array}.{method}().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(3, "all-unguarded")], "{array} through {method}"); + } + for array in ["[1]", "[1, 2]", "[1; 2]", "[[1; 0]]", "[\"[;]\"]"] { + let src = format!("#[test]\nfn t() {{\n assert!({array}.{method}().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{array} through {method}"); + } + } + } + + #[test] + fn all_skips_mapped_arrays_of_named_rectangles() { + for (name, labels, message) in [ + ("chips", "[\"Color (, or Shift+,)\", \"Gradient (. or Shift+.)\", \"None (/)\"]", "one line"), + ("modes", "[\"Draw Normal (Shift+D)\", \"Draw Behind (Shift+D)\", \"Draw Inside (Shift+D)\"]", "side by side"), + ] { + let src = format!( + "#[test]\nfn t() {{\n let {name} = {labels}.map(|label| named_rect(&nodes, label));\n assert!({name}.iter().all(|r| (r.top() - {name}[0].top()).abs() < 0.5), \"{message}: {{{name}:?}}\");\n}}\n" + ); + assert_eq!(hits(&src), [], "{name}"); + let empty = src.replace(labels, "[]"); + assert_eq!(hits(&empty), [(4, "all-unguarded")], "an empty {name} still passes vacuously"); + } + } + + #[test] + fn all_respects_condition_polarity() { + for condition in [ + "!xs.iter().all(|x| *x > 0)", + "!(xs.iter().all(|x| *x > 0))", + "ready() && !xs.iter().all(|x| *x > 0)", + "!xs.iter().all(|x| *x > 0) && ready()", + "xs.iter().all(|x| *x > 0) == false", + "ready() && (xs.iter().all(|x| *x > 0) == false)", + "false == xs.iter().all(|x| *x > 0)", + ] { + let good = format!("#[test]\nfn t() {{\n assert!({condition});\n}}\n"); + assert_eq!(hits(&good), [], "{condition}"); + let bad = format!("#[test]\nfn t() {{\n assert!(({condition}) && ys.iter().all(|y| *y > 0));\n}}\n"); + assert_eq!(hits(&bad), [(3, "all-unguarded")], "a positive operand beside {condition}"); + } + } + + #[test] + fn all_reports_positive_boolean_operands() { + for condition in [ + "xs.iter().all(|x| *x > 0)", + "ready() && xs.iter().all(|x| *x > 0)", + "xs.iter().all(|x| *x > 0) && ready()", + "ready() || xs.iter().all(|x| *x > 0)", + "xs.iter().all(|x| *x > 0) || ready()", + "!!xs.iter().all(|x| *x > 0)", + "!xs.iter().all(|x| *x > 0) == false", + "!(xs.iter().all(|x| *x > 0) == false)", + ] { + let bad = format!("#[test]\nfn t() {{\n assert!({condition});\n}}\n"); + assert_eq!(hits(&bad), [(3, "all-unguarded")], "{condition}"); + let good = bad.replace(" assert!", " assert_eq!(xs.len(), 3);\n assert!"); + assert_eq!(hits(&good), [], "a length check guards {condition}"); + } + } + + #[test] + fn all_guards_use_assertion_operands_and_skip_messages() { + for name in ["assert", "debug_assert", "prop_assert"] { + let good = format!("#[test]\nfn t() {{\n {name}!(xs.len() > 0);\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "{name} condition"); + let bad = format!("#[test]\nfn t() {{\n {name}!(ready(), \"length {{}}\", xs.len());\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&bad), [(4, "all-unguarded")], "{name} message"); + } + for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { + for (left, right) in [("xs.len()", "3"), ("3", "xs.len()")] { + let good = format!("#[test]\nfn t() {{\n {name}!({left}, {right});\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "{name} operands"); + } + let bad = format!("#[test]\nfn t() {{\n {name}!(a, b, \"length {{}}\", xs.len());\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&bad), [(4, "all-unguarded")], "{name} message"); + } + } + + #[test] + fn all_guards_require_checks_of_collection_properties() { + for expr in ["xs.len()", "xs.is_empty()", "xs.iter().count()", "xs.first()", "xs.iter().any(|x| *x > 0)", "xs.iter().next()", "xs.last()"] { + let bad = format!("#[test]\nfn t() {{\n let _ = {expr};\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&bad), [(4, "all-unguarded")], "unused {expr}"); + let good = format!("#[test]\nfn t() {{\n assert_eq!({expr}, expected);\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "checked {expr}"); + } + } + + #[test] + fn all_guards_accept_first_item_access_that_fails_when_empty() { + for expr in ["xs[0]", "xs.first().unwrap()", "xs.first().expect(\"item\")", "xs.iter().next().unwrap()", "xs.iter().next().expect(\"item\")"] + { + let good = format!("#[test]\nfn t() {{\n let _ = {expr};\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "{expr} fails when empty"); + let inner = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| {expr} > 0));\n}}\n"); + assert_eq!(hits(&inner), [(3, "all-unguarded")], "{expr} inside the predicate"); + let message = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| *x > 0), \"item {{:?}}\", {expr});\n}}\n"); + assert_eq!(hits(&message), [(3, "all-unguarded")], "{expr} inside the message"); + } + let literal = "#[test]\nfn t() {\n let _ = [0];\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(literal), [(4, "all-unguarded")], "an array literal does not access an item"); + } + + #[test] + fn all_guards_accept_panicking_first_item_bindings() { + let good = "#[test]\nfn t() {\n let Some(x) = xs.first() else { panic!(\"empty\") };\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(good), []); + let bad = "#[test]\nfn t() {\n let Some(x) = xs.first() else { skip(); };\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(bad), [(4, "all-unguarded")]); + } + + #[test] + fn all_hits_count_changes_anywhere_in_their_test() { + let src = "#[should_panic]\n#[test]\nfn t() {\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\nfn other() {}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.len(), 1); + assert_eq!(found[0].line, 5); + let guarded = src.replace(" assert!(xs.iter()", " assert!(!xs.is_empty());\n assert!(xs.iter()"); + assert_eq!(hits(&guarded), [], "the guard prevents the finding before deletion"); + for line in [1, 2, 3, 4, 5, 6] { + assert!(touches(&found[0], Some(&[line].into_iter().collect())), "test line {line}"); + } + assert!(!touches(&found[0], Some(&[7].into_iter().collect())), "another function is outside the test"); + let diff = "diff --git a/crates/x/src/tests.rs b/crates/x/src/tests.rs\n--- a/crates/x/src/tests.rs\n+++ b/crates/x/src/tests.rs\n@@ -5 +4,0 @@\n- assert!(!xs.is_empty());\n"; + let changed = parse_diff(diff); + assert!(touches(&found[0], changed["crates/x/src/tests.rs"].as_ref()), "removing a guard changes the test"); + } + + #[test] + fn all_allow_comments_stay_near_the_finding() { + let distant = "#[test]\nfn t() {\n // test-lint: allow all-unguarded empty input is allowed\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(distant), [(5, "all-unguarded")]); + let adjacent = "#[test]\nfn t() {\n let xs = f();\n // test-lint: allow all-unguarded empty input is allowed\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(adjacent), []); + let same = "#[test]\nfn t() {\n assert!(xs.iter().all(|x| *x > 0)); // test-lint: allow all-unguarded empty input is allowed\n}\n"; + assert_eq!(hits(same), []); + } + + #[test] + fn only_weak_checks_are_reported_once_per_test() { + let bad = "#[test]\nfn t() {\n assert!(parse(\"a\").is_ok());\n assert!(!list().is_empty());\n}\n"; + assert_eq!(hits(bad), [(2, "only-weak")]); + let good = "#[test]\nfn t() {\n assert!(parse(\"a\").is_ok());\n assert_eq!(parse(\"a\").unwrap(), 1);\n}\n"; + assert_eq!(hits(good), []); + let refusal = "#[test]\nfn t() {\n assert!(parse(\"\").is_err());\n}\n"; + assert_eq!(hits(refusal), [], "is_err is not on the plan's list"); + let compound = "#[test]\nfn t() {\n assert!(a.is_some() && a == Some(2));\n}\n"; + assert_eq!(hits(compound), []); + } + + #[test] + fn self_compare_needs_the_same_plain_expression() { + let bad = "#[test]\nfn t() {\n let x = f();\n assert_eq!(x.len(), x.len());\n assert_eq!(&x, x);\n}\n"; + assert_eq!(hits(bad), [(4, "self-compare"), (5, "self-compare")]); + let good = "#[test]\nfn t() {\n assert_eq!(write(&doc), write(&doc), \"deterministic\");\n assert_eq!(f(\"a\"), f(\"b\"));\n assert_ne!(\"a b\", \"ab\");\n assert_ne!(x /* one */, x.y);\n assert_ne!(' ', ':');\n}\n"; + assert_eq!(hits(good), [], "literal text, including its spaces, is compared"); + } + + #[test] + fn self_compare_counts_changes_through_the_second_operand() { + let src = "#[test]\nfn t() {\n assert_eq!(\n actual,\n actual,\n \"comparison\"\n );\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.len(), 1); + let hit = &found[0]; + assert_eq!(hit.rule, Rule::SelfCompare); + assert_eq!((hit.line, hit.first, hit.last), (3, 3, 5)); + for line in [3, 4, 5] { + assert!(touches(hit, Some(&[line].into_iter().collect())), "changed line {line}"); + } + for line in [2, 6, 7] { + assert!(!touches(hit, Some(&[line].into_iter().collect())), "changed line {line}"); + } + assert_eq!(hits(&src.replacen(" actual,", " expected,", 1)), []); + } + + #[test] + fn self_compare_keeps_exemptions_near_the_macro_opening() { + let src = "#[test]\nfn t() {\n assert_eq!( // MARKER\n actual, // OPERAND\n actual\n );\n}\n"; + let allow = "test-lint: allow self-compare checks the lint"; + assert_eq!(hits(&src.replace("MARKER", allow)), []); + assert_eq!(hits(&src.replace(" assert_eq!", &format!(" // {allow}\n assert_eq!"))), []); + assert_eq!(hits(&src.replace("OPERAND", allow)), [(3, "self-compare")]); + } + + #[test] + fn a_process_test_must_read_its_output() { + let bad = "#[test]\nfn t() {\n let out = Command::new(bin()).arg(\"x\").output().unwrap();\n assert!(out.status.success());\n}\n"; + assert_eq!(hits(bad), [(2, "exit-status-only")]); + let good = "#[test]\nfn t() {\n let out = Command::new(bin()).output().unwrap();\n assert!(out.status.success());\n assert_eq!(out.stdout, b\"ok\\n\");\n}\n"; + assert_eq!(hits(good), []); + } + + #[test] + fn process_status_checks_accept_every_comparison_assertion() { + for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {name}!(out.status.code(), Some(0), \"{{:?}}\", out.stderr);\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{name}"); + let good = bad.replace("Some(0)", "parse_code(&out.stdout)"); + assert_eq!(hits(&good), [], "{name} reads output in its second operand"); + } + } + + #[test] + fn process_status_checks_accept_either_compared_operand() { + for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { + for (expected, status) in [("Some(0)", "out.status.code()"), ("true", "out.status.success()")] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {name}!({expected}, {status}, \"{{:?}}\", out.stdout);\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{name} with {status} on the right"); + let good = bad.replace(expected, "parse_status(&out.stderr)"); + assert_eq!(hits(&good), [], "{name} reads output in its first operand"); + let message = bad.replace(status, "expected_status"); + assert_eq!(hits(&message), [], "{name} has no status check in its operands"); + } + } + } + + #[test] + fn process_output_in_failure_messages_does_not_count_as_reading() { + for assertion in ["assert!(out.status.success()", "debug_assert!(out.status.success()", "prop_assert!(out.status.success()"] { + let bad = + format!("#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {assertion}, \"{{:?}}\", out.stderr);\n}}\n"); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{assertion}"); + let good = bad.replace("out.status.success()", "out.status.success() && out.stdout == expected"); + assert_eq!(hits(&good), [], "output in the condition of {assertion}"); + } + for assertion in ["assert_eq", "assert_ne"] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {assertion}!(out.status.code(), f::(), \"{{:?}}\", out.stderr);\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{assertion}"); + let good = bad.replace("f::()", "from_slice(&out.stdout)"); + assert_eq!(hits(&good), [], "output in the second operand of {assertion}"); + } + } + + #[test] + fn stream_configuration_does_not_count_as_reading_output() { + for stream in ["stdout", "stderr", "stdin"] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).{stream}(Stdio::piped()).output().unwrap();\n assert!(out.status.success());\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{stream} configuration"); + let good = bad.replace(" assert!", " let _ = out.stderr;\n assert!"); + assert_eq!(hits(&good), [], "reading a field after {stream} configuration"); + } + let bad = "#[test]\nfn t() {\n let out = Command::new(bin()).stdout (std::process::Stdio::piped()).output().unwrap();\n assert!(out.status.success());\n}\n"; + assert_eq!(hits(bad), [(2, "exit-status-only")]); + let good = bad.replace("std::process::Stdio::piped()", "output.stdout"); + assert_eq!(hits(&good), [], "a field read in a builder argument counts"); + } + + #[test] + fn output_inspection_counts_outside_failure_messages() { + for read in [ + "out.stdout", + "out.stderr", + "String::from_utf8(out.stdout)", + "fs::read(path)", + "read_to_string(path)", + "from_slice(data)", + "from_str(text)", + "text.contains(needle)", + ] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n assert!(out.status.success(), \"{{:?}}\", {read});\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{read} in a message"); + let good = bad.replace(" assert!", &format!(" let _ = {read};\n assert!")); + assert_eq!(hits(&good), [], "{read} outside a message"); + } + } + + #[test] + fn failure_messages_are_removed_for_every_standard_assertion() { + for name in [ + "assert", + "debug_assert", + "prop_assert", + "assert_eq", + "assert_ne", + "debug_assert_eq", + "debug_assert_ne", + "prop_assert_eq", + "prop_assert_ne", + ] { + let operands = if guard_arg_count(name) == 1 { "true" } else { "left, right" }; + let bad = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| *x > 0));\n {name}!({operands}, \"{{:?}}\", xs[0]);\n}}\n"); + assert_eq!(hits(&bad), [(3, "all-unguarded")], "{name} message"); + let good = bad.replace(" assert!", " let _ = xs[0];\n assert!"); + assert_eq!(hits(&good), [], "access outside the {name} message"); + } + } + + #[test] + fn assertion_arguments_keep_turbofish_groups_and_split_comparisons() { + for operand in ["f::()", "f::>()", "f :: ()"] { + let src = format!("{operand}, expected, message"); + let m = mask(&src); + let args: Vec<&str> = split_args(&m, 0, m.len()).into_iter().map(|(from, to)| src[from..to].trim()).collect(); + assert_eq!(args, [operand, "expected", "message"], "{operand}"); + let comparison = format!("a < b, {operand} > c, message"); + let m = mask(&comparison); + let args: Vec<&str> = split_args(&m, 0, m.len()).into_iter().map(|(from, to)| comparison[from..to].trim()).collect(); + assert_eq!(args, ["a < b", &format!("{operand} > c"), "message"], "comparisons around {operand}"); + } + } + + #[test] + fn a_test_needs_an_assertion_or_an_asserting_helper() { + let bad = "#[test]\nfn t() {\n let d = open(\"x\").unwrap();\n d.save();\n}\n"; + assert_eq!(hits(bad), [(2, "no-assertion")]); + let panics = "fn f() {}\n/// Panics.\n#[should_panic(expected = \"x\")]\n#[test]\nfn p() {\n f();\n}\n"; + assert_eq!(hits(panics), [], "#[should_panic] before #[test]"); + let src = "fn same(a: u8, b: u8) {\n assert_eq!(a, b);\n}\nfn twice(a: u8) {\n same(a, a);\n}\n#[test]\nfn t() {\n twice(f());\n}\n#[test]\n#[should_panic]\nfn p() {\n f();\n}\n#[test]\nfn q() {\n check_round_trip(f());\n}\n"; + let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); + assert!(helpers["crates/x"].contains("twice"), "{helpers:?}"); + let ctx = Ctx { helpers, ci_env: HashSet::new() }; + assert_eq!(hits_in("crates/x/tests/it.rs", src, &ctx), []); + assert_eq!(hits_in("crates/y/tests/it.rs", src, &ctx), [(8, "no-assertion")], "another crate's helper does not count"); + let kit = asserting_helpers(&[("crates/testkit/src/lib.rs".to_owned(), src.to_owned()), ("crates/y/src/lib.rs".to_owned(), String::new())]); + assert!(kit["crates/y"].contains("twice"), "testkit helpers count in every crate: {kit:?}"); + assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx { helpers: HashMap::new(), ci_env: HashSet::new() }), [(8, "no-assertion")]); + } + + #[test] + fn generic_asserting_calls_count_for_functions_and_methods() { + for call in ["check_round_trip::()", "check_round_trip::>(x)", "value.check::()", "value.check :: >> ()"] { + let src = format!("#[test]\nfn t() {{\n {call};\n}}\n"); + assert_eq!(hits(&src), [], "{call}"); + } + for expression in ["check_round_trip::", "value.check::", "round_trip::()", "value.round_trip::()"] { + let src = format!("#[test]\nfn t() {{\n let _ = {expression};\n}}\n"); + assert_eq!(hits(&src), [(2, "no-assertion")], "{expression}"); + } + } + + #[test] + fn generic_crate_helpers_count_through_other_helpers() { + let defs = "fn same(a: T, b: T) { assert_eq!(a, b); }\nfn twice(a: T) { same::(a, a); }\nfn idle() {}\n"; + let helpers = asserting_helpers(&[("crates/x/tests/helpers.rs".to_owned(), defs.to_owned())]); + assert!(helpers["crates/x"].contains("same")); + assert!(helpers["crates/x"].contains("twice")); + assert!(!helpers["crates/x"].contains("idle")); + let ctx = Ctx { helpers, ci_env: HashSet::new() }; + for call in ["same::(a, b)", "twice::>>(x)"] { + let src = format!("#[test]\nfn t() {{\n {call};\n}}\n"); + assert_eq!(hits_in("crates/x/tests/it.rs", &src, &ctx), [], "{call}"); + assert_eq!(hits_in("crates/y/tests/it.rs", &src, &ctx), [(2, "no-assertion")], "{call} in another crate"); + } + for expression in ["idle::()", "same::", "value.same::()"] { + let src = format!("#[test]\nfn t() {{\n let _ = {expression};\n}}\n"); + assert_eq!(hits_in("crates/x/tests/it.rs", &src, &ctx), [(2, "no-assertion")], "{expression}"); + } + } + + #[test] + fn early_returns_on_values_are_reported_and_resource_skips_are_not() { + let bad = "#[test]\nfn t() {\n let Some(n) = find() else { return };\n assert_eq!(n, 2);\n}\n"; + assert_eq!(hits(bad), [(3, "early-return")]); + let fonts = "#[test]\nfn t() {\n let Some(face) = installed_family(\"Kufi\") else { return; };\n assert_eq!(face.n, 2);\n}\n"; + assert_eq!(hits(fonts), []); + let closure = "#[test]\nfn t() {\n let f = |x: u8| { if x == 0 { return; } g(x) };\n assert_eq!(f(1), ());\n}\n"; + assert_eq!(hits(closure), []); + let last = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n if g() { return; }\n}\n"; + assert_eq!(hits(last), []); + let value = "#[test]\nfn t() -> Result<(), String> {\n if f()? == 0 { return Ok(()); }\n assert_eq!(g(), 1);\n Ok(())\n}\n"; + assert_eq!(hits(value), [(3, "early-return")]); + let checked = "#[test]\nfn t() {\n for _ in 0..9 {\n if g() == 1 {\n assert_eq!(f(), 2);\n return;\n }\n }\n panic!(\"never stable\");\n}\n"; + assert_eq!(hits(checked), [], "a return after an assertion in its block"); + let said = "#[test]\nfn t() {\n if !link(\"a\") {\n eprintln!(\"skipped: no links here\");\n return;\n }\n assert_eq!(f(), 2);\n}\n"; + assert_eq!(hits(said), [], "a return after a printed skip note"); + let commented = "#[test]\nfn t() {\n let Some(w) = width() else { return }; // no wide font here\n assert_eq!(w, 2);\n}\n"; + assert_eq!(hits(commented), [], "a return whose line says why"); + let quiet = "#[test]\nfn t() {\n if !link(\"a\") {\n return;\n }\n assert_eq!(f(), 2);\n}\n"; + assert_eq!(hits(quiet), [(4, "early-return")]); + } + + #[test] + fn ignore_needs_a_reason() { + let bad = "#[test]\n#[ignore]\nfn t() {\n assert_eq!(f(), 1);\n}\n#[ignore = \" \"]\n#[test]\nfn u() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(bad), [(2, "ignore-without-reason"), (6, "ignore-without-reason")]); + let good = "#[test]\n#[ignore = \"a benchmark: run with --ignored\"]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(good), []); + } + + #[test] + fn ignore_accepts_non_empty_raw_string_reasons() { + for hashes in ["", "#", "##", "########"] { + for reason in ["requires an external service", " service ", r"service \ path"] { + let literal = format!("r{hashes}\"{reason}\"{hashes}"); + let src = format!("#[test]\n#[ignore = {literal}]\nfn t() {{ assert_eq!(f(), 1); }}\n"); + assert_eq!(hits(&src), [], "{literal}"); + } + for reason in ["", " ", "\t\n"] { + let literal = format!("r{hashes}\"{reason}\"{hashes}"); + let src = format!("#[test]\n#[ignore = {literal}]\nfn t() {{ assert_eq!(f(), 1); }}\n"); + assert_eq!(hits(&src), [(2, "ignore-without-reason")], "{literal}"); + } + } + } + + #[test] + fn env_gates_need_a_variable_ci_sets() { + let bad = "#[test]\nfn t() {\n let Ok(dir) = std::env::var(\"MY_SAMPLES\") else { return };\n assert_eq!(count(&dir), 3);\n}\n"; + assert_eq!(hits(bad), [(3, "env-gate-unset")]); + let ci = "#[test]\nfn t() {\n if std::env::var(\"SET_IN_CI\").is_ok() { assert_eq!(f(), 1); }\n assert_eq!(std::env::var(\"CARGO_PKG_NAME\").unwrap(), \"x\");\n}\n"; + assert_eq!(hits(ci), []); + let child = "const CHILD: &str = \"X_TEST_CHILD\";\n#[test]\nfn t() {\n if std::env::var_os(\"X_TEST_CHILD\").is_some() { assert_eq!(f(), 1); }\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(child), []); + } + + #[test] + fn env_gates_ignore_commented_out_setters() { + for setter in ["cmd.env(\"MY_SAMPLES\", dir);", "std::env::set_var(\"MY_SAMPLES\", \"x\");", "const X: &str = \"MY_SAMPLES\";"] { + for comment in [format!("// {setter}"), format!("/* {setter} */"), format!("/* outer /* {setter} */ end */")] { + let src = + format!("{comment}\n#[test]\nfn t() {{\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(dir, expected);\n}}\n"); + assert_eq!(hits(&src), [(4, "env-gate-unset")], "{comment}"); + } + } + } + + #[test] + fn env_gates_keep_code_setters_and_literal_contents() { + for setter in [ + "cmd . env ( \"MY_SAMPLES\", dir);", + "std::env::set_var ( \"MY_SAMPLES\", \"x\");", + "set_var(\"MY_SAMPLES\", \"x\");", + "use std::env::set_var; fn setup() { set_var(\"MY_SAMPLES\", \"x\"); }", + "cmd.set_var(\"MY_SAMPLES\", \"x\");", + "const X: &str = \"MY_SAMPLES\";", + "cmd.env(/* name */ \"MY_SAMPLES\", dir);", + ] { + let src = format!("{setter}\n#[test]\nfn t() {{\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(dir, expected);\n}}\n"); + assert_eq!(hits(&src), [], "{setter}"); + assert_eq!(hits(&src.replacen("MY_SAMPLES", "OTHER_SAMPLES", 1)), [(4, "env-gate-unset")], "{setter}"); + } + let src = "let a = \"https://host/*path*/\"; /* removed */ let b = r#\"// kept /* kept */\"#; // removed\nlet c = '/';"; + let masked = String::from_utf8(mask_comments(src)).unwrap(); + assert!(masked.contains("\"https://host/*path*/\"")); + assert!(masked.contains("r#\"// kept /* kept */\"#")); + assert!(masked.contains("let c = '/';")); + assert!(!masked.contains("removed")); + } + + #[test] + fn env_gates_require_setter_call_boundaries() { + for reader in [ + "read_env(\"MY_SAMPLES\");", + "cmd.read_env(\"MY_SAMPLES\");", + "env(\"MY_SAMPLES\", dir);", + "my_set_var(\"MY_SAMPLES\", \"x\");", + "std::env::my_set_var(\"MY_SAMPLES\", \"x\");", + "cmd.my_set_var(\"MY_SAMPLES\", \"x\");", + ] { + let src = format!("{reader}\n#[test]\nfn t() {{\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(dir, expected);\n}}\n"); + assert_eq!(hits(&src), [(4, "env-gate-unset")], "{reader}"); + } + } + + #[test] + fn sleep_in_test_code_is_reported() { + let bad = "fn wait() {\n std::thread::sleep(Duration::from_millis(5));\n}\n#[test]\nfn t() {\n thread::sleep(D);\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(bad), [(2, "sleep"), (6, "sleep")]); + let good = "fn sleep(d: D) {}\n#[test]\nfn t() {\n run(\"$.sleep(250)\");\n clock.sleep(D);\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(good), []); + let shipped = "pub fn wait() {\n std::thread::sleep(D);\n}\n#[cfg(test)]\nmod tests {}\n"; + assert_eq!(hits_in("crates/x/src/lib.rs", shipped, &ctx()), [], "code before #[cfg(test)] is not test code"); + assert_eq!(hits_in("xtask/src/test_lint.rs", shipped, &ctx()), [], "a name that only starts with test is not a test file"); + let after = "#[cfg(test)]\nmod tests {\n fn w() { thread::sleep(D); }\n}\npub fn later() {\n thread::sleep(D);\n}\n"; + assert_eq!(hits_in("crates/x/src/lib.rs", after, &ctx()), [(3, "sleep")], "code after a #[cfg(test)] module is not test code"); + for test_file in [ + "crates/x/src/tests.rs", + "crates/x/src/tests_wheel.rs", + "crates/x/src/widget_tests.rs", + "crates/x/tests/it/a.rs", + "crates/testkit/src/lib.rs", + ] { + assert_eq!(hits_in(test_file, shipped, &ctx()), [(2, "sleep")], "{test_file}"); + } + } + + #[test] + fn reading_rust_source_is_reported_outside_the_audits() { + let bad = "#[test]\nfn t() {\n let src = include_str!(\"../lib.rs\");\n assert_eq!(src.matches(\"x\").count(), 1);\n}\n"; + assert_eq!(hits(bad), [(3, "reads-source")]); + let walk = "#[test]\nfn t() {\n let n = files().filter(|p| p.ends_with(\".rs\")).count();\n assert_eq!(n, 4);\n}\n"; + assert_eq!(hits(walk), [(3, "reads-source")]); + assert_eq!(hits_in(SOURCE_AUDITS[0], bad, &ctx()), []); + let data = "#[test]\nfn t() {\n let s = include_str!(\"fixtures/a.svg\");\n assert_eq!(s.len(), 4);\n}\n"; + assert_eq!(hits(data), []); + } + + #[test] + fn allow_comments_need_the_rule_and_a_reason() { + let src = "#[test]\nfn t() {\n // test-lint: allow sleep the file clock has a 2 ms step\n thread::sleep(D);\n thread::sleep(D); // test-lint: allow sleep same\n assert_eq!(f(), 1);\n thread::sleep(D); // test-lint: allow sleep\n thread::sleep(D); // test-lint: allow early-return wrong rule\n}\n// test-lint: allow no-assertion a smoke test of the panic-free reader\n#[test]\nfn u() {\n let _ = read(b\"junk\");\n}\n"; + assert_eq!(hits(src), [(7, "sleep"), (8, "sleep")], "an allow covers its own line and the next, and needs a reason"); + let strings = "#[test]\nfn t() {\n let s = \"test-lint: allow sleep in a string\"; thread::sleep(D);\n let r = r#\"test-lint: allow sleep raw\"#; thread::sleep(D);\n /* test-lint: allow sleep a block comment */ thread::sleep(D);\n assert_eq!(s, r);\n}\n"; + assert_eq!(hits(strings), [(3, "sleep"), (4, "sleep")], "a marker in a literal is not an exemption"); + } + + #[test] + fn comments_and_strings_are_not_code() { + let src = "#[test]\nfn t() {\n // assert!(x.iter().all(|y| y))\n let s = \"thread::sleep(d); #[ignore]\";\n let r = r#\"env::var(\"NOPE\")\"#;\n let c = '\"';\n assert_eq!(s, r);\n}\n"; + assert_eq!(hits(src), []); + } + + #[test] + fn tests_are_found_by_their_attributes() { + let src = "#[cfg(test)]\nmod tests {\n #[tokio::test]\n async fn a() {}\n #[test_case(1)]\n fn b(n: u8) {}\n proptest! {\n #[test]\n fn c(x in 0..9u8) {}\n }\n #[test]\n fn d() -> Result<(), String> { Ok(()) }\n fn not_a_test() {}\n}\n"; + let names: Vec = tests_in(&mask(src)).into_iter().map(|t| t.name).collect(); + assert_eq!(names, ["a", "b", "c", "d"]); + } + + #[test] + fn changed_lines_come_from_the_new_side_of_each_hunk() { + let diff = "diff --git a/crates/x/src/a.rs b/crates/x/src/a.rs\nindex 1..2 100644\n--- a/crates/x/src/a.rs\n+++ b/crates/x/src/a.rs\n@@ -3,0 +4,2 @@ fn f() {\n+a\n+b\n@@ -10 +12 @@\n-c\n+d\n@@ -20,2 +21,0 @@\n-e\ndiff --git a/crates/x/src/n.rs b/crates/x/src/n.rs\nnew file mode 100644\n--- /dev/null\n+++ b/crates/x/src/n.rs\n@@ -0,0 +1,3 @@\n"; + let got = parse_diff(diff); + assert_eq!(got.len(), 2); + assert_eq!(got["crates/x/src/a.rs"], Some([4, 5, 12, 21, 22].into_iter().collect())); + assert_eq!(got["crates/x/src/n.rs"], None); + } + + #[test] + fn deleting_the_first_attribute_changes_the_remaining_test() { + let path = "crates/x/src/tests.rs"; + for (prefix, anchor) in [("", 0), ("fn before() {}\n", 1)] { + let src = format!("{prefix}#[test]\nfn t() {{}}\n#[test]\nfn other() {{}}\n"); + let before = src.replacen("#[test]", "#[should_panic]\n#[test]", 1); + assert!(lint_file(path, &before, &ctx()).iter().all(|h| h.test != "t"), "the attribute prevents the finding"); + let found = lint_file(path, &src, &ctx()); + assert_eq!(found.len(), 2); + let old = anchor + 1; + let diff = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -{old} +{anchor},0 @@\n-#[should_panic]\n"); + let changed = parse_diff(&diff); + let expected = if anchor == 0 { vec![1] } else { vec![anchor, anchor + 1] }; + assert_eq!(changed[path], Some(expected.into_iter().collect())); + assert_eq!(found[0].rule, Rule::NoAssertion); + assert_eq!(found[0].test, "t"); + assert!(touches(&found[0], changed[path].as_ref()), "the deletion changes the remaining test"); + assert!(!touches(&found[1], changed[path].as_ref()), "the following test is unchanged"); + } + } + + #[test] + fn only_hits_on_changed_lines_count() { + let src = "#[test]\nfn old() {\n f();\n}\n#[test]\nfn new() {\n g();\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.len(), 2); + let changed: BTreeSet = [7].into_iter().collect(); + let counted: Vec<&str> = found.iter().filter(|h| touches(h, Some(&changed))).map(|h| h.test.as_str()).collect(); + assert_eq!(counted, ["new"]); + assert_eq!(found.iter().filter(|h| touches(h, None)).count(), 2); + assert_eq!(found.iter().filter(|h| touches(h, Some(&BTreeSet::new()))).count(), 0); + } + + #[test] + fn options_reject_unknown_and_repeated_arguments() { + assert_eq!(Options::parse(&[]), Ok(Options::default())); + assert_eq!(Options::parse(&["--base", "abc"]), Ok(Options { all: false, base: Some("abc".into()) })); + assert_eq!(Options::parse(&["--all"]), Ok(Options { all: true, base: None })); + for bad in [&["--base"][..], &["--base", "--all"], &["--all", "--all"], &["--fix"], &["--all", "--base", "x"]] { + assert!(Options::parse(bad).unwrap_err().starts_with("test-lint:"), "{bad:?}"); + } + } + + #[test] + fn workflow_variables_count_as_set() { + let names: Vec = upper_words("env:\n AFFINITY_CORPUS_REQUIRED: 1\n run: X=1 cargo test # A\n").collect(); + assert_eq!(names, ["AFFINITY_CORPUS_REQUIRED"]); + assert!(set_by_system("CARGO_MANIFEST_DIR") && set_by_system("HOME") && !set_by_system("MY_SAMPLES")); + } + + #[test] + fn workflow_mapping_keys_count_without_reads_or_comments() { + let assigned: Vec = upper_words("env:\n MY_SAMPLES: fixtures\n - OTHER_SAMPLES: fixtures\n EMPTY_SAMPLES:\n").collect(); + assert_eq!(assigned, ["MY_SAMPLES", "OTHER_SAMPLES", "EMPTY_SAMPLES"]); + let reads = "# MY_SAMPLES: fixtures\nif: env.MY_SAMPLES != ''\nrun: echo $OTHER_SAMPLES ${EMPTY_SAMPLES}\nvalue: ${{ env.MY_SAMPLES }}\n"; + assert_eq!(upper_words(reads).collect::>(), Vec::::new()); + } + + #[test] + fn workflow_script_assignments_count_without_reads_or_comments() { + for assignment in [ + " MY_SAMPLES=value", + " export MY_SAMPLES=value", + " run: MY_SAMPLES=value cargo test", + " echo \"MY_SAMPLES=value\" >> \"$GITHUB_ENV\"", + " echo 'MY_SAMPLES=value' >> \"$GITHUB_ENV\"", + " MY_SAMPLES=value # OTHER_SAMPLES=value", + " MY_SAMPLES=\"#value\"", + " MY_SAMPLES=", + " - MY_SAMPLES=value", + ] { + assert_eq!(upper_words(assignment).collect::>(), ["MY_SAMPLES"], "{assignment}"); + let commented = format!("# {assignment}"); + assert_eq!(upper_words(&commented).collect::>(), Vec::::new(), "{commented}"); + } + let reads = "env.MY_SAMPLES=value\n${{ env.MY_SAMPLES }}\n$MY_SAMPLES\n${MY_SAMPLES}\nMY_SAMPLES==value\n"; + assert_eq!(upper_words(reads).collect::>(), Vec::::new()); + } + + #[test] + fn workflow_mentions_do_not_suppress_unset_gates() { + let src = "#[test]\nfn t() {\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; + for workflow in ["if: env.MY_SAMPLES != ''", "run: echo $MY_SAMPLES", "# MY_SAMPLES=value"] { + let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words(workflow).collect() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [(3, "env-gate-unset")], "{workflow}"); + } + for workflow in ["env:\n MY_SAMPLES: fixtures", "run: |\n export MY_SAMPLES=fixtures", "with:\n env: |\n MY_SAMPLES=fixtures"] { + let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words(workflow).collect() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [], "{workflow}"); + } + } +} From f677523787f00ad35282422242e369c860aeb6c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 03:23:37 -0800 Subject: [PATCH 42/69] Menus: the keymap test counts only runs the catalogs held still through A font, plug-in, script or proof setup change from a test running alongside rebuilds the menus, so the test now holds the fonts and plug-ins steady and runs again on a new app, at most 20 times, until the catalogs held still, as the Selection move test in canvas/tests.rs does. --- crates/ui-egui/src/menus/model.rs | 70 +++++++++++++++++++++---------- 1 file changed, 48 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 3095b74794..ced219084f 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -743,7 +743,9 @@ mod tests { /// A new window keymap with nothing else changed (the framework builds the first one after the first frame's /// menus) sets the panel rows' shortcuts from it, in the bar and in the laid-out bar, without building the menus - /// again. + /// again. The menus are also built again when a process-wide catalog changes, so the fonts and plug-ins are held + /// steady against tests running alongside, and the steps run again on a new app, at most 20 times, until the + /// other catalogs held still through them. #[test] fn a_new_keymap_alone_sets_the_shortcuts_without_a_rebuild() { fn clear(nodes: &mut [Node]) { @@ -761,28 +763,52 @@ mod tests { .filter(|it| it.command.id == "window.panel" && it.command.params["toggle"] == true && it.shortcut.is_some()) .count() } - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let ctx = crate::testing::ui_context(); - for _ in 0..2 { - crate::testing::app_frame(&mut app, &ctx, egui::RawInput::default()); - } - let shown = panel_chords(&app.menus.bar); + let fonts = vectorcraft_text::FontDb::global(); + let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins()); + let catalogs = || { + ( + crate::menus::plugin_revision(), + fonts.generation(), + fonts.installed_fonts_ready(), + crate::scripts_menu::revision(), + crate::dialogs::proof_setup::saved_revision(), + ) + }; + let run = || { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + for _ in 0..2 { + crate::testing::app_frame(&mut app, &ctx, egui::RawInput::default()); + } + let shown = panel_chords(&app.menus.bar); + // The menus as a refresh before the window's keymap leaves them. + app.menus.keymap = None; + for menu in &mut app.menus.bar.menus { + clear(&mut menu.children); + } + app.menus.laid.edit(|laid| laid.menus.iter_mut().for_each(|menu| clear(&mut menu.children))); + let (rebuilds, refreshes) = (app.menus.rebuilds, app.menus.shortcut_refreshes); + refresh(&mut app, &ctx); + let first = (app.menus.rebuilds - rebuilds, app.menus.shortcut_refreshes - refreshes); + let chords = (panel_chords(&app.menus.bar), panel_chords(&app.menus.laid)); + refresh(&mut app, &ctx); + let second = (app.menus.rebuilds - rebuilds, app.menus.shortcut_refreshes - refreshes); + (shown, first, chords, second) + }; + let (shown, first, chords, second) = (0..20) + .find_map(|_| { + let before = catalogs(); + let out = run(); + (catalogs() == before).then_some(out) + }) + .unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs")); assert!(shown > 0, "the panel rows show their shortcuts' chords"); - // The menus as a refresh before the window's keymap leaves them. - app.menus.keymap = None; - for menu in &mut app.menus.bar.menus { - clear(&mut menu.children); - } - app.menus.laid.edit(|laid| laid.menus.iter_mut().for_each(|menu| clear(&mut menu.children))); - let (rebuilds, refreshes) = (app.menus.rebuilds, app.menus.shortcut_refreshes); - refresh(&mut app, &ctx); - assert_eq!(app.menus.rebuilds, rebuilds, "a new keymap alone does not build the menus again"); - assert_eq!(app.menus.shortcut_refreshes, refreshes + 1, "the new keymap sets the shortcuts"); - assert_eq!(panel_chords(&app.menus.bar), shown, "the panel rows show their chords again"); - assert_eq!(panel_chords(&app.menus.laid), shown, "the laid-out bar shows them too"); - refresh(&mut app, &ctx); - assert_eq!((app.menus.rebuilds, app.menus.shortcut_refreshes), (rebuilds, refreshes + 1), "the same keymap sets nothing again"); + assert_eq!(first.0, 0, "a new keymap alone does not build the menus again"); + assert_eq!(first.1, 1, "the new keymap sets the shortcuts"); + assert_eq!(chords.0, shown, "the panel rows show their chords again"); + assert_eq!(chords.1, shown, "the laid-out bar shows them too"); + assert_eq!(second, (0, 1), "the same keymap sets nothing again"); } /// A rebuild runs the check of a command that many rows share once: Effect's dialogs, Window's panels, the From f4c911d4d34f9b10071fd050dbc14ab665a61fb9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 03:36:01 -0800 Subject: [PATCH 43/69] Scripts: open options with an importer, null export options and close checks for files that keep every artboard - document.open refuses page, cropTo, pages and crop when a named importer reads the file (linkPages still uses the built-in reader). - exportFile with explicit null options throws a TypeError for GIF, PNG8 and TIFF too. - close(SaveOptions.SAVECHANGES) saves a modern .ai or .ait file and an SVG file with Preserve Editing whatever range was remembered; a range the save refuses still refuses. - The script checker keeps a try statement's catch and finally, and an else after a nested do-while, inside the loop body; a line break after a label does not start a new statement; a this assignment in a function that hides a global clears the global's saved methods; and holder.d['saveAs'] = ... no longer counts as a write to d. - docs/mcp.md describes which files keep every artboard on close. --- crates/engine/src/cmd/fileio.rs | 2 +- crates/engine/src/cmd/fileio/load.rs | 13 +++++- crates/engine/src/cmd/fileio/svg.rs | 9 +++- crates/engine/src/script/dom/save_open.rs | 31 ++++++++++--- crates/engine/src/tests/script_save_open.rs | 39 ++++++++++++++++ crates/engine/tests/plugin_import.rs | 27 +++++++++++ crates/scriptcheck/src/analyze.rs | 19 +++++++- crates/scriptcheck/src/analyze/declared.rs | 33 +++++++++++--- crates/scriptcheck/src/analyze/features.rs | 11 ++--- crates/scriptcheck/src/tests.rs | 50 +++++++++++++++++++++ docs/mcp.md | 7 ++- 11 files changed, 215 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 21424f7bdc..38654bb8ba 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -125,7 +125,7 @@ pub use screens::{ builtin_presets as screen_export_builtin_presets, first_file as screen_first_file, preset_list as screen_export_preset_list, preset_rows as screen_preset_rows, }; -pub(crate) use svg::lost_artboards_warning as svg_lost_artboards_warning; +pub(crate) use svg::{lost_artboards_warning as svg_lost_artboards_warning, preserves_editing as svg_preserves_editing}; /// Does a save in `format` (a format id) with options `p` write a legacy version 7 `.ai` file, /// which holds the artboards its own options pick? An unknown version counts as one. diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index e426bd5a23..cce50485dd 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -1096,8 +1096,17 @@ pub(super) fn open(s: &mut Session, p: &Value) -> Result { source(p, "document.open")? } }; - if crate::file_access::in_script_command() && ["page", "cropTo"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { - let pdf = detect(src.name, &src.bytes).is_some_and(|f| matches!(f.id, "pdf" | "ai" | "ait")) && !vectorcraft_pdf::is_postscript(&src.bytes); + let given = |keys: &[&str]| keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); + let (options, aliases) = (given(&["page", "cropTo"]), given(&["pages", "crop"])); + if crate::file_access::in_script_command() && (options || aliases) { + // An importer plug-in receives only the params, so it cannot apply the pages or the crop + // box; `linkPages` reads the file with the built-in reader before any importer. + let link_pages = p.get("linkPages").and_then(Value::as_bool) == Some(true); + let built_in = link_pages || super::importer::pick(src.name, &src.bytes, p)?.is_none(); + let pdf = built_in + && (!options + || (detect(src.name, &src.bytes).is_some_and(|f| matches!(f.id, "pdf" | "ai" | "ait")) + && !vectorcraft_pdf::is_postscript(&src.bytes))); if !pdf { return Err(bad("document.open", "PDF open options require a PDF file")); } diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index e5ecc858dc..ac66cb8e65 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -174,12 +174,17 @@ pub(super) fn drawn<'a>(doc: &'a Document, p: &Value) -> Option Option { let n = doc.artboards.len(); - let preserved = plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing); - (n > 1 && !preserved).then(|| { + (n > 1 && !preserves_editing(doc, p)).then(|| { format!("{label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all.") }) } +/// Whether a save of `doc` as SVG with options `p` (flat or nested in `svg`) embeds the native +/// document (Preserve Editing Capabilities), which keeps every artboard. +pub(crate) fn preserves_editing(doc: &Document, p: &Value) -> bool { + plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing) +} + /// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder` /// outside the read roots of the request being served (the open document keeps it). fn native_attachment(doc: &Document) -> Vec { diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 09c438040c..060454798a 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -767,6 +767,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { }, Some(o) => match kind.options { Some(class) => options_params(class, o)?, + None if matches!(o, Data::Null) => return Err(HostError::Type("the options must be an object".into())), None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))), }, }; @@ -946,21 +947,37 @@ fn picks_artboards(st: &crate::doc_state::DocState) -> bool { return false; } let options = Value::Object(crate::cmd::fileio::remembered_save_options(st)); - if matches!(st.format, "svg" | "svgz") && crate::cmd::fileio::svg_lost_artboards_warning(&st.doc, &options, st.format).is_some() { + let svg = matches!(st.format, "svg" | "svgz"); + if svg && crate::cmd::fileio::svg_lost_artboards_warning(&st.doc, &options, st.format).is_some() { return true; } if st.format == "pdf" && options.get("useArtboards") == Some(&Value::Bool(false)) { return true; } - if matches!(st.format, "vectorcraft" | "template" | "ai" | "ait") - && options.get("separateArtboards") == Some(&Value::Bool(true)) - && !crate::cmd::fileio::saves_legacy_ai(st.format, &options) - { + let legacy = crate::cmd::fileio::saves_legacy_ai(st.format, &options); + if matches!(st.format, "vectorcraft" | "template" | "ai" | "ait") && options.get("separateArtboards") == Some(&Value::Bool(true)) && !legacy { return false; } let count = st.doc.artboards.len(); - let pick = serde_json::from_value::(options); - match pick.map_err(|e| e.to_string()).and_then(|p| p.resolve(count)) { + // A `.ai` file other than a legacy one saves with `range` "all" (a `range` that isn't text is + // left for the save to refuse). + let modern_ai = matches!(st.format, "ai" | "ait") && !legacy; + let mut effective = options.clone(); + if let (true, Value::Object(o)) = (modern_ai, &mut effective) + && o.get("range").is_none_or(|r| r.is_string() || r.is_null()) + { + o.insert("range".into(), json!("all")); + } + let resolved = serde_json::from_value::(effective).map_err(|e| e.to_string()).and_then(|p| p.resolve(count)); + // Such a `.ai` file, and an SVG file that carries the native document, keep every artboard; + // a pick the save refuses still refuses (an SVG save with `useArtboards: false` reads no pick). + if modern_ai { + return resolved.is_err(); + } + if svg && crate::cmd::fileio::svg_preserves_editing(&st.doc, &options) { + return options.get("useArtboards") != Some(&Value::Bool(false)) && resolved.is_err(); + } + match resolved { Ok(None) => false, Ok(Some(indices)) => (0..count).any(|i| !indices.contains(&i)), Err(_) => true, diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 68183e8637..064ff3c15a 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -763,6 +763,10 @@ fn explicit_crop_box_opens_the_bleed_outside_an_editable_files_trim_box() { let trim = s.active().unwrap().doc.artboards[0].rect; logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}), undefined, {{pDFCropToBox: PDFBoxType.PDFCROPBOX}});")); let crop = s.active().unwrap().doc.artboards[0].rect; + // Without the embedded document and without a crop box, the file opens at its trim box too. + s.execute("document.open", &json!({"path": file.to_string_lossy(), "editingData": false})).unwrap(); + let implicit = s.active().unwrap().doc.artboards[0].rect; + assert_eq!((implicit.width(), implicit.height()), (trim.width(), trim.height()), "{extension}"); assert_eq!((default.width(), default.height()), (trim.width(), trim.height()), "{extension}"); assert!(crop.width() > trim.width() && crop.height() > trim.height(), "{extension}"); } @@ -845,6 +849,9 @@ fn explicit_null_options_do_not_save_export_open_or_close() { for call in [ format!("app.activeDocument.saveAs({f}, null);"), format!("app.activeDocument.exportFile({f}, ExportType.SVG, null);"), + format!("app.activeDocument.exportFile({f}, ExportType.GIF, null);"), + format!("app.activeDocument.exportFile({f}, ExportType.PNG8, null);"), + format!("app.activeDocument.exportFile({f}, ExportType.TIFF, null);"), format!("app.open({f}, null);"), format!("app.open({f}, undefined, null);"), "app.activeDocument.close(null);".into(), @@ -1074,6 +1081,38 @@ fn closing_with_save_changes_checks_the_artboards_the_file_keeps() { let _ = std::fs::remove_dir_all(base); } +/// A `.ai` file saved without separate artboard files, and an SVG file that carries the native +/// document, keep every artboard whatever `range` names, so `close(SaveOptions.SAVECHANGES)` saves +/// them; a `range` the save refuses still refuses. +#[test] +fn closing_with_save_changes_saves_files_that_keep_every_artboard() { + let base = folder("closekeepall"); + let dir = { + let mut s = session(&base); + data_folder(&mut s, &base) + }; + for (name, options) in [("whole.ai", json!({"range": "2"})), ("native.svg", json!({"preserveEditing": true, "range": "1"}))] { + let mut s = session(&base); + data_folder(&mut s, &base); + let file = dir.join(name); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + let mut save = options.clone(); + save["path"] = json!(file.to_string_lossy()); + s.execute("document.save", &save).unwrap(); + let before = std::fs::read(&file).unwrap(); + logged( + &mut s, + &base, + "Folder.userData; vc.run('shape.rectangle', {x: 10, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(s.documents().is_empty(), "{name}"); + assert_ne!(std::fs::read(&file).unwrap(), before, "{name}"); + s.execute("document.open", &json!({"path": file.to_string_lossy()})).unwrap(); + assert_eq!(s.active().unwrap().doc.artboards.len(), 2, "{name} keeps both artboards"); + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn closing_with_save_changes_keeps_all_eps_artboards_for_subset_ranges() { let base = folder("closeepsboards"); diff --git a/crates/engine/tests/plugin_import.rs b/crates/engine/tests/plugin_import.rs index 1327e57208..9f77d86ec4 100644 --- a/crates/engine/tests/plugin_import.rs +++ b/crates/engine/tests/plugin_import.rs @@ -121,6 +121,33 @@ fn scripted_open_converts_importer_output_to_the_requested_color_space() { let _ = std::fs::remove_dir_all(dir); } +/// A script's PDF open options are refused for a file the named importer reads, which is given +/// only the params, even when the file's extension is a PDF one. +#[test] +fn scripted_pdf_open_options_are_refused_for_an_importer() { + let mut s = Session::new(); + install(&mut s, &tpl::returning(&tpl::importer("test.scriptpdfoptions", r#"["ai"]"#, "{}"), RECT)); + let dir = tmp_dir("scriptpdfoptions"); + s.attach_script_data(dir.join("settings/Script Data")); + let file = dir.join("x.ai"); + std::fs::write(&file, b"importer input").unwrap(); + let script = dir.join("main.jsx"); + let path = serde_json::to_string(&file.to_string_lossy()).unwrap(); + for option in ["page: 1", "cropTo: 'media'", "pages: '1'", "crop: 'media'"] { + std::fs::write( + &script, + format!("Folder.userData; vc.run('document.open', {{path: {path}, importer: 'plugin.test.scriptpdfoptions', {option}}});"), + ) + .unwrap(); + let count = s.documents().len(); + let out = s.execute("script.run", &json!({"path": script.to_string_lossy()})); + let text = format!("{out:?}"); + assert!(text.contains("PDF open options require a PDF file"), "{option}: {text}"); + assert_eq!(s.documents().len(), count, "{option}"); + } + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn an_importer_adds_a_read_only_format_while_it_is_installed() { let mut s = Session::new(); diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index a66b20ef06..a88d7fd04e 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -619,6 +619,8 @@ struct Analyzer<'s, 'a, 'l> { file: Option<&'a str>, /// The four significant tokens before this one, the latest first. h: [Option>; 4], + /// The significant token before the four of [`Self::h`]. + h4: Option>, brackets: Brackets, /// Nesting too deep to follow was reported: it is reported once. deep: bool, @@ -723,6 +725,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { acc, file, h: [None; 4], + h4: None, brackets: Brackets::default(), deep: false, active: None, @@ -853,6 +856,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.features(&t); self.newer(&t); self.module_check(&t); + self.h4 = self.h[3]; self.h = [Some(t), self.h[0], self.h[1], self.h[2]]; } @@ -1401,7 +1405,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let body = self.scopes.last().map_or(0, |s| s.depth); let starts = before.is_none() || [";", "{", "}"].iter().any(|p| is(before, p)) - || (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !word(before, "else") && !word(before, "do")); + // A line break after a label's `:` does not end the statement the label may be + // the body of (`if (c) l:` before the line). + || (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !is(before, ":") && !word(before, "else") && !word(before, "do")); let whole = word(declaration, "var") && starts && depth.checked_sub(1) == Some(body); if self.objects.len() < self.acc.limits.nesting { self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole, value: None }); @@ -1483,6 +1489,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// The global variable `name` is assigned as a property of `this`: as [`Self::reassigned_later`], + /// and when a function body's own variable hides it, the global's methods saved for the body's + /// end are no longer known either. + pub(super) fn reassigned_global(&mut self, name: &str) { + self.reassigned_later(name); + if let Some(saved) = self.scopes.iter_mut().find_map(|s| s.saved.get_mut(name)) { + saved.writer = 0; + } + } + /// Whether `name` is declared in the innermost function body (`var name`, `function /// name`, a parameter). fn declared_in_body(&self, name: &str) -> bool { @@ -1736,6 +1752,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.var_depth = None; self.conds.clear(); self.h = [None; 4]; + self.h4 = None; self.acc.steps = self.acc.steps.saturating_add(1); let d = directives::parse(t.text); let Some(name) = d.known else { diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index 03ad43ab10..ca4ac99823 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -163,6 +163,9 @@ enum Stage { Head, /// The parentheses after the `while` of a `do` loop. DoHead, + /// The `)` of a `do` loop's `while` was read: the loop ends with the `;` after it, or before the + /// next token. + DoEnd, /// The body's first token is next. Start, /// A body in braces. @@ -170,7 +173,7 @@ enum Stage { /// A body that is one statement without braces. Statement, /// The statement of a body without braces has reached its end: the loop ends at the next token, - /// unless it is `else`, which goes on with the statement. + /// unless it is `else`, `catch` or `finally`, which go on with the statement. Tail, } @@ -274,7 +277,7 @@ impl<'s> Declarations<'s, '_, '_> { /// at it, and `for`, `while` and `do` start a loop. Past [`crate::Limits::nesting`] loops, any /// variable may be assigned in one ([`Declared::looped_full`]). fn loop_start(&mut self, t: &Sig<'s>) { - let [h0, ..] = self.h; + let [h0, h1, ..] = self.h; let depth = self.depth(); while let Some(l) = self.loops.last_mut() { let after_head = std::mem::take(&mut l.after_head); @@ -288,14 +291,19 @@ impl<'s> Declarations<'s, '_, '_> { // don't go on with it, as in [`Analyzer::token`], and it does not follow the // parentheses of an `if` or another statement that the body goes on with. Stage::Statement - if t.nl && depth == l.depth && !goes_on_after(h0) && !goes_on_with(t) && !after_head && !word(h0, "else") && !word(h0, "do") => + if t.nl + && depth == l.depth + && !goes_on_after(h0) + && !goes_on_with(t) + && !after_head + && !["else", "do", "catch", "finally"].iter().any(|w| word(h0, w) && !member_mark(h1)) => { l.stage = Stage::Tail; } Stage::Statement => { if depth == l.depth { if t.is("{") { - l.block = t.stmt || after_head || word(h0, "else"); + l.block = t.stmt || after_head || word(h0, "else") || (word(h0, "finally") && !member_mark(h1)); } else if HEADS.iter().any(|w| t.word(w)) && !member_mark(h0) { l.head = true; } @@ -310,7 +318,14 @@ impl<'s> Declarations<'s, '_, '_> { l.stage = Stage::Statement; break; } - Stage::Tail => { + // The `catch` and `finally` of a `try` statement that is the body go on with it. + Stage::Tail if t.word("catch") || t.word("finally") => { + l.stage = Stage::Statement; + l.head = t.word("catch"); + break; + } + Stage::DoEnd if t.is(";") && depth == l.depth => break, + Stage::Tail | Stage::DoEnd => { self.pop_loop(t.start); // A body of one statement that is this loop ends with it. if let Some(outer) = self.loops.last_mut() @@ -366,7 +381,13 @@ impl<'s> Declarations<'s, '_, '_> { } false } - Stage::DoHead => t.is(")") && depth == l.depth, + Stage::DoHead => { + if t.is(")") && depth == l.depth { + l.stage = Stage::DoEnd; + } + false + } + Stage::DoEnd => t.is(";") && depth == l.depth, Stage::Block => { if t.is("}") && depth == l.depth && l.do_loop { l.stage = Stage::Tail; diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 48db72caad..ac0e69b52f 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -403,15 +403,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // function called without a receiver (ECMA-262 3rd edition, sections 10.2.1 and 10.2.3), so the // global variable of that name may get another value. if changes { - let global = if is(h1, ".") && word(h2, "this") { + // `this`, not a property named `this` (`holder.this.d`). + let global = if is(h1, ".") && word(h2, "this") && !member_mark(h3) { h0.filter(|s| s.kind == T::Ident).map(|s| s.text.to_string()) - } else if is(h0, "]") && is(h2, "[") && word(h3, "this") { + } else if is(h0, "]") && is(h2, "[") && word(h3, "this") && !member_mark(self.h4) { h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 64)) } else { None }; if let Some(name) = global { - self.reassigned_later(&name); + self.reassigned_global(&name); } } let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before, None) != 0).map(|s| s.text); @@ -431,8 +432,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // `local['name' + k]`. writer(h2, h3).filter(|_| !t.is("]")) } else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) { - // `local['saveAs'] = …` - writer(h3, None) + // `local['saveAs'] = …`, not `other.local['saveAs'] = …`. + writer(h3, self.h4) } else { None }; diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 2991b1c23f..ca87f3d384 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -761,6 +761,56 @@ fn an_own_save_as_reassigned_later_in_a_loop_writes_a_file() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 8][..])); } +/// The `catch` and `finally` of a `try` body, and an `else` after a `do` loop inside a body without +/// braces, are in the loop; a statement after the whole loop is not. +#[test] +fn try_clauses_and_else_after_a_nested_do_loop_are_in_the_loop() { + let r = report(concat!( + "var f = new File(p);\n", + "var d = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n", + "var h = {saveAs: function () {}};\n", + "while (i++ < 2) try { d.saveAs(f); } finally { d = app.activeDocument; }\n", + "while (i++ < 2)\n", + " if (i === 2) do e.saveAs(f); while (false);\n", + " else e = app.activeDocument;\n", + "while (n--) do g.saveAs(f); while (false);\n", + "g = app.activeDocument;\n", + "while (n--) h.saveAs(f), holder.finally\n", + "h = app.activeDocument;\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 6][..])); +} + +/// A literal after a label's line break may not run, a `this` assignment in a function whose own +/// variable hides the global one changes the global, and a property `d` of another object is not +/// the variable `d`. +#[test] +fn labels_hidden_globals_and_other_objects_keep_writes_known() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = app.activeDocument;\n", + "if (no) l:\n", + "var a = {saveAs: function () {}};\n", + "a.saveAs(f);\n", + "var b = {saveAs: function () {}};\n", + "function change() { var b; this.b = app.activeDocument; }\n", + "change(); b.saveAs(f);\n", + "var c = {saveAs: function () {}};\n", + "function keep() { var c; c = 1; }\n", + "keep(); c.saveAs(f);\n", + "var d = {saveAs: function () {}};\n", + "holder.d['saveAs'] = 1;\n", + "d.saveAs(f);\n", + "var e = {saveAs: function () {}};\n", + "e['saveAs'] = app.activeDocument.saveAs;\n", + "e.saveAs(f);\n", + "var g = {saveAs: function () {}};\n", + "function other() { var g; holder.this.g = app.activeDocument; holder.this['g'] = 1; }\n", + "other(); g.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8, 17][..])); +} + /// Only a `var` statement directly in a function body or the global code that gives its first name /// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the /// statement. A literal given in a branch, one the value goes on from, one given by an assignment diff --git a/docs/mcp.md b/docs/mcp.md index b2678c4f1d..d4cb072175 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3169,8 +3169,11 @@ through `$`: and leaves the document open when the document has no file (a converted or recovered document included) or when the save would omit artboards. These refusals occur before writing any files. An SVG or SVGZ save of several artboards requires Preserve Editing Capabilities to close with `SaveOptions.SAVECHANGES`. A PDF last saved with - `useArtboards: false` omits artboards; a native or `.ai` file (other than a version 7 `.ai` file) saved with - `separateArtboards` keeps every artboard whatever its range names. + `useArtboards: false` omits artboards; a native file saved with `separateArtboards` and a `.ai` or `.ait` file other + than a version 7 `.ai` file keep every artboard whatever their range names. An SVG file saved with Preserve + Editing Capabilities carries the native document with every artboard, so `close(SaveOptions.SAVECHANGES)` does not + refuse it for omitted artboards. The SVG drawing still shows one artboard, or the art bounds with + `useArtboards: false`, and the SVG save still refuses a range that selects several artboards. `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws an error and leaves the document open, since a script cannot show the prompt. A bad value throws an error before anything is written. The warnings of the save or export that `saveAs`, `exportFile`, `app.open` and `close` run go to the console, each after the method's name From 25756e1b8d38fc93ef8b6c5989253b4a00fc4fd3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 04:43:33 -0800 Subject: [PATCH 44/69] xtask: test-lint fails on four rules; all-unguarded skips collections that cannot be empty Replayed over the last 300 merges of main, all-unguarded failed good pull requests on collections that cannot be empty. It now leaves out: - plain locals bound to an array type of a positive length, to a non-empty array literal or vec![...], or to a literal range followed only by methods that keep an item (map, iter, rev, collect into a known collection ...); counts may be consts of the file - locals filled by a push or insert on every pass of a loop over such a source - fields and const or static items the file declares only as arrays of a positive length - collections compared with a non-empty literal through such methods, directly or through a local built from them, and assertions on a local bound to a count or length - .windows(k) and .chunks_exact(k) when the collection has k items Later code that may remove items or replace the collection cancels the exemption. Only only-weak, self-compare, ignore-without-reason and sleep fail the check now. The other rules list their hits on changed lines without failing. On the same 300 merges, 1 would fail (an only-weak test), and the 3 all-unguarded hits are tests an empty result passes. On main at 07037afda8, all-unguarded lists 392 hits instead of 433. --- docs/development.md | 2 +- xtask/src/main.rs | 7 +- xtask/src/test_lint.rs | 1164 ++++++++++++++++++++++++++++++++++++---- 3 files changed, 1065 insertions(+), 108 deletions(-) diff --git a/docs/development.md b/docs/development.md index 26058129e7..cfd02bacc8 100644 --- a/docs/development.md +++ b/docs/development.md @@ -351,7 +351,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) fails on tests that a wrong result can pass, in the lines and tests changed since a base: `assert!(….all(…))` with no length or emptiness check, a test whose only checks are `is_ok`, `is_some` or `!is_empty`, `assert_eq!(x, x)`, a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, `#[ignore]` without a reason, an environment variable that no CI leg sets, `thread::sleep` in test code, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on a test whose only checks are `is_ok`, `is_some` or `!is_empty` (`only-weak`), `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/main.rs b/xtask/src/main.rs index f48f088aa8..addf9cb7e1 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -34,9 +34,10 @@ commands: brands check that user-visible text (labels, params docs, MCP, docs, packaging) names no other vendor's products cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails) test-lint [--base ] [--all] - fail on weak tests (unguarded .all(), only is_ok/is_some checks, no assertion, early - returns, unset env gates, sleeps...) in the lines changed since the base - (xtask/src/test_lint.rs); --all lists every hit by crate and never fails + weak tests in the lines changed since the base: fail on only is_ok/is_some checks, + self-compares, reasonless #[ignore] and sleeps; list unguarded .all(), no assertion, + early returns, unset env gates... (xtask/src/test_lint.rs); --all lists every hit + by crate and never fails i18n-report list the strings each language's catalog lacks, shown in English (fails only on a broken scan; ci runs it too) ui-commands regenerate crates/mcp/src/ui_catalog.rs from desktop UI_COMMANDS; --check fails on drift diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 8664403997..60363000fd 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -9,9 +9,15 @@ //! matches, with whole negations or `!=` comparisons joined only by `&&`, are left out). An earlier //! `assert_eq!`, `debug_assert_eq!` or `prop_assert_eq!` comparing a plain local receiver //! (optionally borrowed or viewed through `.as_slice()` or `[..]`) with a non-empty array -//! literal or `vec![…]` guards only that receiver. Non-empty array literals and plain local -//! names bound to them in the test, optionally through `.map(…)`, are also left out. Empty arrays -//! still count. A change anywhere in the test counts as a change to the hit; +//! literal or `vec![…]` guards only that receiver, and so does an assertion on a local bound to a +//! count, length or emptiness check. Collections that cannot be empty are also left out: +//! non-empty array literals; plain locals of the test bound to an array type of a positive length, +//! to a non-empty array literal or `vec![…]` or a literal range (lengths and repetition counts may +//! be `const`s of the file) followed only by methods that keep an item (`map`, `iter`, `rev`, +//! `collect` …), or filled by a `push` or `insert` on every pass of a loop over one, unless later +//! code may shrink or replace them; and fields the file declares only as arrays of a positive +//! length. `.windows(k)` and `.chunks_exact(k)` need `k` items. Empty arrays still count. A change +//! anywhere in the test counts as a change to the hit; //! * `only-weak`: every assertion is `is_ok()`, `is_some()`, `!is_empty()` or `len() > 0`, and the //! test calls no asserting helper; //! * `self-compare`: `assert_eq!(x, x)` or `assert_ne!(x, x)` on the same expression, when that @@ -50,6 +56,7 @@ //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the //! workspace by crate and rule, and does not fail. +use std::cell::OnceCell; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::path::Path; use std::process::Command; @@ -156,6 +163,11 @@ impl Rule { } } + /// Whether a hit on a changed line fails the command. The other rules only report. + pub fn fails(self) -> bool { + matches!(self, Rule::OnlyWeak | Rule::SelfCompare | Rule::IgnoreWithoutReason | Rule::Sleep) + } + fn from_id(id: &str) -> Option { Rule::ALL.into_iter().find(|r| r.id() == id) } @@ -254,20 +266,33 @@ impl Options { fn finish(counted: &[Hit], older: usize, files: usize, base: &str) -> Result<(), String> { let older = if older == 0 { String::new() } else { format!("; {older} hit(s) on unchanged lines of those files are not counted") }; - if counted.is_empty() { - println!("test-lint: no hits in the changed lines of {files} Rust file(s) since {base}{older}"); + let (failing, reported): (Vec<&Hit>, Vec<&Hit>) = counted.iter().partition(|h| h.rule.fails()); + if !reported.is_empty() { + println!( + "test-lint: {} hit(s) of report-only rules in the lines changed since {base} (they do not fail the check):\n {}", + reported.len(), + listing(&reported).join("\n ") + ); + } + if failing.is_empty() { + println!("test-lint: no failing hits in the changed lines of {files} Rust file(s) since {base}{older}"); return Ok(()); } - let mut out: Vec = counted.iter().map(Hit::show).collect(); - let rules: BTreeSet = counted.iter().map(|h| h.rule).collect(); - out.extend(rules.iter().map(|r| format!("{}: {}", r.id(), r.advice()))); Err(format!( "{} test-lint hit(s) in the lines changed since {base}{older} (exempt a line with `// {ALLOW} `):\n {}", - counted.len(), - out.join("\n ") + failing.len(), + listing(&failing).join("\n ") )) } +/// Each hit, then the advice for each rule they break. +fn listing(hits: &[&Hit]) -> Vec { + let mut out: Vec = hits.iter().map(|h| h.show()).collect(); + let rules: BTreeSet = hits.iter().map(|h| h.rule).collect(); + out.extend(rules.iter().map(|r| format!("{}: {}", r.id(), r.advice()))); + out +} + /// `--all`: counts by crate and rule, then every hit. fn report(hits: &[Hit], files: usize) -> String { let mut by_crate: BTreeMap> = BTreeMap::new(); @@ -1113,21 +1138,26 @@ impl View<'_> { const PLAIN_ASSERTS: &[&str] = &["assert", "debug_assert", "prop_assert"]; +/// Calls whose result says how many items a collection has. +const SIZE_CHECKS: &[&str] = &[".len()", ".is_empty()", ".count()", ".first()", ".any(", ".next()", ".last()"]; + fn all_unguarded(v: &View) -> Vec { let mut body = v.body_without_messages(); strip_all_predicates(&mut body); + let locals = bindings(&body); let checked = v.asserts.iter().any(|a| { a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { - let arg = norm(&body[from - v.t.open..to - v.t.open]); - [".len()", ".is_empty()", ".count()", ".first()", ".any(", ".next()", ".last()"].iter().any(|g| arg.contains(g)) + let (from, to) = (from - v.t.open, to - v.t.open); + SIZE_CHECKS.iter().any(|g| norm(&body[from..to]).contains(g)) || reads_counted_local(&body, &locals, from, to) }) }); - if checked || first_item_guard(&body) { + let sizes = Sizes { file: &v.file.m, consts: OnceCell::new() }; + if checked || first_item_guard(&body, &sizes) { return vec![]; } v.asserts .iter() - .filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && unguarded_all(&v.first_arg(a), &v.file.m[v.t.open..a.at])) + .filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && unguarded_all(&v.first_arg(a), &v.file.m[v.t.open..a.at], &sizes)) .map(|a| { let mut h = v.hit(a.at, Rule::AllUnguarded, format!("{}!(…all(…)) with no length or emptiness check in the test", a.name)); h.first = v.file.lines.of(v.t.attr); @@ -1157,10 +1187,10 @@ fn strip_all_predicates(body: &mut [u8]) { } /// Whether test code accesses a first item in a way that fails on an empty collection. -fn first_item_guard(body: &[u8]) -> bool { +fn first_item_guard(body: &[u8], sizes: &Sizes) -> bool { let compact = norm(body); let unwrapped = [".first().unwrap()", ".first().expect(", ".next().unwrap()", ".next().expect("]; - let indexed = compact.match_indices("[0]").any(|(at, _)| !on_array_literal(&compact[..at + 3])); + let indexed = compact.match_indices("[0]").any(|(at, _)| array_literal_len(&compact[..at + 3], sizes).is_none_or(|n| n == 0)); indexed || unwrapped.iter().any(|g| compact.contains(g)) || panicking_first_binding(body) } @@ -1179,27 +1209,27 @@ fn panicking_first_binding(body: &[u8]) -> bool { /// Whether a (masked, whitespace-free) condition holds an `.all(…)` that an empty collection would /// pass by mistake. Left out: a negated result, a closure that says no item matches (whole -/// negations or `!=` comparisons joined only by `&&`), and a non-empty array literal or a local -/// name bound to or previously compared equal to one. -fn unguarded_all(cond: &str, body: &[u8]) -> bool { - all_with_polarity(cond, true, body) +/// negations or `!=` comparisons joined only by `&&`), and a collection the test shows cannot be +/// empty ([`least_items`]). +fn unguarded_all(cond: &str, body: &[u8], sizes: &Sizes) -> bool { + all_with_polarity(cond, true, body, sizes) } /// Tracks negation through boolean operands and comparisons with `false`. -fn all_with_polarity(cond: &str, positive: bool, body: &[u8]) -> bool { +fn all_with_polarity(cond: &str, positive: bool, body: &[u8], sizes: &Sizes) -> bool { if cond.starts_with('(') && matching(cond.as_bytes(), 0) == Some(cond.len() - 1) { - return all_with_polarity(&cond[1..cond.len() - 1], positive, body); + return all_with_polarity(&cond[1..cond.len() - 1], positive, body, sizes); } if let Some(at) = boolean_split(cond) { - return all_with_polarity(&cond[..at], positive, body) || all_with_polarity(&cond[at + 2..], positive, body); + return all_with_polarity(&cond[..at], positive, body, sizes) || all_with_polarity(&cond[at + 2..], positive, body, sizes); } if let Some(expr) = cond.strip_suffix("==false").or_else(|| cond.strip_prefix("false==")) { - return all_with_polarity(expr, !positive, body); + return all_with_polarity(expr, !positive, body, sizes); } if let Some(expr) = cond.strip_prefix('!') { - return all_with_polarity(expr, !positive, body); + return all_with_polarity(expr, !positive, body, sizes); } - positive && positive_all(cond, body) + positive && positive_all(cond, body, sizes) } /// Finds a boolean operator outside parentheses, brackets and braces. @@ -1215,13 +1245,14 @@ fn boolean_split(cond: &str) -> Option { None } -fn positive_all(cond: &str, test_body: &[u8]) -> bool { +fn positive_all(cond: &str, test_body: &[u8], sizes: &Sizes) -> bool { cond.match_indices(".all(").any(|(i, _)| { let rest = &cond[i + ".all(".len()..]; let arg = &rest[..arg_end(rest)]; let body = arg.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(arg, |(_, body)| body); let none_match = not_equal_conjunction(body); - !none_match && !on_array_literal(&cond[..i]) && !on_bound_array(&cond[..i], test_body) && !on_equal_array(&cond[..i], test_body) + let (receiver, need) = receiver_need(&cond[..i], sizes); + !none_match && least_items(receiver, test_body, sizes) < need }) } @@ -1274,33 +1305,217 @@ fn whole_negation(body: &str) -> bool { !rest.is_empty() } -/// Whether an earlier equality assertion compares this plain local receiver with a non-empty literal. -fn on_equal_array(receiver: &str, body: &[u8]) -> bool { - let name = array_receiver(receiver); - if name.is_empty() || name.as_bytes()[0].is_ascii_digit() || !name.bytes().all(is_ident) { - return false; - } - macro_calls(body, 0, body.len()).iter().any(|a| { - if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) { - return false; +/// The fewest items the test shows `receiver` (the text before `.all(`, without its iterator +/// method) to have: a non-empty array literal, a plain local bound to one or to a sized +/// initializer ([`expr_len`]) or filled by a loop ([`loop_fill_len`]), a plain local an earlier +/// equality assertion compares with a non-empty literal, or a field the file declares as an +/// array of a positive length. 0 when the test does not show it. +fn least_items(receiver: &str, body: &[u8], sizes: &Sizes) -> usize { + let literal = array_literal_len(receiver, sizes).unwrap_or(0); + let derived = derived_locals(receiver, body).iter().map(|(d, from)| equal_len(d, body, sizes, Some(*from))).max().unwrap_or(0); + literal + .max(bound_len(receiver, body, sizes)) + .max(equal_len(receiver, body, sizes, None)) + .max(derived) + .max(field_len(receiver, sizes)) + .max(if binds(body, array_receiver(receiver).as_bytes()) { 0 } else { item_len(receiver, sizes) }) +} + +/// Whether `body` has a `let` binding of `name`. +fn binds(body: &[u8], name: &[u8]) -> bool { + words(body, b"let", 0, body.len()).into_iter().any(|at| { + let mut start = skip_ws(body, at + 3); + if body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace) { + start = skip_ws(body, start + 3); } - let Some(&(lf, lt)) = a.args.first() else { return false }; - let Some(&(rf, rt)) = a.args.get(1) else { return false }; - let (left, right) = (norm(&body[lf..lt]), norm(&body[rf..rt])); - (collection_operand(&left) == name && non_empty_literal(&right)) || (collection_operand(&right) == name && non_empty_literal(&left)) + body[start..].starts_with(name) && !body.get(start + name.len()).copied().is_some_and(is_ident) }) } +/// Methods that give at least one item for each distinct item they are given, and none from none, +/// with `collect` restricted to known collection targets. +const KEEPING: &[&str] = &["map", "iter", "into_iter", "cloned", "copied", "enumerate", "rev", "collect", "to_vec", "to_owned", "clone"]; + +/// Whether a normalized type names a collection that keeps an item of a non-empty iterator. +fn known_collection(ty: &str) -> bool { + let (name, args) = ty.split_once('<').map_or((ty, None), |(name, args)| (name, args.strip_suffix('>'))); + match name { + "Vec" | "std::vec::Vec" | "String" | "std::string::String" => true, + "Box" | "std::boxed::Box" => args.is_some_and(|args| { + args.starts_with('[') && matching(args.as_bytes(), 0) == Some(args.len() - 1) && !has_top_level(&args.as_bytes()[1..args.len() - 1], b';') + }), + _ => matches!( + name.strip_prefix("std::collections::").unwrap_or(name), + "VecDeque" | "HashSet" | "BTreeSet" | "HashMap" | "BTreeMap" | "BinaryHeap" | "LinkedList" + ), + } +} + +/// `operand` (masked, whitespace-free) without trailing calls of [`KEEPING`] methods: the +/// collection a compared or bound value was built from. Only the final call may use an +/// inferred `collect` target, when the caller knows it is a collection. +fn keeping_base(operand: &str, inferred_collect: bool) -> &str { + let mut op = operand; + while op.ends_with(')') { + let b = op.as_bytes(); + let mut depth = 0usize; + let Some(open) = (0..b.len()).rev().find(|&i| { + match b[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' => depth = depth.saturating_sub(1), + _ => {} + } + depth == 0 + }) else { + break; + }; + let mut head = &op[..open]; + let mut target = None; + if head.ends_with('>') { + let Some(turbofish) = head.rfind("::<") else { break }; + target = Some(&head[turbofish + 3..head.len() - 1]); + head = &head[..turbofish]; + } + let Some((rest, method)) = head.rsplit_once('.') else { break }; + if !KEEPING.contains(&method) || (method == "collect" && !target.map_or(inferred_collect && op.len() == operand.len(), known_collection)) { + break; + } + op = rest; + } + op +} + +/// Plain locals of the test bound (`let name = …;`, latest binding) to `receiver` through +/// [`KEEPING`] methods only, so they have no more distinct items than it, when no later code may +/// shrink or replace `receiver` ([`may_shrink`]), paired with the end of each binding. +fn derived_locals(receiver: &str, body: &[u8]) -> Vec<(String, usize)> { + let name = array_receiver(receiver); + if !plain_local(name) { + return vec![]; + } + let mut latest: HashMap = HashMap::new(); + for at in words(body, b"let", 0, body.len()) { + let mut start = skip_ws(body, at + 3); + if body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace) { + start = skip_ws(body, start + 3); + } + let end = start + body[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + if end == start || body[start].is_ascii_digit() { + continue; + } + let stop = statement_end(body, end); + let stmt = norm(&body[end..stop]); + let (annotation, from) = stmt.split_once('=').unwrap_or(("", "")); + let inferred_collect = annotation.strip_prefix(':').is_some_and(known_collection); + let base = keeping_base(from, inferred_collect); + let derived = base != from && collection_operand(base) == name && !may_shrink(body, name.as_bytes(), stop); + latest.insert(String::from_utf8_lossy(&body[start..end]).into_owned(), (derived, stop)); + } + latest.into_iter().filter(|&(_, (derived, _))| derived).map(|(n, (_, stop))| (n, stop)).collect() +} + +/// The length a `const` or `static` item of the file declares for a plain name +/// (`const NAME: [T; N]`), taking the smallest length across all declarations of that name, +/// or 0 when any declaration has an unknown or non-array type. +fn item_len(receiver: &str, sizes: &Sizes) -> usize { + let name = array_receiver(receiver); + if !plain_local(name) { + return 0; + } + let file = sizes.file; + let mut len = None; + for at in words(file, name.as_bytes(), 0, file.len()) { + let before = file[..at].trim_ascii_end(); + let before = before.strip_suffix(b"mut").map_or(before, |b| b.trim_ascii_end()); + let keyword = |w: &[u8]| before.ends_with(w) && !before.len().checked_sub(w.len() + 1).is_some_and(|j| is_ident(before[j])); + if !keyword(b"const") && !keyword(b"static") { + continue; + } + let colon = skip_ws(file, at + name.len()); + let ty = skip_ws(file, colon + 1); + if file.get(colon) != Some(&b':') || file.get(ty) != Some(&b'[') { + return 0; + } + let Some(close) = matching(file, ty) else { return 0 }; + let count = repeat_count(&file[ty + 1..close], sizes).unwrap_or(0); + len = Some(len.map_or(count, |n: usize| n.min(count))); + } + len.unwrap_or(0) +} + +/// The receiver without its iterator method and the items it needs for `.all(…)` to see one: +/// `.windows(k)` and `.chunks_exact(k)` need `k`, anything else one. An unknown `k` needs more +/// than any collection has. +fn receiver_need<'a>(receiver: &'a str, sizes: &Sizes) -> (&'a str, usize) { + let r = array_receiver(receiver); + for (method, exact) in [(".windows(", true), (".chunks_exact(", true), (".chunks(", false)] { + let Some(at) = r.rfind(method) else { continue }; + let open = at + method.len() - 1; + if matching(r.as_bytes(), open) != Some(r.len() - 1) { + continue; + } + let need = match sizes.count(&r[open + 1..r.len() - 1]) { + Some(k) if k > 0 => { + if exact { + k + } else { + 1 + } + } + _ => usize::MAX, + }; + return (array_receiver(&r[..at]), need); + } + (r, 1) +} + +/// The length of the non-empty literal an earlier equality assertion compares this plain local +/// receiver with, or 0. For a derived local, its binding must reach the assertion unchanged. +fn equal_len(receiver: &str, body: &[u8], sizes: &Sizes, binding: Option) -> usize { + let name = array_receiver(receiver); + if !plain_local(name) { + return 0; + } + let lens = macro_calls(body, 0, body.len()).into_iter().filter_map(|a| { + if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) { + return None; + } + let &(lf, lt) = a.args.first()?; + let &(rf, rt) = a.args.get(1)?; + if binding.is_some_and(|from| lf < from || may_change(&body[..lf], name.as_bytes(), from, false)) { + return None; + } + let end = a.args.last().map_or(rt, |&(_, to)| to); + if may_shrink(body, name.as_bytes(), end) { + return None; + } + let (left, right) = (norm(&body[lf..lt]), norm(&body[rf..rt])); + if collection_operand(keeping_base(&left, true)) == name { + Some(literal_len(&right, sizes)) + } else if collection_operand(keeping_base(&right, true)) == name { + Some(literal_len(&left, sizes)) + } else { + None + } + }); + lens.max().unwrap_or(0) +} + +/// Whether `name` is a plain local name: an identifier that does not start with a digit. +fn plain_local(name: &str) -> bool { + !name.is_empty() && !name.as_bytes()[0].is_ascii_digit() && name.bytes().all(is_ident) +} + /// Removes one borrow and a slice view from a compared operand. fn collection_operand(operand: &str) -> &str { let operand = operand.strip_prefix('&').unwrap_or(operand); operand.strip_suffix(".as_slice()").or_else(|| operand.strip_suffix("[..]")).unwrap_or(operand) } -/// Whether the whole operand is a non-empty array literal or `vec![…]`. -fn non_empty_literal(operand: &str) -> bool { +/// The length of an operand that is wholly an array literal or `vec![…]`, else 0. +fn literal_len(operand: &str, sizes: &Sizes) -> usize { let b = operand.strip_prefix("vec!").unwrap_or(operand).as_bytes(); - b.first() == Some(&b'[') && matching(b, 0) == Some(b.len() - 1) && non_empty_array(&b[1..b.len() - 1]) + if b.first() == Some(&b'[') && matching(b, 0) == Some(b.len() - 1) { array_len(&b[1..b.len() - 1], sizes) } else { 0 } } /// The length of a call's arguments in `rest`, the text after its `(`: up to its closing bracket. @@ -1318,13 +1533,13 @@ fn arg_end(rest: &str) -> usize { .unwrap_or(rest.len()) } -/// Whether `receiver` (the text before `.all(`) ends with a non-empty array literal, through `.iter()` or -/// `.into_iter()`. -fn on_array_literal(receiver: &str) -> bool { +/// The length of the array literal `receiver` (the text before `.all(`) ends with, through +/// `.iter()` or `.into_iter()`, or `None` when it does not end with one. +fn array_literal_len(receiver: &str, sizes: &Sizes) -> Option { let r = array_receiver(receiver); let b = r.as_bytes(); if b.last() != Some(&b']') { - return false; + return None; } let mut depth = 0usize; for (j, &c) in b.iter().enumerate().rev() { @@ -1334,13 +1549,13 @@ fn on_array_literal(receiver: &str) -> bool { depth = depth.saturating_sub(1); if depth == 0 { let literal = !j.checked_sub(1).and_then(|k| b.get(k)).is_some_and(|&p| is_ident(p) || matches!(p, b')' | b']' | b'.')); - return literal && non_empty_array(&b[j + 1..b.len() - 1]); + return literal.then(|| array_len(&b[j + 1..b.len() - 1], sizes)); } } _ => {} } } - false + None } /// Removes the iterator method from an array receiver. @@ -1348,68 +1563,455 @@ fn array_receiver(receiver: &str) -> &str { receiver.strip_suffix(".iter()").or_else(|| receiver.strip_suffix(".into_iter()")).unwrap_or(receiver) } -/// Whether a plain local receiver's latest preceding binding initializes a non-empty array. -fn on_bound_array(receiver: &str, body: &[u8]) -> bool { - let name = array_receiver(receiver).as_bytes(); - if name.is_empty() || name[0].is_ascii_digit() || !name.iter().copied().all(is_ident) { - return false; +/// The fewest items a plain local receiver has after its latest preceding binding: from the +/// binding ([`array_binding`]) or a loop that fills it ([`loop_fill_len`]), and 0 when a later +/// statement may shrink or replace it ([`may_shrink`]). +fn bound_len(receiver: &str, body: &[u8], sizes: &Sizes) -> usize { + let name = array_receiver(receiver); + if !plain_local(name) { + return 0; } - words(body, b"let", 0, body.len()).into_iter().rev().find_map(|at| array_binding(&body[at + 3..], name)).unwrap_or(false) + let name = name.as_bytes(); + let Some((len, end)) = words(body, b"let", 0, body.len()).into_iter().rev().find_map(|at| array_binding(body, at, name, sizes)) else { + return 0; + }; + if may_shrink(body, name, end) { + return 0; + } + len.max(loop_fill_len(body, name, end, sizes)) } -/// Checks a named binding, allowing `mut` and an array type annotation. -fn array_binding(mut rest: &[u8], name: &[u8]) -> Option { - rest = rest.trim_ascii_start(); - if rest.starts_with(b"mut") && rest.get(3).is_some_and(u8::is_ascii_whitespace) { - rest = rest[3..].trim_ascii_start(); +/// For a `let` at `at` that binds `name` (allowing `mut`): the fewest items its array type +/// annotation gives (which decides when there is one), else its initializer gives ([`expr_len`]), +/// and where the statement ends. `None` for a binding of another name. +fn array_binding(body: &[u8], at: usize, name: &[u8], sizes: &Sizes) -> Option<(usize, usize)> { + let mut at = skip_ws(body, at + 3); + if body[at..].starts_with(b"mut") && body.get(at + 3).is_some_and(u8::is_ascii_whitespace) { + at = skip_ws(body, at + 3); } - let end = rest.iter().copied().take_while(|&c| is_ident(c)).count(); - if &rest[..end] != name { + let end = at + body[at..].iter().copied().take_while(|&c| is_ident(c)).count(); + if &body[at..end] != name { return None; } - rest = rest[end..].trim_ascii_start(); - if let Some(annotation) = rest.strip_prefix(b":") { - let annotation = annotation.trim_ascii_start(); - let close = (annotation.first() == Some(&b'[')).then(|| matching(annotation, 0)).flatten(); - let Some(close) = close else { return Some(false) }; - rest = annotation[close + 1..].trim_ascii_start(); + let stop = statement_end(body, end); + let stmt = &body[end..stop]; + let eq = (0..stmt.len()).find(|&i| { + stmt[i] == b'=' + && !matches!(stmt.get(i + 1), Some(b'=' | b'>')) + && !matches!(i.checked_sub(1).map(|j| stmt[j]), Some(b'=' | b'!' | b'<' | b'>')) + }); + let (annotation, init) = match eq { + Some(eq) => (&stmt[..eq], Some(&stmt[eq + 1..])), + None => (stmt, None), + }; + let annotation = norm(annotation); + if let Some(ty) = annotation.strip_prefix(':') + && ty.starts_with('[') + && matching(ty.as_bytes(), 0) == Some(ty.len() - 1) + { + return Some((repeat_count(&ty.as_bytes()[1..ty.len() - 1], sizes).unwrap_or(0), stop)); } - Some(rest.strip_prefix(b"=").is_some_and(array_initializer)) + Some((init.map_or(0, |init| expr_len(&norm(init), sizes, annotation.strip_prefix(':').unwrap_or(""))), stop)) } -/// Whether an initializer is a non-empty array literal, optionally followed by one `.map(…)`. -fn array_initializer(rest: &[u8]) -> bool { - let rest = rest.trim_ascii_start(); - let Some(close) = (rest.first() == Some(&b'[')).then(|| matching(rest, 0)).flatten() else { return false }; - if !non_empty_array(&rest[1..close]) { - return false; - } - let tail = rest[close + 1..].trim_ascii_start(); - if tail.starts_with(b";") { - return true; - } - let compact = norm(tail); - if !compact.starts_with(".map(") { - return false; - } - let Some(close) = matching(compact.as_bytes(), 4) else { return false }; - compact[close + 1..].starts_with(';') -} - -/// Whether an array's masked contents have an element and, for repetition, a positive literal count. -fn non_empty_array(contents: &[u8]) -> bool { - let mut at = 0; - while at < contents.len() { - match contents[at] { - b';' => return norm(&contents[at + 1..]).parse::().is_ok_and(|count| count > 0), - b'(' | b'[' | b'{' => { - let Some(close) = matching(contents, at) else { return false }; - at = close + 1; - } +/// The index of the `;` that ends the statement starting at `from`, outside brackets, or the +/// end of `body`. +fn statement_end(body: &[u8], from: usize) -> usize { + let mut at = from; + while at < body.len() { + match body[at] { + b';' => return at, + b'(' | b'[' | b'{' => match matching(body, at) { + Some(close) => at = close + 1, + None => return body.len(), + }, _ => at += 1, } } - !contents.trim_ascii().is_empty() + body.len() +} + +/// The fewest items a (masked, whitespace-free) expression yields: an array literal or `vec![…]`, +/// a literal range, either followed only by methods that keep at least one item of a non-empty +/// input (`map`, `iter`, `into_iter`, `cloned`, `copied`, `enumerate`, `rev`, `chain`, `to_vec`, +/// `to_owned`, `clone`, and `collect` into a known collection or `step_by`, after which at least +/// one is known). Only a final `collect` without a turbofish can use the binding's type. 0 for +/// anything else. +fn expr_len(e: &str, sizes: &Sizes, binding_type: &str) -> usize { + let e = e.strip_prefix("vec!").unwrap_or(e); + let b = e.as_bytes(); + let (mut n, mut rest) = match b.first() { + Some(b'[') => { + let Some(close) = matching(b, 0) else { return 0 }; + (array_len(&b[1..close], sizes), &e[close + 1..]) + } + Some(b'(') => { + let Some(close) = matching(b, 0) else { return 0 }; + (range_len(&e[1..close], sizes), &e[close + 1..]) + } + _ => return range_len(e, sizes), + }; + while !rest.is_empty() { + let Some(tail) = rest.strip_prefix('.') else { return 0 }; + let end = tail.bytes().take_while(|&c| is_ident(c)).count(); + let method = &tail[..end]; + let mut open = end; + if tail[open..].starts_with("::<") { + let mut depth = 0usize; + let Some(close) = tail[open + 2..].bytes().position(|c| { + depth = match c { + b'<' => depth + 1, + b'>' => depth.saturating_sub(1), + _ => depth, + }; + depth == 0 + }) else { + return 0; + }; + open += 2 + close + 1; + } + if tail.as_bytes().get(open) != Some(&b'(') { + return 0; + } + let Some(close) = matching(tail.as_bytes(), open) else { return 0 }; + match method { + "map" | "iter" | "into_iter" | "cloned" | "copied" | "enumerate" | "rev" | "chain" | "to_vec" | "to_owned" | "clone" => {} + "collect" => { + let target = if open > end { + &tail[end + 3..open - 1] + } else if close + 1 == tail.len() { + binding_type + } else { + "" + }; + if !known_collection(target) { + return 0; + } + n = n.min(1); + } + "step_by" => n = n.min(1), + _ => return 0, + } + rest = &tail[close + 1..]; + } + n +} + +/// The number of items in a range of integer literals or constants (`a..b`, `a..=b`); 0 for +/// anything else, an open range included. +fn range_len(e: &str, sizes: &Sizes) -> usize { + let (lo, hi, inclusive) = match e.split_once("..=") { + Some((lo, hi)) => (lo, hi, true), + None => match e.split_once("..") { + Some((lo, hi)) => (lo, hi, false), + None => return 0, + }, + }; + let value = |t: &str| match t.strip_prefix('-') { + Some(t) => sizes.count(t).and_then(|v| i128::try_from(v).ok()).map(|v| -v), + None => sizes.count(t).and_then(|v| i128::try_from(v).ok()), + }; + let (Some(lo), Some(hi)) = (value(lo), value(hi)) else { return 0 }; + let len = hi - lo + i128::from(inclusive); + usize::try_from(len).unwrap_or(0) +} + +/// The number of items in an array literal's masked contents: the count of a repetition, or the +/// elements of a list. +fn array_len(contents: &[u8], sizes: &Sizes) -> usize { + if let Some(count) = repeat_count(contents, sizes) { + return count; + } + if has_top_level(contents, b';') { + return 0; + } + split_args(contents, 0, contents.len()).len() +} + +/// The count of a repetition `[x; N]` (a literal or a `const` of the file), from its masked +/// contents; `None` when they are not a repetition, `Some(0)` when the count is not known. +fn repeat_count(contents: &[u8], sizes: &Sizes) -> Option { + let mut at = 0; + while at < contents.len() { + match contents[at] { + b';' => return Some(sizes.count(&norm(&contents[at + 1..])).unwrap_or(0)), + b'(' | b'[' | b'{' => at = matching(contents, at)? + 1, + _ => at += 1, + } + } + None +} + +/// Whether `c` occurs in `b` outside brackets. +fn has_top_level(b: &[u8], c: u8) -> bool { + let mut at = 0; + while at < b.len() { + match b[at] { + x if x == c => return true, + b'(' | b'[' | b'{' => match matching(b, at) { + Some(close) => at = close + 1, + None => return true, + }, + _ => at += 1, + } + } + false +} + +/// The fewest items a `for` loop after `from`, in the same block, adds to `name`: a loop over a +/// sized source ([`expr_len`]) whose own block (not a nested one) pushes or inserts into `name` +/// on every pass, with no `break`, `continue`, `return` or `?` in the loop. 0 when there is none. +fn loop_fill_len(body: &[u8], name: &[u8], from: usize, sizes: &Sizes) -> usize { + let mut best = 0; + for at in words(body, b"for", from, body.len()) { + if block_depth(&body[from..at]) != Some(0) { + continue; + } + let Some(&in_at) = words(body, b"in", at + 3, body.len()).first() else { continue }; + let Some(open) = (in_at + 2..body.len()).find(|&i| body[i] == b'{' && !has_open_bracket(&body[in_at + 2..i])) else { continue }; + let Some(close) = matching(body, open) else { continue }; + let source = expr_len(&norm(&body[in_at + 2..open]), sizes, ""); + let block = &body[open + 1..close]; + let exits = [&b"break"[..], b"continue", b"return"].iter().any(|w| !words(block, w, 0, block.len()).is_empty()) || contains(block, b"?"); + if source == 0 || exits { + continue; + } + let pushes = words(block, name, 0, block.len()).into_iter().any(|p| { + let before = block[..p].trim_ascii_end(); + let statement = matches!(before.last(), None | Some(b';' | b'{' | b'}')); + let call = norm(&block[p + name.len()..block.len().min(p + name.len() + 16)]); + statement && block_depth(&block[..p]) == Some(0) && [".push(", ".push_back(", ".insert("].iter().any(|m| call.starts_with(m)) + }); + if pushes { + best = best.max(source); + } + } + best +} + +/// The brace depth at the end of `b`, or `None` when it closes a block it did not open. +fn block_depth(b: &[u8]) -> Option { + let mut depth = 0usize; + for &c in b { + match c { + b'{' => depth += 1, + b'}' => depth = depth.checked_sub(1)?, + _ => {} + } + } + Some(depth) +} + +/// Whether `b` leaves a `(` or `[` open. +fn has_open_bracket(b: &[u8]) -> bool { + let mut depth = 0i32; + for &c in b { + match c { + b'(' | b'[' => depth += 1, + b')' | b']' => depth -= 1, + _ => {} + } + } + depth > 0 +} + +/// Whether code after `from` may remove items from `name` or replace it. +fn may_shrink(body: &[u8], name: &[u8], from: usize) -> bool { + may_change(body, name, from, true) +} + +/// Whether code after `from` may change the item count of `name`: an unknown method call, +/// an assignment, or a `&mut` borrow. Growth is harmless only for the source collection. +fn may_change(body: &[u8], name: &[u8], from: usize, allow_growth: bool) -> bool { + const PRESERVING: &[&str] = &[ + "iter", + "iter_mut", + "into_iter", + "len", + "is_empty", + "contains", + "get", + "get_mut", + "first", + "last", + "first_mut", + "last_mut", + "as_slice", + "as_ref", + "clone", + "to_vec", + "to_owned", + "windows", + "chunks", + "chunks_exact", + "sort", + "sort_by", + "sort_by_key", + "sort_unstable", + "sort_unstable_by", + "sort_unstable_by_key", + "reverse", + "binary_search", + "binary_search_by", + "binary_search_by_key", + "starts_with", + "ends_with", + "map", + "concat", + "join", + "keys", + "values", + ]; + const ADDING: &[&str] = &["push", "push_back", "push_front", "insert", "extend"]; + words(body, name, from, body.len()).into_iter().any(|p| { + let after = &body[skip_ws(body, p + name.len())..]; + let assigned = (after.starts_with(b"=") && !after.starts_with(b"==") && !after.starts_with(b"=>")) + || ["+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="].iter().any(|op| after.starts_with(op.as_bytes())); + let before = body[from..p].trim_ascii_end(); + let borrowed = before.strip_suffix(b"mut").is_some_and(|b| b.trim_ascii_end().ends_with(b"&")); + let called = if after.first() == Some(&b'.') { + let start = skip_ws(after, 1); + let end = start + after[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + let rest = &after[skip_ws(after, end)..]; + let method = &after[start..end]; + (rest.starts_with(b"(") || rest.starts_with(b"::<")) + && !PRESERVING.iter().any(|m| method == m.as_bytes()) + && !(allow_growth && ADDING.iter().any(|m| method == m.as_bytes())) + } else { + false + }; + assigned || borrowed || called + }) +} + +/// The length of a field the file declares as an array of a positive length (`name: [T; N]`), +/// for a receiver `….name`. 0 when any other `name:` in the file may start a type: anything but +/// an array, a lowercase name that is not a path or a primitive type (a value in a struct +/// expression), or a literal. +fn field_len(receiver: &str, sizes: &Sizes) -> usize { + let Some((owner, field)) = receiver.rsplit_once('.') else { return 0 }; + if owner.is_empty() || !plain_local(field) { + return 0; + } + const PRIMITIVE: &[&str] = &[ + "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "f32", "f64", "bool", "char", "str", "dyn", "impl", + "fn", "mut", "crate", "self", "super", + ]; + let file = sizes.file; + let mut least: Option = None; + for at in words(file, field.as_bytes(), 0, file.len()) { + let colon = skip_ws(file, at + field.len()); + if file.get(colon) != Some(&b':') || file.get(colon + 1) == Some(&b':') || at.checked_sub(1).is_some_and(|j| file[j] == b':') { + continue; + } + let ty = skip_ws(file, colon + 1); + let word_end = ty + file[ty..].iter().copied().take_while(|&c| is_ident(c)).count(); + let word = &file[ty..word_end]; + let value = match file.get(ty) { + Some(b'[') => false, + Some(c) if c.is_ascii_digit() || matches!(c, b'"' | b'\'' | b'-') => true, + Some(c) if c.is_ascii_lowercase() || *c == b'_' => { + let path = file[skip_ws(file, word_end)..].starts_with(b"::"); + !path && !PRIMITIVE.iter().any(|p| p.as_bytes() == word) + } + _ => return 0, + }; + if value { + continue; + } + let Some(close) = matching(file, ty) else { return 0 }; + match repeat_count(&file[ty + 1..close], sizes) { + Some(n) if n > 0 => least = Some(least.map_or(n, |l| l.min(n))), + Some(_) => return 0, + None => {} + } + } + least.unwrap_or(0) +} + +/// What the rules know about collection sizes in one masked file: its `const` counts, read on first use. +struct Sizes<'a> { + file: &'a [u8], + consts: OnceCell>, +} + +impl Sizes<'_> { + /// An unsigned integer literal (with `_` and an integer suffix allowed) or a `const` of the + /// file whose value is one. + fn count(&self, text: &str) -> Option { + int_literal(text).or_else(|| self.consts.get_or_init(|| file_consts(self.file)).get(text).copied()) + } +} + +fn int_literal(text: &str) -> Option { + let digits = text.bytes().take_while(|c| c.is_ascii_digit() || *c == b'_').count(); + let suffix = &text[digits..]; + let suffixes = ["", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize"]; + if digits == 0 || !text.as_bytes()[0].is_ascii_digit() || !suffixes.contains(&suffix) { + return None; + } + text[..digits].replace('_', "").parse().ok() +} + +/// `const NAME: T = ;` in a masked file; a name declared more than once keeps +/// its smallest value, and 0 when one of its values is not a literal. +fn file_consts(file: &[u8]) -> HashMap { + let mut out: HashMap = HashMap::new(); + for at in words(file, b"const", 0, file.len()) { + let start = skip_ws(file, at + 5); + let end = start + file[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + if end == start || skip_ws(file, end) >= file.len() || file[skip_ws(file, end)] != b':' { + continue; + } + let stop = statement_end(file, end); + let stmt = norm(&file[end..stop]); + let Some((_, value)) = stmt.split_once('=') else { continue }; + let value = int_literal(value).unwrap_or(0); + let name = String::from_utf8_lossy(&file[start..end]).into_owned(); + let slot = out.entry(name).or_insert(value); + *slot = (*slot).min(value); + } + out +} + +/// A `let` of a plain name: the name, where the statement ends, and whether it binds an expression +/// that checks a size ([`SIZE_CHECKS`]). +struct Binding { + name: Vec, + end: usize, + counts: bool, +} + +/// Every `let` of a plain name in `body`, in order. +fn bindings(body: &[u8]) -> Vec { + words(body, b"let", 0, body.len()) + .into_iter() + .filter_map(|at| { + let mut start = skip_ws(body, at + 3); + if body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace) { + start = skip_ws(body, start + 3); + } + let end = start + body[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + if end == start || body[start].is_ascii_digit() { + return None; + } + let stop = statement_end(body, end); + let stmt = norm(&body[end..stop]); + let counts = stmt.split_once('=').is_some_and(|(_, init)| SIZE_CHECKS.iter().any(|g| init.contains(g))); + Some(Binding { name: body[start..end].to_vec(), end: stop, counts }) + }) + .collect() +} + +/// Whether `body[from..to]` (an assertion operand) reads a local whose binding reaching that +/// point checks a size and was not assigned since. +fn reads_counted_local(body: &[u8], all: &[Binding], from: usize, to: usize) -> bool { + all.iter().filter(|b| b.counts && b.name != b"_").any(|b| { + words(body, &b.name, from, to).into_iter().any(|p| { + let reaching = all.iter().rfind(|o| o.name == b.name && o.end <= p); + reaching.is_some_and(|r| r.counts && !may_shrink(&body[..p], &r.name, r.end)) + }) + }) } /// Whether an assertion's (masked, whitespace-free) condition only says that there is a value. @@ -1803,7 +2405,7 @@ mod tests { let src = format!("#[test]\nfn t() {{\n assert_eq!(xs, {expected});\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); assert_eq!(hits(&src), [(4, "all-unguarded")], "{expected}"); } - for operand in ["ys", "xs_other", "other.xs", "other::xs", "xs()", "xs.clone()", "xs[1..]", "&&xs"] { + for operand in ["ys", "xs_other", "other.xs", "other::xs", "xs()", "xs.filter(f)", "xs.iter().filter(f).collect()", "xs[1..]", "&&xs"] { let src = format!("#[test]\nfn t() {{\n assert_eq!({operand}, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); assert_eq!(hits(&src), [(4, "all-unguarded")], "{operand}"); } @@ -1913,12 +2515,23 @@ mod tests { "[]", "[1; 0]", "[1; 0].map(|x| x + 1)", - "vec![1, 2]", + "vec![]", + "vec![1; 0]", + "vec![1; n]", "items()", "items().collect()", + "items().collect::>()", + "(0..0).collect::>()", + "(3..1).collect::>()", + "(0..n).collect::>()", + "(0..).take(3).collect::>()", + "[1, 2].iter().filter(|x| keep(x)).collect::>()", + "[1, 2].into_iter().zip(ys).collect::>()", + "[None::].into_iter().collect::>>()", + "[Err::(error())].into_iter().collect::, E>>()", "[1, 2].into_iter().collect()", - "[1, 2].map(|x| x + 1).into_iter().collect()", - "[1, 2].map(|x| x + 1).map(|x| x + 1)", + "[1, 2].into_iter().collect::()", + "[1, 2].into_iter().collect::>()", ] { for binding in [format!("let xs = {value};"), format!("let mut xs = {value};"), format!("let xs: [u8; 0] = {value};")] { let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); @@ -1976,6 +2589,333 @@ mod tests { } } + #[test] + fn all_skips_bindings_with_sized_initializers() { + let consts = "const N: usize = 3;\nconst NONE: usize = 0;\n"; + for binding in [ + "let xs = vec![1, 2];", + "let mut xs = vec![[1, 2]; 2];", + "let xs: Vec<_> = [1, 2].into_iter().collect();", + "let xs = [1, 2].map(|x| x + 1).map(|x| x + 1);", + "let xs: Vec = [1, 2].iter().copied().rev().collect();", + "let xs: Vec = (0..40u8).map(|n| px(n)).collect();", + "let xs = (1..=3).collect::>();", + "let xs = (-2..1).step_by(2).collect::>();", + "let xs: Vec<_> = (0..N).collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect::>().into_iter().collect();", + "let xs = [0.0; N];", + "let xs: [u8; 3] = items();", + "let xs: [u8; N] = items();", + ] { + let src = format!("{consts}#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding}"); + let cleared = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&cleared), [(7, "all-unguarded")], "{binding} then cleared"); + } + for binding in [ + "let xs = (0..NONE).collect::>();", + "let xs = [0.0; NONE];", + "let xs: [u8; NONE] = [1];", + "let xs = (0..M).collect::>();", + "let xs = [None::].into_iter().collect::>>();", + "let xs = [Err::(error())].into_iter().collect::, E>>();", + "let xs: Option> = [1].into_iter().collect();", + "let xs: Result, E> = [1].into_iter().collect();", + "let xs = [1, 2].into_iter().collect();", + "let xs: Items = [1, 2].into_iter().collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect().clone();", + "let xs: Vec<_> = [1, 2].into_iter().collect().into_iter().collect();", + "let xs: Vec<_> = [None::].into_iter().collect::>>().into_iter().collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect::();", + ] { + let src = format!("{consts}#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(6, "all-unguarded")], "{binding}"); + } + for later in [ + "xs.retain(|x| keep(x));", + "xs = items();", + "take(&mut xs);", + "xs.truncate(0);", + "xs.pop();", + "xs.resize(0, 0);", + "xs.resize_with(0, f);", + "xs.pop_front();", + "xs.pop_back();", + "xs.unknown_method_that_may_shrink();", + "xs . unknown::();", + ] { + let src = format!("#[test]\nfn t() {{\n let mut xs = vec![1, 2];\n {later}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{later}"); + } + for op in ["+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="] { + let src = + format!("#[test]\nfn t() {{\n let mut xs = vec![1, 2];\n xs {op} other;\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{op}"); + } + for later in [ + "xs[0] = 5; use_it(&xs);", + "xs[1] = 5; use_it(&xs);", + "use_it(&xs);", + "use_it(xs);", + "use_it(xs == other);", + "match other { xs => use_it(xs), _ => () };", + "xs.push(3); xs.push_back(4); xs.push_front(5); xs.insert(0, 6); xs.extend(other);", + "xs.sort(); xs.sort_by(f); xs.sort_by_key(f); xs.sort_unstable(); xs.reverse();", + "use_it(xs.iter()); use_it(xs.iter_mut()); use_it(xs.into_iter());", + "use_it(xs.len()); use_it(xs.is_empty()); use_it(xs.contains(&1));", + "use_it(xs.get(0)); use_it(xs.get_mut(0)); use_it(xs.first()); use_it(xs.last());", + "use_it(xs.first_mut()); use_it(xs.last_mut()); use_it(xs.as_slice()); use_it(xs.as_ref());", + "use_it(xs.clone()); use_it(xs.to_vec()); use_it(xs.windows(2)); use_it(xs.chunks(2));", + "use_it(xs.binary_search(&1)); use_it(xs.starts_with(&[1])); use_it(xs.ends_with(&[2]));", + "use_it(xs.map(f)); use_it(xs.concat()); use_it(xs.join(sep)); use_it(xs.keys()); use_it(xs.values());", + ] { + let src = format!("#[test]\nfn t() {{\n let mut xs = vec![1, 2];\n {later}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{later}"); + } + } + + #[test] + fn all_collects_require_known_collection_targets() { + for target in [ + "Vec<_>", + "std::vec::Vec<_>", + "VecDeque<_>", + "std::collections::VecDeque<_>", + "HashSet<_>", + "std::collections::HashSet<_>", + "BTreeSet<_>", + "std::collections::BTreeSet<_>", + "HashMap<_, _>", + "std::collections::HashMap<_, _>", + "BTreeMap<_, _>", + "std::collections::BTreeMap<_, _>", + "BinaryHeap<_>", + "std::collections::BinaryHeap<_>", + "LinkedList<_>", + "std::collections::LinkedList<_>", + "String", + "std::string::String", + "Box<[_]>", + "std::boxed::Box<[_]>", + ] { + let source = if target.contains("Map") { "[(1, 2)]" } else { "['a', 'b']" }; + for binding in [ + format!("let xs = {source}.into_iter().collect::<{target}>();"), + format!("let xs: {target} = {source}.into_iter().collect();"), + format!("let xs = {source}.into_iter().collect::<{target}>().into_iter().collect::>();"), + ] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding}"); + } + } + } + + #[test] + fn all_skips_collections_every_pass_of_a_sized_loop_fills() { + for (source, fill) in [ + ("[1, 2, 3]", "xs.push(i);"), + ("0..3", "xs.push(i);"), + ("[[0, 1], [1, 0]]", "let s = Fill { a: 1 }.span(i);\n xs.push(s);"), + ("[1, 2].iter().enumerate()", "for j in items() { use_it(j); }\n xs.insert(i);"), + ] { + let src = format!( + "#[test]\nfn t() {{\n let mut xs = vec![];\n for i in {source} {{\n {fill}\n }}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [], "{source}: {fill}"); + let after = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&after), [(line + 1, "all-unguarded")], "{source} then cleared"); + } + for (source, fill) in [ + ("items()", "xs.push(i);"), + ("0..0", "xs.push(i);"), + ("0..n", "xs.push(i);"), + ("[1, 2]", "if keep(i) { xs.push(i); }"), + ("[1, 2]", "if !keep(i) { continue; }\n xs.push(i);"), + ("[1, 2]", "let v = get(i)?;\n xs.push(v);"), + ("[1, 2]", "ys.iter().for_each(|y| xs.push(*y));"), + ("[1, 2]", "ys.push(i);"), + ("[1, 2]", "let mut xs = vec![];\n xs.push(i);"), + ("[1, 2].iter().filter(|x| keep(x))", "xs.push(i);"), + ] { + let src = format!( + "#[test]\nfn t() {{\n let mut xs = vec![];\n for i in {source} {{\n {fill}\n }}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [(line, "all-unguarded")], "{source}: {fill}"); + } + let nested = "#[test]\nfn t() {\n let mut xs = vec![];\n if ready() {\n for i in [1, 2] {\n xs.push(i);\n }\n }\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(nested), [(9, "all-unguarded")], "a loop that may not run"); + } + + #[test] + fn all_skips_fields_the_file_declares_as_arrays() { + let test = "#[test]\nfn t() {\n let c = parse();\n assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v)));\n}\n"; + for decl in [ + "struct C { rgb: [f32; 3] }\n", + "const N: usize = 3;\nstruct C { pub rgb: [f32; N], alpha: Option }\n", + "struct C { rgb: [f32; 3] }\nfn c() -> C { C { rgb: rgb_of(\"x\"), alpha: 1 } }\n", + ] { + let src = format!("{decl}{test}"); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [], "{decl}"); + let other = format!("{decl}struct D {{ rgb: Vec }}\n{test}"); + assert_eq!(hits(&other), [(line + 1, "all-unguarded")], "another struct's rgb can be empty"); + } + for decl in + ["struct C { rgb: [f32; 0] }\n", "struct C { rgb: &'static [f32] }\n", "struct C { rgb: [f32; LEN] }\n", "struct C { other: [f32; 3] }\n"] + { + let src = format!("{decl}{test}"); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{decl}"); + } + for other in ["std::vec::Vec", "Pixels", "u8", "(f32, f32)", "T"] { + let src = format!("struct C {{ rgb: [f32; 3] }}\nstruct D {{ rgb: {other} }}\n{test}"); + assert_eq!(hits(&src), [(6, "all-unguarded")], "another struct's rgb is {other}"); + } + let local = "struct C { rgb: [f32; 3] }\n#[test]\nfn t() {\n let rgb = parse();\n assert!(rgb.iter().all(|v| valid(v)));\n}\n"; + assert_eq!(hits(local), [(5, "all-unguarded")], "a local name is not the field"); + } + + #[test] + fn all_equality_guards_follow_methods_that_keep_items() { + for operand in [ + "xs.clone()", + "xs.iter().map(|l| l.0).collect()", + "xs.iter().copied().collect::>().into_iter().collect()", + "xs.iter().map(|l| l.0).collect::>()", + "&xs.iter().copied().rev().collect::>()", + ] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({operand}, vec![0, 7]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{operand}"); + let cleared = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&cleared), [(5, "all-unguarded")], "{operand} then cleared"); + } + for (binding, compared) in [ + ("let ids: Vec<&str> = xs.iter().map(|l| l.id()).collect();", "assert_eq!(ids, [\"a\", \"b\"]);"), + ("let ids = xs.iter().cloned().collect::>();", "assert_eq!([\"a\"], ids);"), + ("let ids = xs.iter().copied().collect::>();", "assert_eq!(ids, [1]);"), + ("let ids: Vec<_> = xs.iter().copied().collect::>().into_iter().collect();", "assert_eq!(ids, [1]);"), + ] { + let src = format!("#[test]\nfn t() {{\n {binding}\n {compared}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding}"); + let filtered = src.replace(binding, &binding.replace(".iter()", ".iter().filter(|x| keep(x))")); + assert_eq!(hits(&filtered), [(5, "all-unguarded")], "{binding} through a filter"); + let rebound = src.replace(&format!(" {compared}\n"), &format!(" let ids = other();\n {compared}\n")); + assert_eq!(hits(&rebound), [(6, "all-unguarded")], "{binding} then bound again"); + for change in ["ids = vec![1];", "ids.clear();", "reset(&mut ids);", "ids.push(1);"] { + let reassigned = + src.replace("let ids", "let mut ids").replace(&format!(" {compared}\n"), &format!(" {change}\n {compared}\n")); + assert_eq!(hits(&reassigned), [(6, "all-unguarded")], "{binding} then {change}"); + } + let cleared = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&cleared), [(6, "all-unguarded")], "{binding} then the source cleared"); + } + } + + #[test] + fn all_equality_guards_stop_at_other_collect_targets() { + for operand in [ + "xs.iter().copied().collect().into_iter().collect::>()", + "xs.iter().copied().collect().into_iter().collect()", + "xs.iter().copied().collect().clone()", + ] { + for compared in [format!("{operand}, [vec![]]"), format!("[vec![]], {operand}")] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({compared});\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{compared}"); + } + } + for binding in [ + "let ids: Option> = xs.iter().copied().collect();", + "let ids: Result, E> = xs.iter().copied().collect();", + "let ids: Items = xs.iter().copied().collect();", + "let ids = xs.iter().copied().collect();", + "let ids: Vec<_> = xs.iter().copied().collect().into_iter().collect();", + "let ids: Vec<_> = xs.iter().copied().collect().into_iter().collect::>();", + "let ids: Vec<_> = xs.iter().copied().collect().clone();", + ] { + let src = format!( + "#[test]\nfn t() {{\n {binding}\n assert_eq!(ids.into_iter().collect::>(), [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{binding}"); + } + for target in ["Option>", "Result, E>", "Items"] { + let operand = format!("xs.iter().copied().collect::<{target}>().iter().collect::>()"); + let direct = format!("#[test]\nfn t() {{\n assert_eq!({operand}, [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&direct), [(4, "all-unguarded")], "{target} compared directly"); + let derived = format!( + "#[test]\nfn t() {{\n let ids = {operand};\n assert_eq!(ids, [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + assert_eq!(hits(&derived), [(5, "all-unguarded")], "{target} through a local"); + } + } + + #[test] + fn all_skips_const_and_static_arrays_of_the_file() { + let test = "#[test]\nfn t() {\n assert!(NAMES.iter().all(|n| valid(n)));\n}\n"; + for decl in [ + "const NAMES: [&str; 2] = [\"a\", \"b\"];\n", + "static NAMES: [u8; N] = [0; N];\nconst N: usize = 4;\n", + "pub(crate) static mut NAMES: [u8; 1] = [0];\n", + ] { + let src = format!("{decl}{test}"); + assert_eq!(hits(&src), [], "{decl}"); + } + for decl in ["const NAMES: [&str; 0] = [];\n", "const NAMES: &[&str] = &[\"a\"];\n", "fn my_const() {}\nlet NAMES: [u8; 2] = f();\n", ""] { + let src = format!("{decl}{test}"); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [(line, "all-unguarded")], "{decl}"); + } + let shadowed = "const NAMES: [&str; 2] = [\"a\", \"b\"];\n#[test]\nfn t() {\n let NAMES = items();\n assert!(NAMES.iter().all(|n| valid(n)));\n}\n"; + assert_eq!(hits(shadowed), [(5, "all-unguarded")], "a local of the same name"); + for (other_type, other_value, found) in [("[u8; 0]", "[]", true), ("&[u8]", "&[]", true), ("[u8; 3]", "[0; 3]", false)] { + for (first_type, first_value, second_type, second_value) in + [("[u8; 2]", "[0; 2]", other_type, other_value), (other_type, other_value, "[u8; 2]", "[0; 2]")] + { + let src = format!( + "mod a {{ const CASES: {first_type} = {first_value}; }}\nmod b {{\nconst CASES: {second_type} = {second_value};\n#[test]\nfn t() {{\n assert!(CASES.iter().all(|n| valid(n)));\n}}\n}}\n" + ); + let want: &[(usize, &str)] = if found { &[(6, "all-unguarded")] } else { &[] }; + assert_eq!(hits(&src), want, "{first_type} and {second_type}"); + } + } + } + + #[test] + fn all_windows_need_as_many_items_as_their_size() { + for (array, method, found) in [ + ("[a, b, c, d]", "windows(2)", false), + ("[a, b]", "windows(2)", false), + ("[a]", "windows(2)", true), + ("[a, b]", "windows(k)", true), + ("[a]", "chunks(3)", false), + ("[a, b]", "chunks_exact(3)", true), + ("[a, b, c]", "chunks_exact(3)", false), + ] { + let src = + format!("#[test]\nfn t() {{\n let xs = {array}.map(|s| node(s));\n assert!(xs.{method}.all(|w| w[0].y == w[1].y));\n}}\n"); + let want: &[(usize, &str)] = if found { &[(4, "all-unguarded")] } else { &[] }; + assert_eq!(hits(&src), want, "{array}.{method}"); + } + } + + #[test] + fn all_guards_accept_asserted_locals_that_count() { + let src = "#[test]\nfn t() {\n let row = cards.iter().filter(|c| first_row(c)).count();\n assert_eq!(row, 4, \"four cards\");\n assert!(cards.iter().all(|c| c.x < 10));\n}\n"; + assert_eq!(hits(src), []); + let summed = src.replace(".count()", ".map(|c| c.w).sum::()"); + assert_eq!(hits(&summed), [(5, "all-unguarded")], "a sum does not count items"); + let message = src.replace("assert_eq!(row, 4, \"four cards\")", "assert_eq!(a, b, \"{}\", row)"); + assert_eq!(hits(&message), [(5, "all-unguarded")], "a count in a failure message checks nothing"); + let unused = src.replace(" assert_eq!(row, 4, \"four cards\");\n", ""); + assert_eq!(hits(&unused), [(4, "all-unguarded")], "a count no assertion reads checks nothing"); + for change in ["let row = 4;", "row = 4;", "reset(&mut row);"] { + let changed = src.replace(" assert_eq!(row", &format!(" {change}\n assert_eq!(row")); + assert_eq!(hits(&changed), [(6, "all-unguarded")], "{change} before the assertion"); + } + let later = src.replace(" assert_eq!(row, 4, \"four cards\");\n", " assert_eq!(row, 4);\n let row = 4;\n"); + assert_eq!(hits(&later), [], "the count reaches the assertion before it is bound again"); + } + #[test] fn all_respects_condition_polarity() { for condition in [ @@ -2513,6 +3453,22 @@ mod tests { assert_eq!(found.iter().filter(|h| touches(h, Some(&BTreeSet::new()))).count(), 0); } + #[test] + fn only_failing_rules_fail_the_check() { + let failing: Vec<&str> = Rule::ALL.into_iter().filter(|r| r.fails()).map(Rule::id).collect(); + assert_eq!(failing, ["only-weak", "self-compare", "ignore-without-reason", "sleep"]); + let weak = "#[test]\nfn weak() {\n assert!(f().is_ok());\n}\n"; + let unguarded = "#[test]\nfn all() {\n assert!(f().iter().all(|x| valid(x)));\n}\n"; + let hits_of = |src: &str| lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(finish(&hits_of(unguarded), 0, 1, "base"), Ok(()), "all-unguarded only reports"); + let both = hits_of(&format!("{weak}{unguarded}")); + assert_eq!(both.len(), 2); + let Err(message) = finish(&both, 0, 1, "base") else { panic!("only-weak fails the check") }; + assert!(message.starts_with("1 test-lint hit(s)"), "{message}"); + assert!(message.contains("[only-weak] `weak`") && !message.contains("[all-unguarded]"), "{message}"); + assert_eq!(finish(&[], 3, 1, "base"), Ok(())); + } + #[test] fn options_reject_unknown_and_repeated_arguments() { assert_eq!(Options::parse(&[]), Ok(Options::default())); From 747593d0dd6524ed3789940a590ed9e5d8039cfd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:10:17 -0800 Subject: [PATCH 45/69] xtask: test-lint reads quoted paths, test_case tests and literal setters correctly - Changed mode decodes `+++` labels (the tab after a path with a space, C-quoted paths), and the file inventories read `git ls-files -z`, so files with spaces, quotes or non-ASCII names are linted. - `#[test_case(1; "one")]` arguments and other attributes no longer end the item before its `fn`, and an inner `#![...]` attribute before the first test is not part of that test's span. - A helper name counts as asserting only when every function of that name in the crate's test code asserts. - `.stdout(file)` and other stream builder calls count as configuration whatever their argument, so `exit-status-only` still reports. - A `return` inside `async { ... }` or `async move { ... }` ends the future, not the test, for `early-return`. - `env-gate-unset` looks for setters in code only, not in string literals, ignores `echo` and `printf` output that is not written to `$GITHUB_ENV`, and its span reaches the variable name on a later line. - `sleep` reports `thread::sleep`, or a bare `sleep(...)` only where the file imports `thread::sleep`. - `reads-source` checks raw string paths in `include_str!` and `ends_with`. - A test pins that a collection changed after its `assert_eq!` loses that guard for `all-unguarded`. --- xtask/src/main.rs | 4 +- xtask/src/test_lint.rs | 288 +++++++++++++++++++++++++++++++++++------ 2 files changed, 247 insertions(+), 45 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index addf9cb7e1..3a0c854486 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -125,13 +125,13 @@ pub fn root() -> PathBuf { pub fn repo_files(root: &Path) -> Result, String> { let out = Command::new("git") .current_dir(root) - .args(["ls-files", "--cached", "--others", "--exclude-standard"]) + .args(["ls-files", "-z", "--cached", "--others", "--exclude-standard"]) .output() .map_err(|e| format!("git ls-files: {e}"))?; if !out.status.success() { return Err(format!("git ls-files failed: {}", String::from_utf8_lossy(&out.stderr).trim())); } - Ok(String::from_utf8_lossy(&out.stdout).lines().filter(|l| root.join(l).exists()).map(str::to_owned).collect()) + Ok(String::from_utf8_lossy(&out.stdout).split('\0').filter(|l| !l.is_empty() && root.join(l).exists()).map(str::to_owned).collect()) } /// A `cargo` command (the one running xtask, else `cargo` on the PATH) run in the workspace root. diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 60363000fd..a0e8f8040a 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -32,9 +32,10 @@ //! corpora, environment variables, the platform or a child process; //! * `ignore-without-reason`: `#[ignore]` with no `= "reason"`; //! * `env-gate-unset`: `env::var("NAME")` in a test where no CI workflow, the shared gate or the -//! file itself sets `NAME`; workflow mapping keys and `NAME=` assignments count, but comments -//! and variable reads do not; -//! * `sleep`: `thread::sleep` in test code; +//! file's code sets `NAME`; workflow mapping keys and `NAME=` assignments count, but comments, +//! string literals, `echo` or `printf` output that is not written to `$GITHUB_ENV`, and variable +//! reads do not; +//! * `sleep`: `thread::sleep` in test code, or a bare `sleep(…)` in a file that imports it; //! * `reads-source`: test code that reads Rust source (`include_str!` of a `.rs` file, or a walk //! that keeps files ending in `.rs`), outside the source audits in [`SOURCE_AUDITS`]. //! @@ -42,8 +43,8 @@ //! `benches` folder, `crates/testkit`), an item under `#[cfg(test)]`, or a test function. //! //! An asserting helper is a function or macro in the crate's test code (or in `crates/testkit`) -//! that asserts, panics or calls one that does, or a call whose name starts with `assert`, -//! `check`, `verify`, `ensure` or `expect_`. +//! that asserts, panics or calls one that does (every one of that name, when there are several), +//! or a call whose name starts with `assert`, `check`, `verify`, `ensure` or `expect_`. //! //! `// test-lint: allow ` exempts the line it is on and the line below it; for the //! rules about a whole test it can be on any line from the line above the test attribute to the @@ -185,8 +186,9 @@ pub struct Hit { pub note: String, /// The first and last line of what the hit covers: the test, from its attribute to its closing /// brace, for a rule about a whole test or `all-unguarded`, through the second operand for - /// `self-compare`, else `line`. This span controls changed-line detection; `all-unguarded` - /// and `self-compare` exemptions still apply only near `line`. + /// `self-compare`, through the variable's name for `env-gate-unset`, else `line`. This span + /// controls changed-line detection; `all-unguarded` and `self-compare` exemptions still apply + /// only near `line`. pub first: usize, pub last: usize, } @@ -385,7 +387,7 @@ fn changed_lines(root: &Path, base: &str) -> Result BTreeMap>> { } else if header && line.starts_with("new file mode") { new_file = true; } else if let Some(path) = line.strip_prefix("+++ ").filter(|_| header) { - current = path.strip_prefix("b/").map(str::to_owned); + current = patch_path(path).and_then(|p| p.strip_prefix("b/").map(str::to_owned)); if let Some(p) = ¤t { out.insert(p.clone(), if new_file { None } else { Some(BTreeSet::new()) }); } @@ -422,6 +424,41 @@ fn parse_diff(diff: &str) -> BTreeMap>> { out } +/// The path in a `+++ ` label: git ends a label that contains a space with a tab, and writes a +/// path with a quote, a backslash or a control character as a C-style quoted string. +fn patch_path(label: &str) -> Option { + let label = label.strip_suffix('\t').unwrap_or(label); + let Some(quoted) = label.strip_prefix('"') else { return Some(label.to_owned()) }; + let body = quoted.strip_suffix('"')?.as_bytes(); + let (mut out, mut i) = (Vec::with_capacity(body.len()), 0); + while i < body.len() { + if body[i] != b'\\' { + out.push(body[i]); + i += 1; + continue; + } + let c = *body.get(i + 1)?; + let octal = body.get(i + 1..i + 4).filter(|d| d.iter().all(|c| (b'0'..=b'7').contains(c))); + if let Some(digits) = octal { + out.push(digits.iter().fold(0u8, |n, d| n.wrapping_mul(8).wrapping_add(d - b'0'))); + i += 4; + continue; + } + out.push(match c { + b'a' => 7, + b'b' => 8, + b't' => b'\t', + b'n' => b'\n', + b'v' => 11, + b'f' => 12, + b'r' => b'\r', + other => other, + }); + i += 2; + } + String::from_utf8(out).ok() +} + /// `(start, count)` of the new side of a hunk header's `-a,b +c,d @@`. A pure deletion has count 0 /// and sits between lines c and c + 1; c = 0 places it before line 1. fn hunk_range(hunk: &str) -> Option<(usize, usize)> { @@ -459,12 +496,20 @@ fn upper_words(text: &str) -> impl Iterator + '_ { let name = line[..at].rsplit(|c: char| !(c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')).next().unwrap_or_default(); let from = at - name.len(); let boundary = from == 0 || line.as_bytes().get(from - 1).is_some_and(|c| c.is_ascii_whitespace() || matches!(c, b'\'' | b'"' | b';')); - (boundary && env_assignment_name(name) && !line[at + 1..].starts_with(['=', '>'])).then(|| name.to_owned()) + (boundary && env_assignment_name(name) && !line[at + 1..].starts_with(['=', '>']) && !printed(line, from)).then(|| name.to_owned()) }); mapping.map(|(name, _)| name.to_owned()).into_iter().chain(assignments) }) } +/// Whether the text at `from` is an argument of `echo` or `printf` in its shell command, on a line +/// that does not write to `$GITHUB_ENV`. +fn printed(line: &str, from: usize) -> bool { + let command = line[..from].rsplit([';', '&', '|']).next().unwrap_or_default().as_bytes(); + let prints = ["echo", "printf"].iter().any(|w| !words(command, w.as_bytes(), 0, command.len()).is_empty()); + prints && !line.contains("GITHUB_ENV") +} + fn env_assignment_name(name: &str) -> bool { name.len() > 1 && name.starts_with(|c: char| c.is_ascii_uppercase()) @@ -513,11 +558,6 @@ fn mask_with(src: &str, comments: bool) -> Vec { mask_parts(src, comments, true) } -/// Blanks comments while keeping code and literal contents at the same byte offsets. -fn mask_comments(src: &str) -> Vec { - mask_parts(src, true, false) -} - /// Blanks the selected comments and literal contents, preserving line breaks and literal quotes. fn mask_parts(src: &str, comments: bool, literals: bool) -> Vec { let b = src.as_bytes(); @@ -769,6 +809,11 @@ fn tests_in(m: &[u8]) -> Vec { /// The function an attribute at `attr` (ending at `from`) belongs to. fn fn_after(m: &[u8], attr: usize, from: usize) -> Option { + // The attribute's arguments, and the attributes after it, can hold `;` (`#[test_case(1; "one")]`). + let mut from = from.max(matching(m, attr + 1)? + 1); + while m[skip_ws(m, from)..].starts_with(b"#[") { + from = matching(m, skip_ws(m, from) + 1)? + 1; + } let limit = (from + 800).min(m.len()); let fn_at = *words(m, b"fn", from, limit).first()?; if m[from..fn_at].iter().any(|&c| c == b'{' || c == b';') { @@ -785,7 +830,11 @@ fn fn_after(m: &[u8], attr: usize, from: usize) -> Option { } let close = matching(m, open)?; // The item starts after the previous item or block opening; comments before it are masked. - let item = m[..attr].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + // Inner attributes (`#![…]`) there belong to the enclosing module or crate. + let mut item = m[..attr].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + while m[skip_ws(m, item)..].starts_with(b"#![") && skip_ws(m, item) < attr { + item = matching(m, skip_ws(m, item) + 2)? + 1; + } let attr = skip_ws(m, item).min(attr); Some(TestFn { name: String::from_utf8_lossy(&m[name_start..name_end]).into_owned(), attr, fn_at, open, close }) } @@ -960,12 +1009,22 @@ pub fn asserting_helpers(files: &[(String, String)]) -> HashMap(defs: impl Iterator + Clone) -> HashSet { - let mut known: HashSet = defs.clone().filter(|d| d.1).map(|d| d.0.clone()).collect(); + let mut by_name: HashMap<&str, Vec<&Def>> = HashMap::new(); + for d in defs { + by_name.entry(d.0.as_str()).or_default().push(d); + } + let mut known: HashSet = HashSet::new(); loop { - let more: Vec = - defs.clone().filter(|d| !known.contains(&d.0) && d.2.iter().any(|c| known.contains(c))).map(|d| d.0.clone()).collect(); + let checks = |d: &Def| d.1 || d.2.iter().any(|c| known.contains(c)); + let more: Vec = by_name + .iter() + .filter(|(name, same)| !known.contains(**name) && same.iter().all(|d| checks(d))) + .map(|(name, _)| (*name).to_owned()) + .collect(); if more.is_empty() { return known; } @@ -2074,13 +2133,12 @@ fn exit_status_only(v: &View) -> Option { Some(v.whole(Rule::ExitStatusOnly, "runs a process and checks only its exit status".into())) } -/// Blanks stream method names that configure a process with `Stdio` in whitespace-free text. +/// Blanks the names of builder calls that set a process's streams (`.stdout(…)`, whatever the +/// argument) in whitespace-free text. Reads of the output fields (`out.stdout`) stay. fn strip_stream_configuration(body: &mut [u8]) { for stream in ["stdout", "stderr", "stdin"] { for at in words(body, stream.as_bytes(), 0, body.len()) { - let rest = &body[at + stream.len()..]; - let config = rest.starts_with(b"(Stdio::") || rest.starts_with(b"(std::process::Stdio::"); - if body[..at].ends_with(b".") && config { + if body[..at].ends_with(b".") && body[at + stream.len()..].starts_with(b"(") { blank(body, at, at + stream.len()); } } @@ -2205,7 +2263,9 @@ fn opens_closure_or_fn(m: &[u8], open: usize, brace: usize) -> bool { let head = String::from_utf8_lossy(&head[start..]).into_owned(); let head = head.trim_end(); let closure = head.ends_with('|') || head.rfind("->").is_some_and(|p| head[..p].trim_end().ends_with('|')); - closure || !words(head.as_bytes(), b"fn", 0, head.len()).is_empty() + let block = head.strip_suffix("move").unwrap_or(head).trim_end(); + let future = block.ends_with("async") && !block[..block.len() - "async".len()].ends_with(|c: char| c.is_ascii_alphanumeric() || c == '_'); + closure || future || !words(head.as_bytes(), b"fn", 0, head.len()).is_empty() } /// Whether the return at `at..end` is not a silent skip on a value: the block it ends asserts @@ -2239,24 +2299,50 @@ fn env_gates(v: &View, ctx: &Ctx) -> Vec { if !m[..at].ends_with(b"env::") { continue; } - let Some(name) = env_name(m, src, at) else { continue }; + let Some((name, end)) = env_name(m, src, at) else { continue }; if ctx.ci_env.contains(&name) || set_by_system(&name) { continue; } - // The whole file is masked and searched only for a name that CI and the system leave unset. - let file = norm(&mask_comments(&String::from_utf8_lossy(src))); - let set_here = file.contains(&format!(".env(\"{name}\"")) - || file.contains(&format!("=\"{name}\";")) - || file.match_indices(&format!("set_var(\"{name}\"")).any(|(at, _)| at == 0 || !is_ident(file.as_bytes()[at - 1])); - if !set_here { - out.push(v.hit(at, Rule::EnvGateUnset, format!("reads {name}, which no CI leg sets"))); + if !set_in_file(m, src, &name) { + // The hit sits on `var`; its span reaches the name, which can be on a later line. + let mut hit = v.hit(at, Rule::EnvGateUnset, format!("reads {name}, which no CI leg sets")); + hit.last = v.file.lines.of(end); + out.push(hit); } } out } -/// The literal name in `env::var("NAME")` whose `var` is at `at`. -fn env_name(m: &[u8], src: &[u8], at: usize) -> Option { +/// Whether the file's code (masked `m`, outside comments and literals) sets `name`: `.env("NAME", …)`, +/// `set_var("NAME", …)`, or a constant `= "NAME";`. The name is read from the source. +fn set_in_file(m: &[u8], src: &[u8], name: &str) -> bool { + let call = |word: &[u8], method: bool| { + words(m, word, 0, m.len()).into_iter().any(|at| { + let dot = m[..at].trim_ascii_end().ends_with(b"."); + (dot || !method) && env_name(m, src, at).is_some_and(|(n, _)| n == name) + }) + }; + let constant = find_all(src, name.as_bytes()).any(|p| { + let (open, close) = (p.wrapping_sub(1), p + name.len()); + let (Some(b'"'), Some(b'"')) = (m.get(open), m.get(close)) else { return false }; + m[..open].trim_ascii_end().ends_with(b"=") && m.get(skip_ws(m, close + 1)) == Some(&b';') + }); + call(b"env", true) || call(b"set_var", false) || constant +} + +/// Every start of `needle` in `hay`. +fn find_all<'a>(hay: &'a [u8], needle: &'a [u8]) -> impl Iterator + 'a { + let mut from = 0; + std::iter::from_fn(move || { + let at = find(hay, needle, from)?; + from = at + 1; + Some(at) + }) +} + +/// The literal name in `env::var("NAME")` whose `var` is at `at`, and the offset of its closing +/// quote. +fn env_name(m: &[u8], src: &[u8], at: usize) -> Option<(String, usize)> { let open = skip_ws(m, at + m[at..].iter().take_while(|&&c| is_ident(c)).count()); if m.get(open) != Some(&b'(') { return None; @@ -2267,7 +2353,7 @@ fn env_name(m: &[u8], src: &[u8], at: usize) -> Option { } let end = string_end(src, quote + 1).saturating_sub(1); let name = std::str::from_utf8(&src[quote + 1..end]).ok()?; - (!name.is_empty() && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')).then(|| name.to_owned()) + (!name.is_empty() && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')).then(|| (name.to_owned(), end)) } fn ignore_hits(file: &File) -> Vec { @@ -2311,16 +2397,24 @@ fn ignore_reason(src: &[u8]) -> Option<&[u8]> { fn sleep_hits(file: &File) -> Vec { let m = &file.m; + // A bare `sleep(…)` counts only where a `use` brings in `thread::sleep`. + let imported = words(m, b"use", 0, m.len()).into_iter().any(|u| { + let item = norm(&m[u..statement_end(m, u)]); + item.contains("thread::sleep") + || item.split_once("thread::{").is_some_and(|(_, list)| !words(list.as_bytes(), b"sleep", 0, list.len()).is_empty()) + }); words(m, b"sleep", 0, m.len()) .into_iter() .filter(|&at| { - if !in_regions(&file.regions, at) { + if !in_regions(&file.regions, at) || m.get(skip_ws(m, at + "sleep".len())) != Some(&b'(') { return false; } - let before = m[..at].iter().rposition(|c| !c.is_ascii_whitespace()); - let method = before.is_some_and(|b| m[b] == b'.'); - let definition = m[..at].trim_ascii_end().ends_with(b"fn"); - !method && !definition && m.get(skip_ws(m, at + "sleep".len())) == Some(&b'(') + let before = m[..at].trim_ascii_end(); + let path = before.strip_suffix(b"::").map(<[u8]>::trim_ascii_end); + match path { + Some(p) => p.ends_with(b"thread") && !p.ends_with(b"_thread"), + None => imported && !before.ends_with(b".") && !before.ends_with(b"fn"), + } }) .map(|at| file.hit(at, Rule::Sleep, file.test_at(at), "sleeps in test code".into())) .collect() @@ -2337,7 +2431,10 @@ fn reads_source_hits(file: &File) -> Vec { let open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; let arg = norm(&file.src[open + 1..close]); - let rs = if word == b"ends_with" { arg == "\".rs\"" } else { arg.ends_with(".rs\"") }; + // An ordinary or raw string literal: `".rs"`, `r".rs"`, `r#"…/lib.rs"#`. + let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); + let literal = raw.unwrap_or(&arg); + let rs = if word == b"ends_with" { literal == "\".rs\"" } else { arg.trim_end_matches('#').ends_with(".rs\"") }; if rs { out.push(file.hit(at, Rule::ReadsSource, file.test_at(at), note.into())); } @@ -3335,7 +3432,7 @@ mod tests { assert_eq!(hits(&src.replacen("MY_SAMPLES", "OTHER_SAMPLES", 1)), [(4, "env-gate-unset")], "{setter}"); } let src = "let a = \"https://host/*path*/\"; /* removed */ let b = r#\"// kept /* kept */\"#; // removed\nlet c = '/';"; - let masked = String::from_utf8(mask_comments(src)).unwrap(); + let masked = String::from_utf8(mask_parts(src, true, false)).unwrap(); assert!(masked.contains("\"https://host/*path*/\"")); assert!(masked.contains("r#\"// kept /* kept */\"#")); assert!(masked.contains("let c = '/';")); @@ -3527,4 +3624,109 @@ mod tests { assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [], "{workflow}"); } } + + #[test] + fn printed_workflow_assignments_do_not_count() { + for line in + ["run: echo \"MY_SAMPLES=fixtures\"", " echo MY_SAMPLES=fixtures", " printf 'MY_SAMPLES=x\\n'", " true && echo \"MY_SAMPLES=x\""] + { + assert_eq!(upper_words(line).collect::>(), Vec::::new(), "{line}"); + } + for line in [" echo hi; MY_SAMPLES=x cargo test", " printf 'MY_SAMPLES=x\\n' >> \"$GITHUB_ENV\""] { + assert_eq!(upper_words(line).collect::>(), ["MY_SAMPLES"], "{line}"); + } + } + + #[test] + fn patch_labels_are_decoded_before_filtering() { + let diff = "diff --git a/crates/x/tests/two words.rs b/crates/x/tests/two words.rs\n--- a/crates/x/tests/two words.rs\t\n+++ b/crates/x/tests/two words.rs\t\n@@ -1 +1 @@\n-a\n+b\ndiff --git \"a/crates/x/tests/q\\\"t.rs\" \"b/crates/x/tests/q\\\"t.rs\"\n--- \"a/crates/x/tests/q\\\"t.rs\"\n+++ \"b/crates/x/tests/q\\\"t.rs\"\n@@ -2 +2 @@\n-a\n+b\ndiff --git \"a/crates/x/tests/caf\\303\\251.rs\" \"b/crates/x/tests/caf\\303\\251.rs\"\n--- \"a/crates/x/tests/caf\\303\\251.rs\"\n+++ \"b/crates/x/tests/caf\\303\\251.rs\"\n@@ -3 +3 @@\n-a\n+b\n"; + let got = parse_diff(diff); + assert_eq!(got.get("crates/x/tests/two words.rs"), Some(&Some([1].into_iter().collect())), "{got:?}"); + assert_eq!(got.get("crates/x/tests/q\"t.rs"), Some(&Some([2].into_iter().collect())), "{got:?}"); + assert_eq!(got.get("crates/x/tests/caf\u{e9}.rs"), Some(&Some([3].into_iter().collect())), "{got:?}"); + assert!(got.keys().all(|p| is_scanned(p)), "{got:?}"); + } + + #[test] + fn test_case_arguments_and_inner_attributes_do_not_hide_tests() { + let cases = "#[test_case(1; \"one\")]\n#[test_case(2; \"two\")]\nfn t(n: u8) {}\n"; + assert_eq!(hits(cases), [(3, "no-assertion")]); + let inner = "#![allow(dead_code)]\n\n#[should_panic]\n#[test]\nfn t() {\n f();\n}\n#[test]\nfn u() {\n g();\n}\n"; + let found = lint_file("crates/x/src/tests.rs", &inner.replace("#[should_panic]\n", ""), &ctx()); + assert_eq!(found.iter().map(|h| (h.first, h.last)).collect::>(), [(3, 6), (7, 10)], "{found:?}"); + assert_eq!(hits(inner), [(9, "no-assertion")], "#[should_panic] before #[test] still belongs to the test"); + } + + #[test] + fn helpers_with_a_shared_name_count_only_when_each_asserts() { + let src = "mod a {\n pub fn exercise() { assert_eq!(f(), 1); }\n}\nmod b {\n pub fn exercise() { f(); }\n}\n#[test]\nfn t() {\n b::exercise();\n}\n"; + let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); + assert!(!helpers["crates/x"].contains("exercise"), "{helpers:?}"); + assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx { helpers, ci_env: HashSet::new() }), [(8, "no-assertion")]); + let both = src.replace("{ f(); }", "{ assert!(f()); }"); + let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), both.clone())]); + assert_eq!(hits_in("crates/x/tests/it.rs", &both, &Ctx { helpers, ci_env: HashSet::new() }), []); + } + + #[test] + fn a_changed_collection_loses_its_equality_guard() { + let src = "#[test]\nfn t() {\n let mut xs = f();\n assert_eq!(xs, vec![1]);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), []); + for change in ["xs.clear();", "xs.retain(|x| *x > 5);", "xs = vec![];"] { + let changed = src.replace("\n assert!", &format!("\n {change}\n assert!")); + assert_eq!(hits(&changed), [(6, "all-unguarded")], "{change}"); + } + } + + #[test] + fn stream_redirection_to_any_target_is_configuration() { + let bad = "#[test]\nfn t() {\n let status = Command::new(bin()).stdout(file).stderr(log.try_clone().unwrap()).status().unwrap();\n assert!(status.success());\n}\n"; + assert_eq!(hits(bad), [(2, "exit-status-only")]); + let good = bad.replace(" assert!", " assert_eq!(fs::read(path).unwrap(), b\"ok\");\n assert!"); + assert_eq!(hits(&good), []); + } + + #[test] + fn async_blocks_end_their_own_returns() { + let src = "#[test]\nfn t() {\n block_on(async { if missing() { return; } work().await; });\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(src), []); + assert_eq!(hits(&src.replace("async {", "async move {")), []); + let own = "#[tokio::test]\nasync fn t() {\n if missing() { return; }\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(own), [(3, "early-return")], "a return from the test's own body"); + } + + #[test] + fn env_setters_in_literals_do_not_count_and_spans_reach_the_name() { + let src = "#[test]\nfn t() {\n let _example = r#\"cmd.env(\"MY_SAMPLES\", dir)\"#;\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; + assert_eq!(hits(src), [(4, "env-gate-unset")]); + let constant = "const X: &str = r#\"= \"MY_SAMPLES\";\"#;\n#[test]\nfn t() {\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; + assert_eq!(hits(constant), [(4, "env-gate-unset")]); + let multiline = "#[test]\nfn t() {\n let dir = std::env::var(\n \"MY_SAMPLES\",\n );\n assert_eq!(f(dir), 3);\n}\n"; + let found = lint_file("crates/x/src/tests.rs", multiline, &ctx()); + assert_eq!(found.iter().map(|h| (h.rule, h.line, h.first, h.last)).collect::>(), [(Rule::EnvGateUnset, 3, 3, 4)]); + assert!(touches(&found[0], Some(&[4].into_iter().collect())), "a change to the name alone"); + } + + #[test] + fn sleep_needs_the_thread_function() { + let local = "fn sleep() -> u8 { 42 }\n#[test]\nfn t() {\n assert_eq!(sleep(), 42);\n}\n"; + assert_eq!(hits(local), []); + for import in ["use std::thread::sleep;", "use std::thread::{self, sleep};"] { + let src = format!("{import}\n#[test]\nfn t() {{\n sleep(D);\n assert_eq!(f(), 42);\n}}\n"); + assert_eq!(hits(&src), [(4, "sleep")], "{import}"); + } + assert_eq!(hits("#[test]\nfn t() {\n std :: thread :: sleep(D);\n assert_eq!(f(), 1);\n}\n"), [(3, "sleep")]); + } + + #[test] + fn raw_include_str_paths_are_checked() { + for literal in ["r\"../lib.rs\"", "r#\"../lib.rs\"#", "r##\"../lib.rs\"##"] { + let src = format!("#[test]\nfn t() {{\n let src = include_str!({literal});\n assert_eq!(src.len(), 1);\n}}\n"); + assert_eq!(hits(&src), [(3, "reads-source")], "{literal}"); + assert_eq!(hits(&src.replace(".rs", ".svg")), [], "{literal} with a fixture"); + assert_eq!(hits_in(SOURCE_AUDITS[0], &src, &ctx()), [], "{literal} in an audit"); + } + let walk = "#[test]\nfn t() {\n let n = files().filter(|p| p.ends_with(r#\".rs\"#)).count();\n assert_eq!(n, 4);\n}\n"; + assert_eq!(hits(walk), [(3, "reads-source")]); + } } From b851ac2c8d118022643616ecbd3240c91520664d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:16:23 -0800 Subject: [PATCH 46/69] CI: drop the cache prune watcher job; cache-prune.yml prunes after each run ci.yml's `cache prune` job held a runner beside the whole gate on every main push and nightly run, only to delete the rolling entry that the `cache warm` leg replaced. cache-prune.yml already runs that prune once every CI attempt on main ends, and the warm leg is the last job to finish, so the old entry now goes a few seconds after the save instead of during it. The nightly cold run's `cold cache clear` job stays. Its script used the `cache prune` job to tell "Re-run all jobs" from a re-run of failed jobs. It now looks for `gate / select legs` instead, which only "Re-run all jobs" lists once the warm leg has succeeded, and it waits 5 minutes for that job to appear before it treats the warm leg as finished in an earlier attempt. --- .github/workflows/cache-prune.yml | 11 +++++---- .github/workflows/ci.yml | 30 ++----------------------- scripts/ci-clear-rolling-cache-tests.py | 24 +++++++++++++------- scripts/ci-clear-rolling-cache.py | 23 ++++++++++++------- 4 files changed, 38 insertions(+), 50 deletions(-) diff --git a/.github/workflows/cache-prune.yml b/.github/workflows/cache-prune.yml index a79f1ed907..c1b1e73ae3 100644 --- a/.github/workflows/cache-prune.yml +++ b/.github/workflows/cache-prune.yml @@ -1,11 +1,10 @@ name: Cache prune -# A pass of the cache prune after every CI attempt on main. ci.yml's `cache prune` job prunes while -# a run's jobs save their entries, but "Re-run failed jobs" re-runs only the failed jobs: a re-run -# `cache warm` leg saves a new entry, and the prune job, which succeeded in the first attempt, does -# not run again. The entry it replaced would stay until the next main run, and with it the cache -# would be over its 10 GB budget, where GitHub evicts entries a run still needs. This runs once -# after every attempt, re-runs and canceled runs included (craft-common-actions actions/cache-prune). +# Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache +# budget, where GitHub evicts entries a run still needs. Each main CI attempt's `cache warm` leg +# saves a new rolling entry; this deletes the entry it replaced once the attempt ends. It runs once +# after every attempt, re-runs of failed jobs and canceled runs included (craft-common-actions +# actions/cache-prune). on: workflow_run: workflows: [CI] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0954b5c35c..9937d6165c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -50,8 +50,8 @@ jobs: # 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 - # `cache-prune` below deletes the one it replaced. The nightly run restores nothing and - # builds everything from source. + # 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 cold-build: ${{ github.event_name == 'schedule' }} packages: >- @@ -59,32 +59,6 @@ jobs: libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers libgl1-mesa-dev - # Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache - # budget. It runs beside the gate and prunes each time the `cache warm` leg finishes saving. A - # failed prune warns instead of failing the run, and cache-prune.yml prunes again after every - # attempt, re-runs of failed jobs included. `watch-minutes` is longer than the gate's - # `timeout-minutes`, so the watch outlasts a cold `cache warm` leg. - cache-prune: - name: cache prune - if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' - runs-on: ubuntu-24.04 - timeout-minutes: 170 - permissions: - actions: write - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - name: Prune replaced cache entries - uses: storytold/craft-common-actions/actions/cache-prune@main - continue-on-error: true - with: - watch: true - watch-minutes: 160 - saving-jobs: | - ^gate( / cache warm \(.*\))?$ - # 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 diff --git a/scripts/ci-clear-rolling-cache-tests.py b/scripts/ci-clear-rolling-cache-tests.py index a284579d16..250fd92b1c 100644 --- a/scripts/ci-clear-rolling-cache-tests.py +++ b/scripts/ci-clear-rolling-cache-tests.py @@ -129,18 +129,26 @@ class Jobs(unittest.TestCase): jobs = [{"name": "gate / test 1/5 (ubuntu-24.04)"}, {"name": "gate / build (${{ matrix.os }})"}, {"name": WARM}] self.assertEqual(clear.warm_job(jobs), jobs[2]) - def test_a_rerun_of_this_job_alone_skips_a_leg_that_succeeded(self): - self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success")})) - self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success"), 2: [{"name": "cold cache clear"}]})) - self.assertTrue(clear.not_in_attempt(ME, {1: earlier("failure"), 2: [{"name": "cold cache clear"}], 3: earlier("success")})) + def test_a_rerun_of_failed_jobs_skips_a_leg_that_succeeded(self): + grace = clear.RERUN_GRACE_SECONDS + failed_shard = [{"name": "gate / test 3/6 (ubuntu-24.04)", "status": "in_progress"}] + self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success")}, grace)) + self.assertTrue(clear.not_in_attempt(ME + failed_shard, {1: earlier("success")}, grace)) + self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success"), 2: [{"name": "cold cache clear"}]}, grace)) + self.assertTrue(clear.not_in_attempt(ME, {1: earlier("failure"), 2: [{"name": "cold cache clear"}], 3: earlier("success")}, grace)) + + def test_an_attempt_is_watched_for_the_grace_period_first(self): + self.assertFalse(clear.not_in_attempt(ME, {1: earlier("success")}, clear.RERUN_GRACE_SECONDS - 1)) def test_a_leg_that_did_not_succeed_is_waited_for(self): - self.assertFalse(clear.not_in_attempt(ME, {1: earlier("cancelled")})) - self.assertFalse(clear.not_in_attempt(ME, {})) - self.assertFalse(clear.not_in_attempt(ME, {1: earlier("success"), 2: earlier("failure")})) + grace = clear.RERUN_GRACE_SECONDS + self.assertFalse(clear.not_in_attempt(ME, {1: earlier("cancelled")}, grace)) + self.assertFalse(clear.not_in_attempt(ME, {}, grace)) + self.assertFalse(clear.not_in_attempt(ME, {1: earlier("success"), 2: earlier("failure")}, grace)) def test_a_rerun_of_all_jobs_is_waited_for(self): - self.assertFalse(clear.not_in_attempt(ME + [{"name": "cache prune", "status": "in_progress"}], {1: earlier("success")})) + select = [{"name": "gate / select legs", "status": "queued"}] + self.assertFalse(clear.not_in_attempt(ME + select, {1: earlier("success")}, clear.GIVE_UP_SECONDS)) def test_a_failed_select_or_build_stops_the_wait(self): done = lambda n, c: {"name": n, "status": "completed", "conclusion": c} diff --git a/scripts/ci-clear-rolling-cache.py b/scripts/ci-clear-rolling-cache.py index 3b913d68f7..e285fef70b 100644 --- a/scripts/ci-clear-rolling-cache.py +++ b/scripts/ci-clear-rolling-cache.py @@ -18,9 +18,10 @@ were deleted leaves no rolling entry, so the next run starts cold, and this exit in a later post step does not count once the save step has succeeded. This also exits 1 when the leg has not started START_SECONDS after this script started, and when the leg has not reached its save, or its save has not finished, GIVE_UP_SECONDS after the leg started. An absent warm leg is treated as finished only -when the most recent earlier attempt that lists it reports success and the current attempt lists -no `cache prune` job, which runs from the start of "Re-run all jobs". Otherwise this keeps polling -because reusable-workflow dependencies may still be scheduling it. +when the most recent earlier attempt that lists it reports success and the current attempt still +lists no `gate / select legs` job RERUN_GRACE_SECONDS after this script started: "Re-run all +jobs" lists that job from its start, and "Re-run failed jobs" after a successful leg does not. +Otherwise this keeps polling because reusable-workflow dependencies may still be scheduling it. """ from datetime import datetime, timezone @@ -36,7 +37,12 @@ WARM_JOB = re.compile(r'^gate / cache warm \(') # 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. NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \()') -PRUNE_JOB = 'cache prune' +# The gate's first job. "Re-run all jobs" lists it; "Re-run failed jobs" lists it only when it +# failed, and then no warm leg succeeded before. +SELECT_JOB = 'gate / select legs' +# How long an attempt that does not list SELECT_JOB is watched before the warm leg counts as +# finished in an earlier attempt. +RERUN_GRACE_SECONDS = 5 * 60 ROLLING = '-gate-crates-' # The gate-setup action's post step, which saves the dependency cache (craft-common-actions # actions/gate-setup, under the gate's `Setup` step). @@ -135,9 +141,10 @@ def legs_stopped(jobs): return any(NEEDED_JOBS.match(j['name']) and j['status'] == 'completed' and j.get('conclusion') in STOPPED for j in jobs) -def not_in_attempt(jobs, earlier_jobs): - """True when no prune job is listed and the most recent earlier warm leg succeeded.""" - if any(j['name'] == PRUNE_JOB for j in jobs): +def not_in_attempt(jobs, earlier_jobs, waited): + """True when SELECT_JOB is not listed `waited` seconds after this script started, at least + RERUN_GRACE_SECONDS, and the most recent earlier warm leg succeeded.""" + if waited < RERUN_GRACE_SECONDS or any(j['name'] == SELECT_JOB for j in jobs): return False for attempt in sorted(earlier_jobs, reverse=True): job = warm_job(earlier_jobs[attempt]) @@ -185,7 +192,7 @@ def main(): earlier_jobs[earlier] = previous.get('jobs', []) if warm_job(earlier_jobs[earlier]) is not None: break - if not_in_attempt(jobs.get('jobs', []), earlier_jobs): + 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') return if legs_stopped(jobs.get('jobs', [])): From 28f33ca04c29a0e6c75d256ad873099ff3ce9e0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:20:08 -0800 Subject: [PATCH 47/69] xtask: test-lint scopes bindings, spans ignore reasons and names its failing rules - The module docs and docs/development.md name the four rules that fail the check, and describe `only-weak` and `self-compare` by what they match (`len() > 0`, `assert_ne!`). - The changed-lines diff passes `--inter-hunk-context=0`, so a clone's `diff.interHunkContext` cannot mark unchanged lines between two edits. - Single-letter workflow variables count as set. - Test names with non-ASCII letters are read whole. - An allow in a block comment needs a reason before `*/`. - `all-unguarded` uses only a binding still in scope at the assertion, treats a `const` declared with different values as unknown, and drops a counted local once its collection may shrink or be replaced. - `only-weak` ignores `unwrap_err`, `expect_err` and `panic!` in failure messages. - `self-compare` leaves out operands that call a method returning the next value each time (`next`, `pop_front`, `recv` and others). - An `ignore-without-reason` span reaches the attribute's `]`, so a change to a reason on the next line counts. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 174 +++++++++++++++++++++++++++++++++++------ 2 files changed, 149 insertions(+), 27 deletions(-) diff --git a/docs/development.md b/docs/development.md index cfd02bacc8..efb554b561 100644 --- a/docs/development.md +++ b/docs/development.md @@ -351,7 +351,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on a test whose only checks are `is_ok`, `is_some` or `!is_empty` (`only-weak`), `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index a0e8f8040a..f442c9681d 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -21,7 +21,8 @@ //! * `only-weak`: every assertion is `is_ok()`, `is_some()`, `!is_empty()` or `len() > 0`, and the //! test calls no asserting helper; //! * `self-compare`: `assert_eq!(x, x)` or `assert_ne!(x, x)` on the same expression, when that -//! expression calls nothing with arguments (two calls with arguments check determinism); +//! expression calls nothing with arguments (two calls with arguments check determinism) and no +//! method that returns the next value each time ([`ADVANCING`], such as `next`); //! * `exit-status-only`: a test that runs a process and checks only its exit status, reading no //! output, with a status check in any condition or compared operand of a standard assertion; //! * `no-assertion`: no assertion macro, `panic!`, `unwrap_err`, `expect_err` or asserting helper, @@ -50,8 +51,9 @@ //! rules about a whole test it can be on any line from the line above the test attribute to the //! `fn` line. An allow without a reason exempts nothing. //! -//! `cargo xtask test-lint` fails on the hits in the lines and tests changed since a base: `--base -//! ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's +//! `cargo xtask test-lint` fails on hits of `only-weak`, `self-compare`, `ignore-without-reason` +//! and `sleep` in the lines and tests changed since a base, and lists the other rules' hits there +//! without failing. The base is `--base ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's //! merge commit is checked out, and a shallow checkout fetches that parent); elsewhere the merge //! base of `HEAD` and `upstream/main` or `origin/main`. Uncommitted and untracked files count as //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the @@ -186,7 +188,8 @@ pub struct Hit { pub note: String, /// The first and last line of what the hit covers: the test, from its attribute to its closing /// brace, for a rule about a whole test or `all-unguarded`, through the second operand for - /// `self-compare`, through the variable's name for `env-gate-unset`, else `line`. This span + /// `self-compare`, through the variable's name for `env-gate-unset`, through the attribute's + /// `]` for `ignore-without-reason`, else `line`. This span /// controls changed-line detection; `all-unguarded` and `self-compare` exemptions still apply /// only near `line`. pub first: usize, @@ -384,7 +387,20 @@ fn resolve_base(root: &Path, explicit: Option) -> Result fn changed_lines(root: &Path, base: &str) -> Result>>, String> { let diff = git( root, - &["-c", "core.quotepath=off", "diff", "-U0", "--no-color", "--no-ext-diff", "--src-prefix=a/", "--dst-prefix=b/", base, "--", "*.rs"], + &[ + "-c", + "core.quotepath=off", + "diff", + "-U0", + "--inter-hunk-context=0", + "--no-color", + "--no-ext-diff", + "--src-prefix=a/", + "--dst-prefix=b/", + base, + "--", + "*.rs", + ], )?; let mut out = parse_diff(&diff); for path in git(root, &["ls-files", "-z", "--others", "--exclude-standard", "--", "*.rs"])?.split('\0').filter(|p| !p.is_empty()) { @@ -511,9 +527,7 @@ fn printed(line: &str, from: usize) -> bool { } fn env_assignment_name(name: &str) -> bool { - name.len() > 1 - && name.starts_with(|c: char| c.is_ascii_uppercase()) - && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_') + name.starts_with(|c: char| c.is_ascii_uppercase()) && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_') } /// Removes comment text outside quotes from a workflow line. @@ -820,7 +834,8 @@ fn fn_after(m: &[u8], attr: usize, from: usize) -> Option { return None; } let name_start = skip_ws(m, fn_at + 2); - let name_end = name_start + m[name_start..].iter().take_while(|&&c| is_ident(c)).count(); + // Identifiers may hold non-ASCII letters (`échec`); their UTF-8 bytes are all 0x80 or above. + let name_end = name_start + m[name_start..].iter().take_while(|&&c| is_ident(c) || c >= 0x80).count(); if name_end == name_start { return None; } @@ -1124,7 +1139,8 @@ fn allows(src: &str, m: &[u8]) -> Vec<(usize, Rule)> { src.match_indices(ALLOW) .filter(|&(p, _)| m[p] == b' ' && literals[p] == b't') .filter_map(|(p, _)| { - let rest = src[p + ALLOW.len()..].lines().next()?; + // The reason ends with the line, or with the block comment that holds the marker. + let rest = src[p + ALLOW.len()..].lines().next()?.split("*/").next()?; let mut words = rest.split_whitespace(); let rule = Rule::from_id(words.next()?)?; words.next().map(|_| (lines.of(p), rule)) @@ -1622,7 +1638,7 @@ fn array_receiver(receiver: &str) -> &str { receiver.strip_suffix(".iter()").or_else(|| receiver.strip_suffix(".into_iter()")).unwrap_or(receiver) } -/// The fewest items a plain local receiver has after its latest preceding binding: from the +/// The fewest items a plain local receiver has after its latest preceding binding still in scope: from the /// binding ([`array_binding`]) or a loop that fills it ([`loop_fill_len`]), and 0 when a later /// statement may shrink or replace it ([`may_shrink`]). fn bound_len(receiver: &str, body: &[u8], sizes: &Sizes) -> usize { @@ -1631,7 +1647,8 @@ fn bound_len(receiver: &str, body: &[u8], sizes: &Sizes) -> usize { return 0; } let name = name.as_bytes(); - let Some((len, end)) = words(body, b"let", 0, body.len()).into_iter().rev().find_map(|at| array_binding(body, at, name, sizes)) else { + let mut in_scope = words(body, b"let", 0, body.len()).into_iter().rev().filter(|&at| open_at_end(body, at)); + let Some((len, end)) = in_scope.find_map(|at| array_binding(body, at, name, sizes)) else { return 0; }; if may_shrink(body, name, end) { @@ -1640,6 +1657,21 @@ fn bound_len(receiver: &str, body: &[u8], sizes: &Sizes) -> usize { len.max(loop_fill_len(body, name, end, sizes)) } +/// Whether the block holding offset `at` of `body` is still open at the end of `body`: a binding +/// there is still in scope. +fn open_at_end(body: &[u8], at: usize) -> bool { + let mut depth = 0usize; + for &c in &body[at..] { + match c { + b'{' => depth += 1, + b'}' if depth == 0 => return false, + b'}' => depth -= 1, + _ => {} + } + } + true +} + /// For a `let` at `at` that binds `name` (allowing `mut`): the fewest items its array type /// annotation gives (which decides when there is one), else its initializer gives ([`expr_len`]), /// and where the statement ends. `None` for a binding of another name. @@ -2012,10 +2044,11 @@ fn int_literal(text: &str) -> Option { text[..digits].replace('_', "").parse().ok() } -/// `const NAME: T = ;` in a masked file; a name declared more than once keeps -/// its smallest value, and 0 when one of its values is not a literal. +/// `const NAME: T = ;` in a masked file. A name declared more than once with +/// different values, or with a value that is not a literal, is left out (its value is unknown). fn file_consts(file: &[u8]) -> HashMap { - let mut out: HashMap = HashMap::new(); + // `None` for a name declared with a value that is not a literal or with different values. + let mut out: HashMap> = HashMap::new(); for at in words(file, b"const", 0, file.len()) { let start = skip_ws(file, at + 5); let end = start + file[start..].iter().copied().take_while(|&c| is_ident(c)).count(); @@ -2025,12 +2058,14 @@ fn file_consts(file: &[u8]) -> HashMap { let stop = statement_end(file, end); let stmt = norm(&file[end..stop]); let Some((_, value)) = stmt.split_once('=') else { continue }; - let value = int_literal(value).unwrap_or(0); + let value = int_literal(value); let name = String::from_utf8_lossy(&file[start..end]).into_owned(); let slot = out.entry(name).or_insert(value); - *slot = (*slot).min(value); + if *slot != value { + *slot = None; + } } - out + out.into_iter().filter_map(|(name, value)| Some((name, value?))).collect() } /// A `let` of a plain name: the name, where the statement ends, and whether it binds an expression @@ -2039,6 +2074,8 @@ struct Binding { name: Vec, end: usize, counts: bool, + /// The local whose method the initializer calls (`xs` in `let n = xs.len()`). + source: Option>, } /// Every `let` of a plain name in `body`, in order. @@ -2056,19 +2093,24 @@ fn bindings(body: &[u8]) -> Vec { } let stop = statement_end(body, end); let stmt = norm(&body[end..stop]); - let counts = stmt.split_once('=').is_some_and(|(_, init)| SIZE_CHECKS.iter().any(|g| init.contains(g))); - Some(Binding { name: body[start..end].to_vec(), end: stop, counts }) + let init = stmt.split_once('=').map_or("", |(_, init)| init); + let counts = SIZE_CHECKS.iter().any(|g| init.contains(g)); + let ident = init.bytes().take_while(|&c| is_ident(c)).count(); + let source = (ident > 0 && init[ident..].starts_with('.')).then(|| init.as_bytes()[..ident].to_vec()); + Some(Binding { name: body[start..end].to_vec(), end: stop, counts, source }) }) .collect() } /// Whether `body[from..to]` (an assertion operand) reads a local whose binding reaching that -/// point checks a size and was not assigned since. +/// point checks a size and was not assigned since, of a collection that no later code may shrink +/// or replace. fn reads_counted_local(body: &[u8], all: &[Binding], from: usize, to: usize) -> bool { all.iter().filter(|b| b.counts && b.name != b"_").any(|b| { words(body, &b.name, from, to).into_iter().any(|p| { let reaching = all.iter().rfind(|o| o.name == b.name && o.end <= p); - reaching.is_some_and(|r| r.counts && !may_shrink(&body[..p], &r.name, r.end)) + reaching + .is_some_and(|r| r.counts && !may_shrink(&body[..p], &r.name, r.end) && r.source.as_ref().is_none_or(|s| !may_shrink(body, s, r.end))) }) }) } @@ -2089,13 +2131,20 @@ fn is_weak(cond: &str) -> bool { fn only_weak(v: &View) -> Option { let all_weak = v.asserts.iter().all(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && is_weak(&v.first_arg(a))); - let other = contains(v.body(), b"panic!") || contains(v.body(), b".unwrap_err()") || contains(v.body(), b".expect_err("); + // Failure messages run only after an assertion has failed, so a check there does not count. + let body = v.body_without_messages(); + let other = contains(&body, b"panic!") || contains(&body, b".unwrap_err()") || contains(&body, b".expect_err("); if v.asserts.is_empty() || !all_weak || other || v.delegates || v.should_panic { return None; } Some(v.whole(Rule::OnlyWeak, format!("its {} assertion(s) only check is_ok/is_some/non-empty", v.asserts.len()))) } +/// Methods that return the next value of something each time (`assert_ne!(it.next(), it.next())` +/// compares two items). +const ADVANCING: &[&str] = + &["next", "next_back", "pop", "pop_front", "pop_back", "recv", "try_recv", "read_line", "take", "tick", "step", "advance", "now", "elapsed"]; + fn self_compare(v: &View) -> Vec { v.asserts .iter() @@ -2105,7 +2154,8 @@ fn self_compare(v: &View) -> Vec { let (l, r) = (v.file.src_norm(*a.args.first()?), v.file.src_norm(right)); let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&')); let calls_with_args = l.replace("()", "").contains(['(', '!']); - (l == r && !l.is_empty() && !calls_with_args).then(|| { + let advances = ADVANCING.iter().any(|m| l.contains(&format!(".{m}()"))); + (l == r && !l.is_empty() && !calls_with_args && !advances).then(|| { let mut h = v.hit(a.at, Rule::SelfCompare, format!("{}! compares `{l}` with itself", a.name)); let end = right.0 + v.file.m[right.0..right.1].trim_ascii_end().len(); h.last = v.file.lines.of(end.saturating_sub(1)); @@ -2373,7 +2423,10 @@ fn ignore_hits(file: &File) -> Vec { }; if !reason { let test = file.tests.iter().find(|t| t.fn_at > at).map_or("", |t| t.name.as_str()); - out.push(file.hit(at - 2, Rule::IgnoreWithoutReason, test, "#[ignore] gives no reason".into())); + // The hit sits on `#[ignore`; its span reaches the attribute's `]`, past a reason on a later line. + let mut hit = file.hit(at - 2, Rule::IgnoreWithoutReason, test, "#[ignore] gives no reason".into()); + hit.last = matching(m, at - 1).map_or(hit.line, |close| file.lines.of(close)); + out.push(hit); } } out @@ -3579,7 +3632,7 @@ mod tests { #[test] fn workflow_variables_count_as_set() { let names: Vec = upper_words("env:\n AFFINITY_CORPUS_REQUIRED: 1\n run: X=1 cargo test # A\n").collect(); - assert_eq!(names, ["AFFINITY_CORPUS_REQUIRED"]); + assert_eq!(names, ["AFFINITY_CORPUS_REQUIRED", "X"]); assert!(set_by_system("CARGO_MANIFEST_DIR") && set_by_system("HOME") && !set_by_system("MY_SAMPLES")); } @@ -3729,4 +3782,73 @@ mod tests { let walk = "#[test]\nfn t() {\n let n = files().filter(|p| p.ends_with(r#\".rs\"#)).count();\n assert_eq!(n, 4);\n}\n"; assert_eq!(hits(walk), [(3, "reads-source")]); } + + #[test] + fn single_letter_variables_set_in_ci_count() { + let src = "#[test]\nfn t() {\n let dir = std::env::var(\"X\");\n assert_eq!(f(dir), 3);\n}\n"; + assert_eq!(hits(src), [(3, "env-gate-unset")]); + let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words("env:\n X: 1\n").collect() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), []); + } + + #[test] + fn tests_with_non_ascii_names_are_checked() { + let src = "#[test]\nfn échec() {\n assert!(f().is_ok());\n}\n"; + assert_eq!(lint_file("crates/x/src/tests.rs", src, &ctx()).iter().map(|h| (h.line, h.test.as_str())).collect::>(), [(2, "échec")]); + } + + #[test] + fn block_comment_allows_need_a_reason_before_the_closing_delimiter() { + let bare = "#[test]\nfn t() {\n thread::sleep(D); /* test-lint: allow sleep */\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(bare), [(3, "sleep")]); + assert_eq!(hits(&bare.replace("sleep */", "sleep the clock has a 2 ms step */")), []); + } + + #[test] + fn bindings_out_of_scope_do_not_guard_all() { + let src = "#[test]\nfn t() {\n let xs: Vec = vec![];\n {\n let xs = vec![1];\n use_it(&xs);\n }\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), [(8, "all-unguarded")]); + let inside = "#[test]\nfn t() {\n let xs: Vec = vec![];\n {\n let xs = vec![1];\n assert!(xs.iter().all(|x| *x > 0));\n }\n use_it(&xs);\n}\n"; + assert_eq!(hits(inside), []); + } + + #[test] + fn constants_with_several_values_are_unknown() { + let src = "mod a { const START: usize = 0; }\nmod b {\nconst START: usize = 2;\nconst END: usize = 2;\n#[test]\nfn t() {\n let xs: Vec = (START..END).collect();\n assert!(xs.iter().all(|x| *x > 0));\n}\n}\n"; + assert_eq!(hits(src), [(8, "all-unguarded")]); + assert_eq!(hits(&src.replace("mod a { const START: usize = 0; }\n", "").replace("END: usize = 2", "END: usize = 4")), []); + } + + #[test] + fn a_count_stops_guarding_when_its_collection_changes() { + let src = + "#[test]\nfn t() {\n let mut xs = f();\n let n = xs.len();\n assert_eq!(n, 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), []); + let cleared = src.replace(" assert_eq!(n, 1);", " xs.clear();\n assert_eq!(n, 1);"); + assert_eq!(hits(&cleared), [(7, "all-unguarded")]); + } + + #[test] + fn checks_in_failure_messages_do_not_end_only_weak() { + let src = "#[test]\nfn t() {\n assert!(parse(input).is_ok(), \"{:?}\", probe().unwrap_err());\n}\n"; + assert_eq!(hits(src), [(2, "only-weak")]); + assert_eq!(hits(&src.replace(" assert!", " let _ = probe().unwrap_err();\n assert!")), []); + } + + #[test] + fn advancing_calls_are_not_self_comparisons() { + for operand in ["it.next()", "q.pop_front()", "rx.recv()"] { + let src = format!("#[test]\nfn t() {{\n assert_ne!({operand}, {operand});\n}}\n"); + assert_eq!(hits(&src), [], "{operand}"); + } + assert_eq!(hits("#[test]\nfn t() {\n assert_eq!(x.len(), x.len());\n}\n"), [(3, "self-compare")]); + } + + #[test] + fn ignore_spans_reach_a_reason_on_the_next_line() { + let src = "#[test]\n#[ignore =\n \"\"]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.iter().map(|h| (h.rule, h.line, h.first, h.last)).collect::>(), [(Rule::IgnoreWithoutReason, 2, 2, 3)]); + assert!(touches(&found[0], Some(&[3].into_iter().collect())), "a change to the reason alone"); + } } From 7aee17deaaf7f00cd078ffff57cfde8299258b82 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:25:15 -0800 Subject: [PATCH 48/69] Tests: the 3D face-limit and gray-level smoothing tests check the same cases with small inputs The two Extrude & Bevel tests of the faces an object's solids keep together built members and strokes from 16,384-corner polygons until they passed MAX_OBJECT_FACES. They took 230 s and 23.5 s on CI. The solids code now reads the limit through object_face_limit(), which tests can lower on their own thread (OBJECT_FACE_LIMIT), and both tests build 64-corner polygons against a limit of exactly three members' or three strokes' faces. The limit is now met exactly, so the tests also check that a solid at the limit still draws. Outside the crate's own tests, object_face_limit() is MAX_OBJECT_FACES. The smoothing test of every pair of gray levels ran the filter on 262,144 one-pixel-pair images, and each pass along a column started two threads. It now puts every pair in one 2-pixel-wide image and one 2-pixel-high image, so it checks the same 65,536 pairs in four passes. --- crates/effects/src/solids.rs | 37 +++++++++++++++++++------- crates/effects/src/solids/tests.rs | 34 ++++++++++++++++++----- crates/effects/src/solids/wireframe.rs | 6 ++--- crates/trace/src/smooth.rs | 30 +++++++++++++++------ 4 files changed, 80 insertions(+), 27 deletions(-) diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index ef1608a5d9..83bb1ca9f7 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -600,9 +600,9 @@ fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { } let (parts, bounds) = solid_parts(shapes, b); if !cast { - return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ())); + return built_solids(id, p, &parts, bounds, object_face_limit()).try_for_each(|r| r.map(|_| ())); } - let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, false, None) + let built = built_solids_cast(id, p, &parts, bounds, object_face_limit(), true, false, None) .map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces))) .collect::, String>>()?; cast_built(id, p, shapes, built).map(|_| ()) @@ -1025,13 +1025,30 @@ thread_local! { /// [`built_solids`] have built on this thread, for the tests. The solids built to cast a shadow /// ([`cast_shadow`]) count too. static SOLID_GEOMETRY_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The limit [`object_face_limit`] gives on this thread: [`MAX_OBJECT_FACES`] unless a test sets + /// a lower one, so that a test of the limit builds small solids. + pub(crate) static OBJECT_FACE_LIMIT: std::cell::Cell = const { std::cell::Cell::new(MAX_OBJECT_FACES) }; +} + +/// Most faces the Extrude & Bevel or Inflate solids of one effect on one object keep together: +/// [`MAX_OBJECT_FACES`]. +#[cfg(not(test))] +fn object_face_limit() -> usize { + MAX_OBJECT_FACES +} + +/// Most faces the Extrude & Bevel or Inflate solids of one effect on one object keep together: +/// [`MAX_OBJECT_FACES`], or the lower limit a test set in [`OBJECT_FACE_LIMIT`]. +#[cfg(test)] +fn object_face_limit() -> usize { + OBJECT_FACE_LIMIT.with(std::cell::Cell::get) } /// The solids Extrude & Bevel (Classic included) or Inflate `id` with parameters `p` builds from /// `parts` ([`solid_parts`]) about `bounds`, one result for each part in order, each built only as /// the iterator reaches it. A stroke's solid past its own limits is `None` (left out of the art, its /// faces not counted); a fill's is an error. The faces of the solids kept count together: once they -/// pass `limit` ([`MAX_OBJECT_FACES`] for the art) the result is an error, and +/// pass `limit` ([`object_face_limit`] for the art) the result is an error, and /// no later part is built. An error ends the iterator. fn built_solids<'a>( id: &'a str, @@ -1211,7 +1228,7 @@ fn rects_overlap(a: Rect, b: Rect) -> bool { /// How many faces [`cut_stroke_faces`] may add to solids painted by `items` that hold `faces` faces /// and whose paint copies take `paint_bytes` so far: as many as keep the faces within -/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as +/// [`object_face_limit`] and the copies within the allowance, each added face counted as /// [`MAX_FACET_COPIES`] copies of the costliest stroke's paint. fn cut_room<'a>(items: impl Iterator, faces: usize, paint_bytes: usize) -> usize { let per_face = items @@ -1225,7 +1242,7 @@ fn cut_room<'a>(items: impl Iterator, faces: usize, p .unwrap_or(0) .max(1); let affordable = crate::revolve::MAX_PAINT_COPIES.saturating_sub(paint_bytes) / per_face; - MAX_OBJECT_FACES.saturating_sub(faces).min(affordable) + object_face_limit().saturating_sub(faces).min(affordable) } /// In `solids`, each solid's part ([`Paints`]), its shape's index and its faces, cut each face of a @@ -2403,7 +2420,7 @@ fn surfaces_with( let map_art = MapArt::of(doc, &fx.id, &p).filter(|_| fx.id == CLASSIC_EXTRUDE); let mut layouts: Vec = vec![]; let mut surfaces_before = 0usize; - let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, membrane, carrier); + let made = built_solids_cast(&fx.id, &p, &parts, bounds, object_face_limit(), cast, membrane, carrier); for (k, ((item, opacity, area, rule, scopes, member), f)) in parts.iter().zip(made).enumerate() { let item: &AppearanceItem = item; let layout = map_art.as_ref().map(|_| { @@ -2471,7 +2488,7 @@ fn surfaces_with( if solids.iter().any(|s| ordered(s.4)) { // A stroke face that passes through a fill wall or another stroke's face is cut where it // does. The pieces count against the limits as the faces did: cutting stops before the - // faces pass MAX_OBJECT_FACES or their paint copies pass the allowance, so an effect that + // faces pass object_face_limit() or their paint copies pass the allowance, so an effect that // draws uncut still draws. let counts: Vec = solids.iter().map(|(.., f, _)| f.len()).collect(); let room = cut_room(solids.iter().map(|(item, ..)| *item), counts.iter().sum(), paint_bytes); @@ -2940,7 +2957,7 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' // their handles. A stroke left out places none of its own. When a fill's solid can't be // built, or the solids together pass the limit, the art draws its source and no piece // places a handle. - let built: Vec = built_solids_cast(INFLATE, &p, &parts, bounds, MAX_OBJECT_FACES, false, true, None) + let built: Vec = built_solids_cast(INFLATE, &p, &parts, bounds, object_face_limit(), false, true, None) .collect::, String>>() .map(|solids| solids.into_iter().flatten().flat_map(|(f, _)| f).collect()) .unwrap_or_default(); @@ -3065,7 +3082,7 @@ pub fn map_surfaces_at(doc: Option<&Document>, n: &Node, item: Option, in let surfaces = vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default(); let facets = vectorcraft_three_d::extrude(area, *rule, bounds, options, view).unwrap_or_default(); kept = kept.saturating_add(facets.len()); - if kept > MAX_OBJECT_FACES { + if kept > object_face_limit() { return None; } listed(&surfaces, &facets, &mut out); @@ -3309,7 +3326,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) Err(e) => return Err(e), }; kept = kept.saturating_add(solid.facets.len()); - if kept > MAX_OBJECT_FACES { + if kept > object_face_limit() { return Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()); } match solid.mesh() { diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 49c301dd75..504fe1d777 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1642,17 +1642,36 @@ fn polygon_node(id: u64, corners: usize) -> Node { Node::path(NodeId(id), path, Appearance::basic(Paint::solid(RED), Paint::None, 0.0)) } +/// Sets the faces the solids of one object keep together ([`OBJECT_FACE_LIMIT`]) to a lower limit +/// on this thread, and sets [`MAX_OBJECT_FACES`] again when dropped, so that a test of the limit +/// builds small solids. +struct FaceLimit(usize); + +impl FaceLimit { + fn set(limit: usize) -> Self { + Self(OBJECT_FACE_LIMIT.with(|l| l.replace(limit))) + } +} + +impl Drop for FaceLimit { + fn drop(&mut self) { + OBJECT_FACE_LIMIT.with(|l| l.set(self.0)); + } +} + /// A group whose members' solids each fit, but not all of them together, draws its source art, and /// the commands that check the effect report the error, as do its mesh and its wireframe; one -/// member fewer, within the limit, draws. +/// member fewer, exactly at the limit, draws. The limit is lowered to three members' faces. #[test] fn a_groups_solids_together_past_the_limit_draw_the_source() { - let member = polygon_node(1, 16_384); + let member = polygon_node(1, 64); let mut alone = member.clone(); alone.appearance.effects.push(fx(EXTRUDE, json!({}))); let [Ok(Some(each))] = solid_faces(EXTRUDE, &alone, MAX_OBJECT_FACES)[..] else { panic!("one solid") }; + let limit = 3 * each; + let _limit = FaceLimit::set(limit); // Members stacked in one place each build the same solid. - let fits = MAX_OBJECT_FACES / each; + let fits = limit / each; let group = |count: usize| { let members = (0..count) .map(|k| { @@ -1703,16 +1722,19 @@ fn an_inflate_frame_places_no_handle_when_a_fill_is_past_the_limits() { } /// A fill and strokes whose solids each fit, but not all of them together, draw the source art, -/// and the strokes after the one past the limit are not left out to make room. +/// and the strokes after the one past the limit are not left out to make room. The limit is +/// lowered to the fill's faces and three strokes'. #[test] fn a_fill_and_strokes_together_past_the_limit_draw_the_source() { - let mut n = polygon_node(1, 16_384); + let mut n = polygon_node(1, 64); n.appearance.effects.push(fx(EXTRUDE, json!({}))); let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(BLUE), 20.0)); n.appearance.items.push(stroke.clone()); // Strokes alike each build the same solid. let [Ok(Some(fill)), Ok(Some(each))] = solid_faces(EXTRUDE, &n, MAX_OBJECT_FACES)[..] else { panic!("a fill's solid and a stroke's") }; - let fits = (MAX_OBJECT_FACES - fill) / each; + let limit = fill + 3 * each; + let _limit = FaceLimit::set(limit); + let fits = (limit - fill) / each; assert!(fits >= 2, "{fill} + {fits} × {each}"); n.appearance.items.extend(std::iter::repeat_n(stroke, fits - 1)); assert!(validate_solid(&n, EXTRUDE, &json!({})).is_ok(), "{fill} + {fits} × {each}"); diff --git a/crates/effects/src/solids/wireframe.rs b/crates/effects/src/solids/wireframe.rs index 65ac8b0f7e..409a5c1dc3 100644 --- a/crates/effects/src/solids/wireframe.rs +++ b/crates/effects/src/solids/wireframe.rs @@ -12,8 +12,8 @@ use vectorcraft_three_d::Facet; use super::{ CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, INFLATE, Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane, - is_three_d, label_of, members, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources, solid_parts, - union_bounds, + is_three_d, label_of, members, object_face_limit, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources, + solid_parts, union_bounds, }; use crate::{GeomContext, is_geometry}; @@ -258,7 +258,7 @@ pub(crate) fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result = (0..=255u8).flat_map(|p| (0..=255u8).map(move |q| (p, q))).collect(); + let n = pairs.len(); + // The pair of pixel `i` in the output of the pass along rows (`true`) or columns. + let pair_of = |along_rows: bool, i: usize| pairs.get(if along_rows { i / 2 } else { i % n }).copied(); + let first_difference = |along_rows: bool, fast: &[u8], slow: &[u8]| { + if fast.len() != slow.len() { + return Some(format!("lengths {} and {}", fast.len(), slow.len())); } + fast.chunks(4).zip(slow.chunks(4)).position(|(a, b)| a != b).map(|i| format!("pair {:?}", pair_of(along_rows, i))) + }; + // Gray, and a mixed pair: the two pixels made from levels `p` and `q`. + type Kind = fn(u8, u8) -> [[u8; 4]; 2]; + let kinds: [Kind; 2] = [|p, q| [[p, p, p, 255], [q, q, q, 255]], |p, q| [[p, q, p ^ q, 255], [q, p, q ^ 0x5a, 255]]]; + for (k, kind) in kinds.into_iter().enumerate() { + let rows: Vec = pairs.iter().flat_map(|&(p, q)| kind(p, q).into_iter().flatten()).collect(); + let columns: Vec = (0..2).flat_map(|side| pairs.iter().flat_map(move |&(p, q)| kind(p, q)[side])).collect(); + let fast = pass(&rows, 2, n, true, &weights); + assert_eq!(first_difference(true, &fast, &reference(&rows, 2, n, true)), None, "kind {k}, along rows"); + let fast = pass(&columns, n, 2, false, &weights); + assert_eq!(first_difference(false, &fast, &reference(&columns, n, 2, false)), None, "kind {k}, along columns"); } } From 13b9e22c4c8881cfad9aa1c832b09d70eddac71d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:29:35 -0800 Subject: [PATCH 49/69] Tests: merge two duplicate engine tests, keeping every assertion Two engine tests ran the same inputs as another test and checked them again with a tighter bound or a second check. - commands_that_do_not_wait_for_a_tool_edit_change_no_document ran every junk case of every non-waiting command on the Single and Multi fixtures, which every_command_with_junk_params also runs. The junk sweep now compares tool_edit_state before and after each of those calls as well as its own panic, interaction and invariant checks. The tool-edit test keeps only the cases that turn each option on and off (option_cases), which the junk sweep does not send. - turned_colored_inflate_facets_and_seams_cover_their_edges_once drew the same turned Inflate in the same solid fill as one case of colored_light_surfaces_match_supersampling_at_internal_facet_edges. That case now carries its bound (at most one RGB channel more than 3 levels off, by no more than 4) and the separate test is removed. Each merged test fails on a fault that only the removed check caught before: document.info bumping the revision on a non-object params value fails every_command_with_junk_params ("document.info "str" [Multi]"), and solid_surface drawing every facet as a fill and a seam stroke fails the supersampling test (2 channels off, at most 5). docs/target-app-parity.md and waits_for_tool_edit's doc comment name the tests that now hold these checks. --- crates/engine/src/command_sets.rs | 4 +- crates/engine/tests/command_sweep.rs | 60 +++++++++++++------ crates/engine/tests/it/three_d_light_color.rs | 35 +++-------- docs/target-app-parity.md | 2 +- 4 files changed, 52 insertions(+), 49 deletions(-) diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 1346dc40c5..3c7db76afe 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -118,8 +118,8 @@ const WAIT_FOR_TOOL_EDIT: &[&str] = &[ /// Does command `id`, run on its own, first apply the edit the active tool is computing on /// another thread and the input held for it ([`Session::finish_tool_edit`])? Every command that /// can edit, select, save or give a document a new revision does; queries that only read do not -/// (`commands_that_do_not_wait_for_a_tool_edit_change_no_document` in the command sweep checks -/// them). A frontend that adds params from +/// (`every_command_with_junk_params` and `commands_that_do_not_wait_for_a_tool_edit_change_no_document` +/// in the command sweep check them). A frontend that adds params from /// its own state (the active artboard) applies them first itself. pub fn waits_for_tool_edit(id: &str) -> bool { find_command(id).is_some_and(|spec| spec.journal || WAIT_FOR_TOOL_EDIT.contains(&id)) diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 67d9b82f76..0fdb272343 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -30,17 +30,27 @@ fn no_panic(r: Result) -> Result Option { + probe_and_compare(fx, id, params, false).0 +} + +/// Run one call as [`probe`] does, returning its failure description, and with `compare`, also +/// `id params [fixture]` when the call changed the session's [`tool_edit_state`], panic or not. +fn probe_and_compare(fx: Fixture, id: &str, params: &Value, compare: bool) -> (Option, Option) { let mut s = fx.session(); + let before = compare.then(|| tool_edit_state(&s)); let r = catch_quiet(|| no_panic(s.execute(id, params))); - match r { + let changed = before.filter(|b| tool_edit_state(&s) != *b).map(|_| format!("{id} {params} [{fx:?}]")); + let failure = match r { Err(msg) => Some(format!("PANIC {id} {params} [{fx:?}]: {msg}")), Ok(_) => { if s.in_interaction() { - return Some(format!("{id} {params} [{fx:?}]: left an interaction open")); + Some(format!("{id} {params} [{fx:?}]: left an interaction open")) + } else { + check_session(&s).err().map(|e| format!("{id} {params} [{fx:?}]: {e}")) } - check_session(&s).err().map(|e| format!("{id} {params} [{fx:?}]: {e}")) } - } + }; + (failure, changed) } #[test] @@ -223,31 +233,43 @@ fn junk_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec { cases } +/// Every command with every junk case in every fixture: no panic, no interaction left open and no +/// broken invariant ([`probe`]). In `Single` and `Multi`, every command that runs at once while the +/// active tool computes an edit on another thread (it does not `waits_for_tool_edit`) also leaves +/// the documents' revisions and selections, the active document and the current paint as they were +/// ([`tool_edit_state`]), as `commands_that_do_not_wait_for_a_tool_edit_change_no_document` checks +/// for the cases that turn each option on and off. #[test] fn every_command_with_junk_params() { let dir = vectorcraft_testkit::TempDir::new("sweep"); let path = safe_path(&dir); let mut failures = vec![]; + let mut changed = vec![]; let mut calls = 0usize; for fx in Fixture::ALL { for c in command_specs() { + let compare = matches!(fx, Fixture::Single | Fixture::Multi) && !vectorcraft_engine::waits_for_tool_edit(c.id); let cases = junk_cases(c, &path); for p in &cases { calls += 1; - if let Some(f) = probe(fx, c.id, p) { - failures.push(f); - } + let (failure, change) = probe_and_compare(fx, c.id, p, compare); + failures.extend(failure); + changed.extend(change); } } } assert!(calls > 5_000, "only {calls} calls"); failures.sort(); failures.dedup(); + changed.sort(); + changed.dedup_by(|a, b| a.split(' ').next() == b.split(' ').next()); assert!( - failures.is_empty(), - "{} failures (of {calls} calls):\n{}", + failures.is_empty() && changed.is_empty(), + "{} failures (of {calls} calls):\n{}\n{} commands change a document without waiting for a tool edit:\n{}", failures.len(), - failures.iter().take(60).cloned().collect::>().join("\n") + failures.iter().take(60).cloned().collect::>().join("\n"), + changed.len(), + changed.join("\n") ); } @@ -262,10 +284,11 @@ fn tool_edit_state(s: &Session) -> ToolEditState { (docs, s.active_index(), s.paint.clone()) } -/// The params the tool-edit sweep sends `c`: junk params, then each documented key turned on and -/// off, with a string under a file or folder key replaced by a location inside `path`'s folder. -fn tool_edit_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec { - let mut cases = junk_cases(c, path); +/// The params the tool-edit sweep sends `c` beyond its junk cases, which the junk sweep checks: +/// each documented key turned on and off, with a string under a file or folder key replaced by a +/// location inside `path`'s folder. +fn option_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec { + let mut cases = vec![]; for k in command_param_keys(c) { for v in [json!(true), json!(false), json!(1), json!("on")] { cases.push(json!({ k.as_str(): safe_value_for_command(c, &k, &v, path) })); @@ -333,7 +356,7 @@ fn sweep_cases_name_files_only_inside_the_temp_folder() { } } let mut cases = junk_params_for_command(c, &path); - cases.extend(tool_edit_cases(c, &path)); + cases.extend(option_cases(c, &path)); cases.extend(serializable_cases(c, &path)); for p in &cases { let Some(o) = p.as_object() else { continue }; @@ -485,8 +508,9 @@ fn sweep_cases_send_the_file_keys_of_the_command_catalog() { /// Every command that runs at once while the active tool computes an edit on another thread (a /// Shape Builder merge), rather than applying the edit first (`waits_for_tool_edit`), leaves the /// documents' revisions and selections, the active document and the current paint as they were, -/// with `{}`, junk params and params that turn its options on and off: the edit, computed for the -/// document as it was, still applies after it. +/// with params that turn its options on and off ([`option_cases`]; `every_command_with_junk_params` +/// checks the same with the junk cases): the edit, computed for the document as it was, still +/// applies after it. #[test] fn commands_that_do_not_wait_for_a_tool_edit_change_no_document() { let dir = vectorcraft_testkit::TempDir::new("sweep"); @@ -494,7 +518,7 @@ fn commands_that_do_not_wait_for_a_tool_edit_change_no_document() { let mut failures = vec![]; for fx in [Fixture::Single, Fixture::Multi] { for c in command_specs().iter().filter(|c| !vectorcraft_engine::waits_for_tool_edit(c.id)) { - let cases = tool_edit_cases(c, &path); + let cases = option_cases(c, &path); for p in &cases { let mut s = fx.session(); let before = tool_edit_state(&s); diff --git a/crates/engine/tests/it/three_d_light_color.rs b/crates/engine/tests/it/three_d_light_color.rs index be06539537..0a6e438a75 100644 --- a/crates/engine/tests/it/three_d_light_color.rs +++ b/crates/engine/tests/it/three_d_light_color.rs @@ -533,7 +533,8 @@ fn seams_against_supersampled(d: &Document, image: &vectorcraft_render::Rendered /// opacity once over the surface. Inflate seen straight on, one layer of facets, has no alpha off, and /// in opaque fills no RGB channel more than 3 levels off. Inflate turned so facets narrow to slivers /// at the edges, and Revolve with a cap over its body, draw facets over other facets, and have no -/// alpha off. +/// alpha off. In the turned Inflate's opaque solid fill, each facet and its seam cover an edge pixel +/// once together, so at most one RGB channel is more than 3 levels off, by no more than 4. #[test] fn colored_light_surfaces_match_supersampling_at_internal_facet_edges() { let lights = json!([ @@ -556,20 +557,21 @@ fn colored_light_surfaces_match_supersampling_at_internal_facet_edges() { let (mut s, _) = setup("threeD.inflate"); let change = json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights,"rotationX":rotation.0,"rotationY":rotation.1}}); s.execute("effect.setParams", &change).unwrap(); - cases.push((format!("inflate {rotation:?}"), s, fills([100, 150], [200, 150]), rotation == (0, 0))); + cases.push((format!("inflate {rotation:?}"), s, fills([100, 150], [200, 150]), rotation == (0, 0), rotation == (50, 35))); } let (mut s, _) = capped_profile(); s.execute("effect.setParams", &json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights}})).unwrap(); - cases.push(("revolve".into(), s, fills([80, 200], [240, 200]), false)); + cases.push(("revolve".into(), s, fills([80, 200], [240, 200]), false, false)); let mut failures = vec![]; - for (name, mut s, fills, one_layer) in cases { + for (name, mut s, fills, one_layer, turned) in cases { for fill in fills { s.execute("paint.setFill", &fill).unwrap(); let image = render(doc(&s)); let (measured, color, max, holes, worst) = seams_against_supersampled(doc(&s), &image); assert!(measured > 2_000, "{name} {fill}: {measured} pixels inside"); let opaque = !fill.to_string().contains("opacity"); - if holes > 0 || (one_layer && opaque && color > 0) { + let edges_once = turned && fill.get("color").is_some(); + if holes > 0 || (one_layer && opaque && color > 0) || (edges_once && (color > 1 || max > 4)) { failures.push(format!( "{name} {fill}: of {measured} pixels, {color} channels off by more than 3 (at most {max}), {holes} alphas off: {worst:?}" )); @@ -579,29 +581,6 @@ fn colored_light_surfaces_match_supersampling_at_internal_facet_edges() { assert!(failures.is_empty(), "{failures:#?}"); } -/// Inflate turned so its facets narrow to slivers at the edges, in an opaque solid fill under two -/// colored lights, against 3x averaged down ([`seams_against_supersampled`]): each facet and its -/// seam cover an edge pixel once together, so at most one RGB channel is more than 3 levels off, by -/// no more than 4, and no alpha is off. -#[test] -fn turned_colored_inflate_facets_and_seams_cover_their_edges_once() { - let lights = json!([ - {"color":"#ff0000","rotation":135,"height":35,"intensity":70}, - {"color":"#0000ff","rotation":-35,"height":25,"intensity":65} - ]); - let (mut s, _) = setup("threeD.inflate"); - let change = json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights,"rotationX":50,"rotationY":35}}); - s.execute("effect.setParams", &change).unwrap(); - s.execute("paint.setFill", &json!({"color":"#ffcc66"})).unwrap(); - let image = render(doc(&s)); - let (measured, color, max, holes, worst) = seams_against_supersampled(doc(&s), &image); - assert!(measured > 2_000, "{measured} pixels inside"); - assert!( - holes == 0 && color <= 1 && max <= 4, - "of {measured} pixels, {color} channels off by more than 3 (at most {max}), {holes} alphas off: {worst:?}" - ); -} - /// The closed facet edges of colored-light surfaces survive SVG and PDF, read back and drawn at /// 1:1, and Expand Appearance: inside the art, every pixel stays opaque and within 6 levels of the /// live art. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4df379b998..b62372f326 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2896,7 +2896,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Evidence for the shared light Color: geometry tests in `tests_lighting`, effect paint tests, command/save/undo/expand and SVG/PDF checks in `three_d_light_color`, and headless picker/reset/preview tests in `tests_revolve`. Revolve keeps smooth colored vector ramps and continuous flat-lit caps. Inflate geometry tests check spherical lighting, shared vertex/edge continuity, concave cell coverage, puffed backs at perspective and legacy single-light/list equivalence; rendered command/export regressions cover smooth shading and editable expansion. Four legacy white-light PNGs matched main byte for byte when this was measured (2026-10-17); since every 3D seam took round joins (2026-11-12), white-light output is expected to differ from them at facet corners ([Seams](three-d.md#seams)); the four scenes were not exported again to measure it; [release measurements](3d-lighting-performance.md) record the colored solid-fill batch and the remaining source-gradient cost. Colored Inflate's facets lie over an underlay of themselves under one clip, so their shared edges show neither the black channel backdrop nor the background ([Seams](three-d.md#seams)); `three_d_light_color::colored_light_surfaces_match_supersampling_at_internal_facet_edges` compares 1:1 with 3x averaged down, and `colored_light_seams_stay_closed_in_svg_pdf_and_expansion` checks SVG, PDF and Expand Appearance. Colored Revolve's faces lie over an underlay of themselves the same way, run by run in a group and with mapped graphics kept after their faces; `colored_revolve_faces_leave_no_alpha_holes_at_one_to_one` checks that no pixel inside the art lets the background through at 1:1 where 3x averaged down is opaque, live, read back from SVG and PDF, and expanded. -Colored Inflate's composited facets that are simple polygons are each one filled path of the facet and its round seam, so a facet edge pixel is covered once instead of by a fill and then a same-color stroke ([Seams](three-d.md#seams)); `three_d_light_color::turned_colored_inflate_facets_and_seams_cover_their_edges_once` bounds the turned (X 50°, Y 35°) solid fill against 3x averaged down, and `lighting::tests::seamed_fill_covers_a_polygon_and_its_seam_once` checks the path's coverage and the facets that keep a fill and a stroke. +Colored Inflate's composited facets that are simple polygons are each one filled path of the facet and its round seam, so a facet edge pixel is covered once instead of by a fill and then a same-color stroke ([Seams](three-d.md#seams)); `three_d_light_color::colored_light_surfaces_match_supersampling_at_internal_facet_edges` bounds the turned (X 50°, Y 35°) solid fill against 3x averaged down, and `lighting::tests::seamed_fill_covers_a_polygon_and_its_seam_once` checks the path's coverage and the facets that keep a fill and a stroke. ## Eyedropper character dimensions (2026-11-11) From ebb84ec16c32313c4590d18e3d8b867b56977c81 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:40:53 -0800 Subject: [PATCH 50/69] xtask: test-lint reports only-weak hits instead of failing on them Replayed over the last 300 merges to main, only-weak would have failed 3 merges on 4 hits, and all 4 were tests where an is_ok or is_some check is the behavior under test (a lease or start file that can be taken again, a never-panic property test, a label found by a search with the row's position in its predicate). Of the 39 only-weak hits in the whole workspace, most are the same kinds: registry and label lookups, still-imports and never-panic tests. only-weak now lists its hits without failing, like all-unguarded. The check fails on self-compare, ignore-without-reason and sleep. With this change the replay fails 0 of 272 merges that change Rust files. --- docs/development.md | 2 +- xtask/src/main.rs | 4 ++-- xtask/src/test_lint.rs | 20 +++++++++++--------- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/docs/development.md b/docs/development.md index efb554b561..604c363dba 100644 --- a/docs/development.md +++ b/docs/development.md @@ -351,7 +351,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 3a0c854486..6f4347e952 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -34,8 +34,8 @@ commands: brands check that user-visible text (labels, params docs, MCP, docs, packaging) names no other vendor's products cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails) test-lint [--base ] [--all] - weak tests in the lines changed since the base: fail on only is_ok/is_some checks, - self-compares, reasonless #[ignore] and sleeps; list unguarded .all(), no assertion, + weak tests in the lines changed since the base: fail on self-compares, reasonless + #[ignore] and sleeps; list only is_ok/is_some checks, unguarded .all(), no assertion, early returns, unset env gates... (xtask/src/test_lint.rs); --all lists every hit by crate and never fails i18n-report list the strings each language's catalog lacks, shown in English (fails only on a diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index f442c9681d..45ae3566d3 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -51,9 +51,8 @@ //! rules about a whole test it can be on any line from the line above the test attribute to the //! `fn` line. An allow without a reason exempts nothing. //! -//! `cargo xtask test-lint` fails on hits of `only-weak`, `self-compare`, `ignore-without-reason` -//! and `sleep` in the lines and tests changed since a base, and lists the other rules' hits there -//! without failing. The base is `--base ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's +//! `cargo xtask test-lint` fails on hits of `self-compare`, `ignore-without-reason` and `sleep` in +//! the lines and tests changed since a base, and lists the other rules' hits there without failing. The base is `--base ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's //! merge commit is checked out, and a shallow checkout fetches that parent); elsewhere the merge //! base of `HEAD` and `upstream/main` or `origin/main`. Uncommitted and untracked files count as //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the @@ -168,7 +167,7 @@ impl Rule { /// Whether a hit on a changed line fails the command. The other rules only report. pub fn fails(self) -> bool { - matches!(self, Rule::OnlyWeak | Rule::SelfCompare | Rule::IgnoreWithoutReason | Rule::Sleep) + matches!(self, Rule::SelfCompare | Rule::IgnoreWithoutReason | Rule::Sleep) } fn from_id(id: &str) -> Option { @@ -3606,16 +3605,19 @@ mod tests { #[test] fn only_failing_rules_fail_the_check() { let failing: Vec<&str> = Rule::ALL.into_iter().filter(|r| r.fails()).map(Rule::id).collect(); - assert_eq!(failing, ["only-weak", "self-compare", "ignore-without-reason", "sleep"]); + assert_eq!(failing, ["self-compare", "ignore-without-reason", "sleep"]); let weak = "#[test]\nfn weak() {\n assert!(f().is_ok());\n}\n"; let unguarded = "#[test]\nfn all() {\n assert!(f().iter().all(|x| valid(x)));\n}\n"; + let skipped = "#[test]\n#[ignore]\nfn skipped() {\n assert_eq!(f(), 1);\n}\n"; let hits_of = |src: &str| lint_file("crates/x/src/tests.rs", src, &ctx()); assert_eq!(finish(&hits_of(unguarded), 0, 1, "base"), Ok(()), "all-unguarded only reports"); - let both = hits_of(&format!("{weak}{unguarded}")); - assert_eq!(both.len(), 2); - let Err(message) = finish(&both, 0, 1, "base") else { panic!("only-weak fails the check") }; + assert_eq!(finish(&hits_of(weak), 0, 1, "base"), Ok(()), "only-weak only reports"); + let all = hits_of(&format!("{weak}{unguarded}{skipped}")); + assert_eq!(all.len(), 3); + let Err(message) = finish(&all, 0, 1, "base") else { panic!("ignore-without-reason fails the check") }; assert!(message.starts_with("1 test-lint hit(s)"), "{message}"); - assert!(message.contains("[only-weak] `weak`") && !message.contains("[all-unguarded]"), "{message}"); + assert!(message.contains("[ignore-without-reason] `skipped`"), "{message}"); + assert!(!message.contains("[only-weak]") && !message.contains("[all-unguarded]"), "{message}"); assert_eq!(finish(&[], 3, 1, "base"), Ok(())); } From fbcc1627c41afd7391e668d42f3ec3a943351545 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:46:34 -0800 Subject: [PATCH 51/69] xtask: test-lint counts items under cfg(all(test, ...)) as test code test_regions matched only the exact `#[cfg(test)]`, so helpers in a module under `#[cfg(all(test, windows))]` or `#[cfg(all(test, not(target_arch = "wasm32")))]` (as in apps/vectorcraft-web/src/file_drops.rs) were not test code: a sleep in such a helper passed the check, and its asserting helpers were not found. A cfg predicate now counts when it is `test` or an `all(...)` with such a predicate among its arguments, at any depth and with any spacing. `any(test, ...)`, `not(test)` and `feature = "test"` do not count. --- xtask/src/test_lint.rs | 53 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 47 insertions(+), 6 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 45ae3566d3..bfa4f4728c 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -41,7 +41,8 @@ //! that keeps files ending in `.rs`), outside the source audits in [`SOURCE_AUDITS`]. //! //! Test code is a test file (`tests.rs`, `tests_*.rs`, `*_tests.rs`, a file in a `tests` or -//! `benches` folder, `crates/testkit`), an item under `#[cfg(test)]`, or a test function. +//! `benches` folder, `crates/testkit`), an item under `#[cfg(test)]` or `#[cfg(all(test, …))]`, +//! or a test function. //! //! An asserting helper is a function or macro in the crate's test code (or in `crates/testkit`) //! that asserts, panics or calls one that does (every one of that name, when there are several), @@ -972,20 +973,52 @@ fn is_test_file(path: &str) -> bool { || path.starts_with("crates/testkit/") } -/// The byte ranges of test code in a file: all of a test file, else each item under -/// `#[cfg(test)]` that has a body in the file, and each test function. +/// Whether a `cfg` predicate holds only in test builds: `test`, or an `all(…)` with such a +/// predicate among its arguments. +fn cfg_requires_test(pred: &[u8]) -> bool { + let pred: Vec = pred.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect(); + if pred == b"test" { + return true; + } + let Some(args) = pred.strip_prefix(b"all(").and_then(|a| a.strip_suffix(b")")) else { return false }; + let mut depth = 0usize; + let mut start = 0; + for (i, &c) in args.iter().enumerate() { + match c { + b'(' => depth += 1, + b')' => depth = depth.saturating_sub(1), + b',' if depth == 0 => { + if cfg_requires_test(&args[start..i]) { + return true; + } + start = i + 1; + } + _ => {} + } + } + cfg_requires_test(&args[start..]) +} + +/// The byte ranges of test code in a file: all of a test file, else each item under a `#[cfg(…)]` +/// that holds only in test builds ([`cfg_requires_test`]) and has a body in the file, and each +/// test function. fn test_regions(path: &str, m: &[u8], tests: &[TestFn]) -> Vec<(usize, usize)> { if is_test_file(path) { return vec![(0, m.len())]; } let mut out: Vec<(usize, usize)> = tests.iter().map(|t| (t.attr, t.close)).collect(); for at in words(m, b"cfg", 0, m.len()) { - let attr = skip_ws(m, at + "cfg".len()); - if !m[..at].ends_with(b"#[") || !m[attr..].starts_with(b"(test)]") { + let open = skip_ws(m, at + "cfg".len()); + if !m[..at].ends_with(b"#[") || m.get(open) != Some(&b'(') { + continue; + } + let Some(close) = matching(m, open) else { continue }; + let end = skip_ws(m, close + 1); + if m.get(end) != Some(&b']') || !cfg_requires_test(&m[open + 1..close]) { continue; } // The item's body: the first `{` before any `;` (`mod tests;` has none here). - let after = attr + "(test)]".len(); + let after = end + 1; let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; if let (b'{', Some(close)) = (m[open], matching(m, open)) { out.push((at, close)); @@ -3517,6 +3550,14 @@ mod tests { assert_eq!(hits_in("xtask/src/test_lint.rs", shipped, &ctx()), [], "a name that only starts with test is not a test file"); let after = "#[cfg(test)]\nmod tests {\n fn w() { thread::sleep(D); }\n}\npub fn later() {\n thread::sleep(D);\n}\n"; assert_eq!(hits_in("crates/x/src/lib.rs", after, &ctx()), [(3, "sleep")], "code after a #[cfg(test)] module is not test code"); + for gate in ["all(test, windows)", "all( test , not(target_arch = \"wasm32\") )", "all(feature = \"x\", all(unix, test))"] { + let gated = format!("#[cfg({gate})]\nmod tests {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); + assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [(3, "sleep")], "{gate} holds only in tests"); + } + for gate in ["any(test, feature = \"x\")", "not(test)", "all(unix, not(test))", "feature = \"test\""] { + let gated = format!("#[cfg({gate})]\nmod helpers {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); + assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [], "{gate} also holds outside tests"); + } for test_file in [ "crates/x/src/tests.rs", "crates/x/src/tests_wheel.rs", From 6d263fc3c6c3557cfa5fe81ec90afcaaa3e854c8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:11:10 -0800 Subject: [PATCH 52/69] Docs: readiness note lists the live objects and warped images the editing copy keeps --- docs/target-app-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c19c35b4f3..7b36616e68 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -438,8 +438,8 @@ The discounts, with the evidence: #868), guides lost (#779), slower opening (#758), live effects, brushes and symbols as their drawn look (#637). VectorCraft's PDF-compatible `.ai` carries an editing copy of the art (layers, groups, paths, colors, gradients, patterns, images, transparency, opacity masks, clipping, type as text and symbols), with live effects kept only - on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, other objects' effects other than geometry - effects left out, and live objects written as their art; the legacy `.ai` of version 7 it also writes keeps layers, groups and type as text (one + on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports and on images with a Warp effect that qualify, other objects' effects other than geometry + effects left out, and live objects written as their art, except the graphs, envelopes, blends, symbol instances and gradient meshes that qualify (the File formats row and the editing-copy evidence below give the limits); the legacy `.ai` of version 7 it also writes keeps layers, groups and type as text (one artboard per file, no transparency) but hasn't been tested by users yet (#868). That blocks beta (the main-format rule) for people who hand files back to Illustrator users, but it doesn't stop someone opening and reworking their own archive. - **Interaction fidelity (×0.9).** Pen, Direct Selection, smart guides and snapping are deep From 050634b6ad44ddefe938b4e636cc9f925bbc5b2d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:19:05 -0800 Subject: [PATCH 53/69] xtask: test-lint skips declared-only items and unapplied should_panic - Functions and macros declared inside a test no longer count as its assertions or calls; a call to one still counts as a helper call. - `should_panic` exempts a test only as an applied attribute: `#[should_panic]`, or inside `#[cfg_attr(test, ...)]`. - `only-weak` strips parentheses around the whole condition, so `assert!((x.is_ok()))` is classified like `assert!(x.is_ok())`. - `#[ cfg(test)]` and attributes with comments between `#`, `[` and `cfg` mark test code like the compact form. --- xtask/src/test_lint.rs | 114 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 104 insertions(+), 10 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index bfa4f4728c..8609ace2f5 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1009,7 +1009,9 @@ fn test_regions(path: &str, m: &[u8], tests: &[TestFn]) -> Vec<(usize, usize)> { let mut out: Vec<(usize, usize)> = tests.iter().map(|t| (t.attr, t.close)).collect(); for at in words(m, b"cfg", 0, m.len()) { let open = skip_ws(m, at + "cfg".len()); - if !m[..at].ends_with(b"#[") || m.get(open) != Some(&b'(') { + // Whitespace and comments (masked to spaces) may separate `#`, `[` and `cfg`. + let outer_attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + if !outer_attr || m.get(open) != Some(&b'(') { continue; } let Some(close) = matching(m, open) else { continue }; @@ -1079,8 +1081,8 @@ fn checking<'a>(defs: impl Iterator + Clone) -> HashSet } } -/// The `fn` or `macro_rules!` at `at`. -fn definition(m: &[u8], at: usize) -> Option { +/// The name, kind (`true` for a macro) and body braces of the `fn` or `macro_rules!` at `at`. +fn item_at(m: &[u8], at: usize) -> Option<(&[u8], bool, usize, usize)> { let is_macro = m[at..].starts_with(b"macro_rules"); let mut start = skip_ws(m, at + if is_macro { "macro_rules".len() } else { 2 }); if is_macro { @@ -1094,8 +1096,13 @@ fn definition(m: &[u8], at: usize) -> Option { if m[open] != b'{' { return None; } - let close = matching(m, open)?; - let name = String::from_utf8_lossy(&m[start..end]).into_owned(); + Some((&m[start..end], is_macro, open, matching(m, open)?)) +} + +/// The `fn` or `macro_rules!` at `at`. +fn definition(m: &[u8], at: usize) -> Option { + let (name, is_macro, open, close) = item_at(m, at)?; + let name = String::from_utf8_lossy(name).into_owned(); let called = calls(m, open, close).into_iter().filter(|(_, method)| !method).map(|(n, _)| n).collect(); Some((if is_macro { format!("{name}!") } else { name }, checks_itself(m, open, close), called)) } @@ -1107,6 +1114,9 @@ struct File<'a> { path: &'a str, src: &'a [u8], m: Vec, + /// [`File::m`] with the functions and macros declared inside each test blanked: declaring + /// one does not run its body ([`executed`]). + exec: Vec, lines: Lines, tests: Vec, /// The test code ([`test_regions`]). @@ -1148,7 +1158,8 @@ pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { let m = mask(src); let tests = tests_in(&m); let regions = test_regions(path, &m, &tests); - let file = File { path, src: src.as_bytes(), m, lines: Lines::new(src), tests, regions }; + let exec = executed(&m, &tests); + let file = File { path, src: src.as_bytes(), m, exec, lines: Lines::new(src), tests, regions }; let mut hits: Vec = file.tests.iter().flat_map(|t| test_hits(&file, t, ctx)).collect(); hits.extend(ignore_hits(&file)); hits.extend(sleep_hits(&file)); @@ -1162,6 +1173,20 @@ pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { hits } +/// `m` with each `fn` and `macro_rules!` declared inside a test's body replaced by spaces, from +/// its keyword to its closing brace. A call to one stays, so it can still count as a helper call. +fn executed(m: &[u8], tests: &[TestFn]) -> Vec { + let mut out = m.to_vec(); + for t in tests { + for at in words(m, b"fn", t.open, t.close).into_iter().chain(words(m, b"macro_rules", t.open, t.close)) { + if let Some((_, _, _, close)) = item_at(m, at).filter(|&(_, _, _, close)| close < t.close) { + blank(&mut out, at, close + 1); + } + } + } + out +} + /// `(line, rule)` of each exemption comment that names a rule and a reason. /// A marker counts only inside a comment: masked (`m`) there, and kept when only literals are /// masked. @@ -1191,7 +1216,7 @@ struct View<'a> { } fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { - let m = &file.m; + let m = &file.exec; let asserts: Vec = macro_calls(m, t.open, t.close).into_iter().filter(|c| is_assert_macro(&c.name)).collect(); let none = HashSet::new(); let helpers = ctx.helpers.get(&crate_of(file.path)).unwrap_or(&none); @@ -1199,7 +1224,7 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { .iter() .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)); let checks = checks_itself(m, t.open, t.close); - let should_panic = contains(&m[t.attr..t.fn_at], b"should_panic"); + let should_panic = should_panic_attr(m, t.attr, t.fn_at); let v = View { file, t, asserts, delegates, checks, should_panic }; let mut hits = all_unguarded(&v); hits.extend(self_compare(&v)); @@ -1209,6 +1234,27 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { hits } +/// Whether the attributes in `m[from..to]` include an applied `should_panic`: `#[should_panic]`, +/// `#[should_panic(…)]`, or one inside `#[cfg_attr(test, …)]`. Another `cfg_attr` predicate may +/// not hold, so it does not count. +fn should_panic_attr(m: &[u8], from: usize, to: usize) -> bool { + let attached = words(m, b"should_panic", from, to).into_iter().any(|at| { + let before = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + before && matches!(m.get(skip_ws(m, at + "should_panic".len())), Some(b']' | b'(')) + }); + attached + || words(m, b"cfg_attr", from, to).into_iter().any(|at| { + let open = skip_ws(m, at + "cfg_attr".len()); + let Some(close) = matching(m, open).filter(|&c| m[open] == b'(' && c < to) else { return false }; + let args = split_args(m, open + 1, close); + let name = |&(f, t): &(usize, usize)| { + let a = norm(&m[f..t]); + a == "should_panic" || a.starts_with("should_panic(") + }; + args.first().is_some_and(|&(f, t)| norm(&m[f..t]) == "test") && args.iter().skip(1).any(name) + }) +} + impl View<'_> { fn hit(&self, at: usize, rule: Rule, note: String) -> Hit { self.file.hit(at, rule, &self.t.name, note) @@ -1223,7 +1269,7 @@ impl View<'_> { } fn body(&self) -> &[u8] { - &self.file.m[self.t.open..self.t.close] + &self.file.exec[self.t.open..self.t.close] } /// The masked body with assertion failure-message arguments replaced by spaces. @@ -2149,8 +2195,9 @@ fn reads_counted_local(body: &[u8], all: &[Binding], from: usize, to: usize) -> /// Whether an assertion's (masked, whitespace-free) condition only says that there is a value. fn is_weak(cond: &str) -> bool { + let cond = unparenthesized(cond); let (negated, expr) = match cond.strip_prefix('!') { - Some(rest) => (true, rest), + Some(rest) => (true, unparenthesized(rest)), None => (false, cond), }; let plain = |rest: &str| !["&&", "||", "==", "!=", "<", ">"].iter().any(|op| rest.contains(op)); @@ -2161,6 +2208,14 @@ fn is_weak(cond: &str) -> bool { suffix(".is_ok()") || suffix(".is_some()") || suffix(".len()>0") || suffix(".len()!=0") || suffix(".len()>=1") } +/// `expr` without the balanced parentheses around all of it (`((a.is_ok()))` gives `a.is_ok()`). +fn unparenthesized(mut expr: &str) -> &str { + while expr.starts_with('(') && matching(expr.as_bytes(), 0) == Some(expr.len() - 1) { + expr = &expr[1..expr.len() - 1]; + } + expr +} + fn only_weak(v: &View) -> Option { let all_weak = v.asserts.iter().all(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && is_weak(&v.first_arg(a))); // Failure messages run only after an assertion has failed, so a check there does not count. @@ -3223,6 +3278,41 @@ mod tests { assert_eq!(hits(refusal), [], "is_err is not on the plan's list"); let compound = "#[test]\nfn t() {\n assert!(a.is_some() && a == Some(2));\n}\n"; assert_eq!(hits(compound), []); + for cond in ["(parse(\"x\").is_ok())", "((parse(\"x\").is_ok()))", "!(list().is_empty())", "(!list().is_empty())"] { + let src = format!("#[test]\nfn t() {{\n assert!({cond});\n}}\n"); + assert_eq!(hits(&src), [(2, "only-weak")], "{cond}"); + } + let grouped = "#[test]\nfn t() {\n assert!((a.is_some()) && (a == Some(2)));\n}\n"; + assert_eq!(hits(grouped), [], "parentheses around one side of a comparison stay"); + } + + #[test] + fn functions_declared_in_a_test_count_only_when_called() { + let unused = "#[test]\nfn t() {\n fn unused() {\n assert_eq!(1, 1);\n }\n assert!(parse(\"x\").is_ok());\n}\n"; + assert_eq!(hits(unused), [(2, "only-weak")], "a declared function's assertion does not run"); + let macro_only = "#[test]\nfn t() {\n macro_rules! check {\n () => { assert_eq!(1, 1) };\n }\n f();\n}\n"; + assert_eq!(hits(macro_only), [(2, "no-assertion")], "a declared macro's assertion does not run"); + let called = unused.replace(" assert!(parse", " unused();\n assert!(parse"); + let files = [("crates/x/src/tests.rs".to_owned(), called.clone())]; + let with_helpers = Ctx { helpers: asserting_helpers(&files), ..ctx() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &called, &with_helpers), [], "a call to it checks"); + } + + #[test] + fn should_panic_counts_only_when_applied() { + let weak = "#[test]\nfn t() {\n assert!(parse(\"x\").is_ok());\n}\n"; + for attr in [ + "#[should_panic]", + "#[ should_panic(expected = \"x\") ]", + "#[cfg_attr(test, should_panic)]", + "#[cfg_attr( test , should_panic(expected = \"x\"))]", + ] { + assert_eq!(hits(&format!("{attr}\n{weak}")), [], "{attr}"); + } + for attr in ["#[cfg_attr(any(), should_panic)]", "#[cfg_attr(windows, should_panic)]", "#[doc = \"should_panic\"]", "#[allow(should_panic)]"] + { + assert_eq!(hits(&format!("{attr}\n{weak}")), [(3, "only-weak")], "{attr}"); + } } #[test] @@ -3554,6 +3644,10 @@ mod tests { let gated = format!("#[cfg({gate})]\nmod tests {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [(3, "sleep")], "{gate} holds only in tests"); } + for attr in ["#[ cfg(all(test, unix))]", "#[/* test-only */cfg(test)]", "# [cfg (test)]"] { + let gated = format!("{attr}\nmod tests {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); + assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [(3, "sleep")], "{attr}"); + } for gate in ["any(test, feature = \"x\")", "not(test)", "all(unix, not(test))", "feature = \"test\""] { let gated = format!("#[cfg({gate})]\nmod helpers {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [], "{gate} also holds outside tests"); From 81cc0fc7973c71bbb5b52c41461669d099088fea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:49:09 -0800 Subject: [PATCH 54/69] Tests: nine engine integration test files join the tests/it binary blend_render_consistency, direct_handle_mirror, ellipse_drag_anchors, eraser_open_fill, group3_reference, path_fill_hits, pen_space_handle, preflight and scissors_snap were each a test binary of their own. They now are modules of crates/engine/tests/it, with their tests unchanged, so the engine's tests link nine fewer binaries. The files that stay separate change process-wide state (installed plug-ins, Safe Mode, the font database, color settings, the working directory), are run by name from CI or xtask (the Affinity corpus tests, script_corpus, import_fuzz), or compile for about a minute on their own (command_sweep), which would make every edit to tests/it rebuild it. Docs that named the old paths name the new ones, and the preflight command in docs/production-preflight.md runs `--test it preflight::`. --- crates/engine/Cargo.toml | 2 +- .../{ => it}/blend_render_consistency.rs | 1 - .../tests/{ => it}/direct_handle_mirror.rs | 1 - .../tests/{ => it}/ellipse_drag_anchors.rs | 1 - .../engine/tests/{ => it}/eraser_open_fill.rs | 2 -- .../engine/tests/{ => it}/group3_reference.rs | 0 crates/engine/tests/it/main.rs | 9 ++++++++ .../engine/tests/{ => it}/path_fill_hits.rs | 1 - .../engine/tests/{ => it}/pen_space_handle.rs | 2 -- crates/engine/tests/{ => it}/preflight.rs | 2 -- crates/engine/tests/{ => it}/scissors_snap.rs | 1 - docs/gaps.md | 10 ++++----- docs/production-preflight.md | 2 +- docs/roadmap.md | 2 +- docs/target-app-parity.md | 22 +++++++++---------- docs/ui-parity.md | 14 ++++++------ 16 files changed, 35 insertions(+), 37 deletions(-) rename crates/engine/tests/{ => it}/blend_render_consistency.rs (99%) rename crates/engine/tests/{ => it}/direct_handle_mirror.rs (99%) rename crates/engine/tests/{ => it}/ellipse_drag_anchors.rs (99%) rename crates/engine/tests/{ => it}/eraser_open_fill.rs (99%) rename crates/engine/tests/{ => it}/group3_reference.rs (100%) rename crates/engine/tests/{ => it}/path_fill_hits.rs (99%) rename crates/engine/tests/{ => it}/pen_space_handle.rs (99%) rename crates/engine/tests/{ => it}/preflight.rs (99%) rename crates/engine/tests/{ => it}/scissors_snap.rs (99%) diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 027ae10251..406851393a 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -116,7 +116,7 @@ zune-core = { workspace = true } # JPEG XL files for the import fuzz tests (tests/import_fuzz.rs). craft-jxl = { workspace = true } # vectorcraft-doc's Group 3 TIFF reader before craft-stream-codecs, the reference -# tests/group3_reference.rs compares it with. +# tests/it/group3_reference.rs compares it with. hayro-ccitt = { workspace = true } craft-stream-codecs = { workspace = true } vectorcraft-affinity = { workspace = true, features = ["synth"] } diff --git a/crates/engine/tests/blend_render_consistency.rs b/crates/engine/tests/it/blend_render_consistency.rs similarity index 99% rename from crates/engine/tests/blend_render_consistency.rs rename to crates/engine/tests/it/blend_render_consistency.rs index fdc2fb3b93..fa69885ad7 100644 --- a/crates/engine/tests/blend_render_consistency.rs +++ b/crates/engine/tests/it/blend_render_consistency.rs @@ -1,5 +1,4 @@ //! Blend edits invalidate every pixel they change, including keys aligned to a curved spine. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::sync::Arc; diff --git a/crates/engine/tests/direct_handle_mirror.rs b/crates/engine/tests/it/direct_handle_mirror.rs similarity index 99% rename from crates/engine/tests/direct_handle_mirror.rs rename to crates/engine/tests/it/direct_handle_mirror.rs index 30326d8e74..bfe8db75a0 100644 --- a/crates/engine/tests/direct_handle_mirror.rs +++ b/crates/engine/tests/it/direct_handle_mirror.rs @@ -1,5 +1,4 @@ //! Temporary Cmd/Control symmetry while Direct Selection drags an existing handle. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::{Value, json}; use vectorcraft_doc::{Node, NodeId}; diff --git a/crates/engine/tests/ellipse_drag_anchors.rs b/crates/engine/tests/it/ellipse_drag_anchors.rs similarity index 99% rename from crates/engine/tests/ellipse_drag_anchors.rs rename to crates/engine/tests/it/ellipse_drag_anchors.rs index afce996136..1e278505ed 100644 --- a/crates/engine/tests/ellipse_drag_anchors.rs +++ b/crates/engine/tests/it/ellipse_drag_anchors.rs @@ -1,5 +1,4 @@ //! Ellipse arrow keys edit the anchor count of the shape actually being dragged. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::{Value, json}; use vectorcraft_doc::{LiveShape, Node, NodeId}; diff --git a/crates/engine/tests/eraser_open_fill.rs b/crates/engine/tests/it/eraser_open_fill.rs similarity index 99% rename from crates/engine/tests/eraser_open_fill.rs rename to crates/engine/tests/it/eraser_open_fill.rs index a0ab760660..a5f6e60956 100644 --- a/crates/engine/tests/eraser_open_fill.rs +++ b/crates/engine/tests/it/eraser_open_fill.rs @@ -1,6 +1,4 @@ //! Fill-only open-path Eraser regressions through the public engine and CPU renderer. -// Integration tests may unwrap and panic on failure (AGENTS.md). -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, NodeKind}; diff --git a/crates/engine/tests/group3_reference.rs b/crates/engine/tests/it/group3_reference.rs similarity index 100% rename from crates/engine/tests/group3_reference.rs rename to crates/engine/tests/it/group3_reference.rs diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index ff4a5c22ab..2be85215bb 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -12,13 +12,18 @@ mod affinity_local; mod align_automatic_reference; mod artboard_click; mod beyond_canvas; +mod blend_render_consistency; mod clear_commands; mod compound_attributes; mod copy_direct_selection; mod delete_path_pieces; mod dimensions; +mod direct_handle_mirror; +mod ellipse_drag_anchors; +mod eraser_open_fill; mod eyedropper_sources; mod find_replace_paras; +mod group3_reference; mod inline_text; mod js_lexer_vs_scriptcheck; mod known_bugs; @@ -27,12 +32,16 @@ mod model_based; mod param_keys; mod paste_many; mod pasted_clipping_path; +mod path_fill_hits; mod pen_click_after_smooth; mod pen_endpoint_picking; mod pen_rubber_band; +mod pen_space_handle; +mod preflight; mod ruler_guide_nodes; mod ruler_guide_perf; mod ruler_origin; +mod scissors_snap; mod script_host_vs_scriptcheck; mod selection_commands; mod several_handles; diff --git a/crates/engine/tests/path_fill_hits.rs b/crates/engine/tests/it/path_fill_hits.rs similarity index 99% rename from crates/engine/tests/path_fill_hits.rs rename to crates/engine/tests/it/path_fill_hits.rs index f8dfebafaf..28ab79e36b 100644 --- a/crates/engine/tests/path_fill_hits.rs +++ b/crates/engine/tests/it/path_fill_hits.rs @@ -1,5 +1,4 @@ //! Path fill hit testing follows the visible paint stack while transparent paint remains selectable. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::sync::Arc; diff --git a/crates/engine/tests/pen_space_handle.rs b/crates/engine/tests/it/pen_space_handle.rs similarity index 99% rename from crates/engine/tests/pen_space_handle.rs rename to crates/engine/tests/it/pen_space_handle.rs index 5e37ca8a11..9bb8a0b8c8 100644 --- a/crates/engine/tests/pen_space_handle.rs +++ b/crates/engine/tests/it/pen_space_handle.rs @@ -1,6 +1,4 @@ //! Pen lends Direct Selection for one handle gesture; Space repositions that handle's owner. -// Integration tests may unwrap and panic (AGENTS.md, Robustness). -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::json; use vectorcraft_doc::NodeId; diff --git a/crates/engine/tests/preflight.rs b/crates/engine/tests/it/preflight.rs similarity index 99% rename from crates/engine/tests/preflight.rs rename to crates/engine/tests/it/preflight.rs index e656596d71..73f6066bd3 100644 --- a/crates/engine/tests/preflight.rs +++ b/crates/engine/tests/it/preflight.rs @@ -1,5 +1,3 @@ -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - //! Production preflight must find actual delivery problems and clear them after repairs. use serde_json::{Value, json}; diff --git a/crates/engine/tests/scissors_snap.rs b/crates/engine/tests/it/scissors_snap.rs similarity index 99% rename from crates/engine/tests/scissors_snap.rs rename to crates/engine/tests/it/scissors_snap.rs index 6d12bd6457..b81ac05bab 100644 --- a/crates/engine/tests/scissors_snap.rs +++ b/crates/engine/tests/it/scissors_snap.rs @@ -1,5 +1,4 @@ //! Scissors receives the view's Smart Guides setting and keeps the split endpoint selected. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::json; use vectorcraft_doc::NodeId; diff --git a/docs/gaps.md b/docs/gaps.md index 9130e782f1..01b62dc5d6 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -29,7 +29,7 @@ OpenType panel feature-row context menus (part of G12): a secondary click on a f Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. -**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. +**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged. Appearance panel row context menus (part of G12): right-clicking stroke and fill rows offers Duplicate Stroke / Duplicate Fill, Delete Stroke / Delete Fill, and Hide Stroke/Show Stroke / Hide Fill/Show Fill; effect rows offer Edit Effect…, Duplicate Effect, Delete Effect, and Hide Effect / Show Effect; the root object row offers Clear Appearance and Reduce to Basic Appearance. Right-clicking an unselected row targets that row before presenting the menu. Item actions run in one undo step. Evidence: `panels::tests_appearance::right_clicking_a_stroke_row_selects_it_and_exposes_context_menu`, `panels::tests_appearance::clicking_duplicate_stroke_duplicates_the_stroke_with_one_undo_step`, `panels::tests_appearance::clicking_delete_effect_removes_the_effect_from_appearance`, and `panels::tests_appearance::right_clicking_root_object_row_exposes_clear_and_reduce_appearance` in `crates/ui-egui/src/panels/tests_appearance.rs`. Scores and estimates unchanged. @@ -185,7 +185,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Temporary handle mirroring (#7842):** with Direct Selection, add Control (Command on macOS) after a direction-handle drag begins to mirror the opposite handle at equal length. This includes ordinary paths, type on a path and blend spines; a missing opposite handle is pulled out while the modifier is held. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without the modifier. Letting go returns to the drag's normal handle behavior, Shift constrains before mirroring, and Alt takes independent-handle priority. The existing Control/Command-before-press Selection-tool loan is unchanged, and the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again. This does not add a persistent coupling mode or change Pen, mesh or warp gestures; the broader G1 scope and estimates remain. -- **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. +- **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. @@ -197,7 +197,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Polygon/Star count persistence:** Exact-size placement saves the chosen count for later drags and reopening the existing canvas dialog. Regression coverage includes both tools, repeated drags, switching tools and Cancel. The remaining G1 scope and estimates are unchanged. -- **Ellipse drag anchor count (#7840):** Up/Down changes the remembered Anchors count from 2 to 1000 in the current preview box. The existing click-dialog count starts later drags; Escape restores the earlier count while an explicit `tool.setOption` update is kept. Regression target: `crates/engine/tests/ellipse_drag_anchors.rs`. Broader G1 scope and estimates unchanged. +- **Ellipse drag anchor count (#7840):** Up/Down changes the remembered Anchors count from 2 to 1000 in the current preview box. The existing click-dialog count starts later drags; Escape restores the earlier count while an explicit `tool.setOption` update is kept. Regression target: `crates/engine/tests/it/ellipse_drag_anchors.rs`. Broader G1 scope and estimates unchanged. - **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:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo. Broader scope and estimates unchanged. @@ -398,8 +398,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G11 Correctness bugs in core tools -- **Resolved redraw-bounds defect (#5179):** a curved-spine blend's renderer bounds include its rotated keys and steps after Replace Spine; `crates/engine/tests/blend_render_consistency.rs` keeps the straight-blend control and checks all changed pixels against the advertised area. Both focused CPU regressions pass; broader G11 scope and estimates unchanged. -- **Improved (#6582), fill-only scope:** the Eraser subtracts its swept area or Alt-drag marquee from filled open contours with no visible painted stroke, preserving fill outside the sweep. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. The result keeps the existing path/compound piece structure and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths deliberately retain the outline-splitting behavior from main. Public reference semantics for those stroked paths were not established, and their fill behavior is not claimed fixed here. Focused engine integration tests cover fixed and varied tips and Alt-drag marquees on fill-only open/closed geometry and pixels, compound holes and self-crossing fill, plus painted-stroke paths that keep the outline route and clipping-mask split, empty-mask and Path Eraser controls. `crates/engine/tests/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Scores and estimates unchanged. +- **Resolved redraw-bounds defect (#5179):** a curved-spine blend's renderer bounds include its rotated keys and steps after Replace Spine; `crates/engine/tests/it/blend_render_consistency.rs` keeps the straight-blend control and checks all changed pixels against the advertised area. Both focused CPU regressions pass; broader G11 scope and estimates unchanged. +- **Improved (#6582), fill-only scope:** the Eraser subtracts its swept area or Alt-drag marquee from filled open contours with no visible painted stroke, preserving fill outside the sweep. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. The result keeps the existing path/compound piece structure and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths deliberately retain the outline-splitting behavior from main. Public reference semantics for those stroked paths were not established, and their fill behavior is not claimed fixed here. Focused engine integration tests cover fixed and varied tips and Alt-drag marquees on fill-only open/closed geometry and pixels, compound holes and self-crossing fill, plus painted-stroke paths that keep the outline route and clipping-mask split, empty-mask and Path Eraser controls. `crates/engine/tests/it/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Scores and estimates unchanged. - **Implemented (#6470):** Scissors hover and cuts use the Pen's path, alignment, intersection and anchor snapping, following the existing Smart Guides, Snap to Point, Snap to Pixel and Snap to Grid options. Alt still adds an anchor without cutting, and a cut still leaves one new endpoint selected. Headless regressions are in `crates/tools/src/draw2/anchor/tests.rs`; broader G11 scope and estimates unchanged. diff --git a/docs/production-preflight.md b/docs/production-preflight.md index ecc551f0c9..77698662d8 100644 --- a/docs/production-preflight.md +++ b/docs/production-preflight.md @@ -52,7 +52,7 @@ The same read-only report is available through `document.preflight`; see [MCP](m Checked on Windows with Rust 1.99.1, based on `main` at `36b5a5920c`: -- Engine integration tests: 9 passed (`cargo test -p vectorcraft-engine --test preflight`). +- Engine integration tests: 9 passed (`cargo test -p vectorcraft-engine --test it preflight::`). - Panel tests: 5 passed (`cargo test -p vectorcraft-ui-egui --lib preflight`), including pointer selection/zoom, edits and Undo, document switching, external-file polling and explicit Recheck. - Both test commands used `--offline --target-dir target --config profile.test.opt-level=0`. diff --git a/docs/roadmap.md b/docs/roadmap.md index 971ca6eafa..726ecd790b 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -34,7 +34,7 @@ Color conversion (#8804) builds one first-name index for the document's global swatch bases and uses indexed lookups for linked paints. Document Color Mode, new-art colors and text-style conversion keep first-record shadowing, spot handling, tint behavior and missing-link fallback. The base construction changes from quadratic name searches to O(N log N) index work; this is a source-complexity result, not a measured elapsed-time or budget improvement. Command-level semantic controls are in `crates/engine/src/tests/colormgmt.rs`; scores and estimates are unchanged. -**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. +**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged. Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4df379b998..ae083e42e9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -77,7 +77,7 @@ Variables panel row context menus (2026-11-20, G12): Right-click highlights the Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. -**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. +**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged. `window.panel.float` updates an existing native panel window's supplied position and size (#8391). Positions use the main window's content origin. Omitted coordinates and dimensions keep their current native values, including after an OS window move or resize. Evidence: `panel_docking::native_tests::an_explicit_float_command_updates_an_existing_native_windows_geometry` covers panel, group and column commands. Scores and estimates are unchanged. @@ -346,8 +346,8 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Area | Weight | Done | Main gaps | One agent (h) | Kind | |---|---:|---:|---|---:|---| -| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | -| Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options; Touch Type (#2469) and the Dimension tool (#1788) are done; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; 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 and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged | +| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/it/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | +| Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options; Touch Type (#2469) and the Dimension tool (#1788) are done; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; 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 and result structure (#6582; `crates/engine/tests/it/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; 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 (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005); the Color Wheel panel's Show Opacity sets the opacity of the fill, stroke, gradient stop or freeform point it edits (part of #978), score and hours unchanged; gradient stop editor color-mode menu (#7918) | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | @@ -692,12 +692,12 @@ since 2026-10-01. - **`.ai` clipping paths grouped in a compound path (#8128):** `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs` covers clipping paths grouped in a compound path (`*u u W n … U *U`, also nested in other groups): they are the compound path's subpaths, and the compound clipping path, their union, clips its clipping group however many there are and wherever in the group it is written. Synthetic files written in the test; no fixtures added. Scores and hours unchanged. -**Production Preflight (2026-11-18, VectorCraft addition):** `document.preflight` and Window > Production Preflight reuse the output-aware type walk, Links status probes, `image.info` effective-PPI calculation and saved Print geometry. Findings locate canvas objects (resource findings name their first visible owner). Rechecking follows document identity/revision, output/scope/threshold changes, explicit Recheck and a two-second external-file timer. Print resolution includes the page transform. Resolution in resource art and placed documents is explicitly not checked; this is not exported-file certification. Regression sources: `crates/engine/tests/preflight.rs`, `crates/ui-egui/src/panels/preflight/tests.rs`. Scores and estimates unchanged. +**Production Preflight (2026-11-18, VectorCraft addition):** `document.preflight` and Window > Production Preflight reuse the output-aware type walk, Links status probes, `image.info` effective-PPI calculation and saved Print geometry. Findings locate canvas objects (resource findings name their first visible owner). Rechecking follows document identity/revision, output/scope/threshold changes, explicit Recheck and a two-second external-file timer. Print resolution includes the page transform. Resolution in resource art and placed documents is explicitly not checked; this is not exported-file certification. Regression sources: `crates/engine/tests/it/preflight.rs`, `crates/ui-egui/src/panels/preflight/tests.rs`. Scores and estimates unchanged. - `object.setBounds` uses the same reference point for whole-number integer and floating-point values, including `0` and `0.0`. It rejects negative and fractional indices without changing geometry, selection, or undo history. An omitted or null reference uses the center, and whole-number references above 8 use point 8. Object and direct-anchor selections follow these rules (`tests::bboxrotate::set_bounds_whole_number_references_match_integer_references`, `set_bounds_rejects_invalid_references_without_changes`). - Twist keeps boundary handles tangent to the rotation inside its outer circle. Regressions cover 90, 400, and -720 degree twists, unchanged boundary anchors, and a sampling midpoint that rounds to an endpoint at large coordinates (`twist_boundary_handles_follow_the_inward_tangent` and `a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction`). -- **Blend redraw bounds (#5179):** renderer bounds include the reach of keys and steps rotated along a curved spine, so changed pixels remain inside the advertised redraw area. The original straight-blend control and curved Replace Spine, move and Undo regressions are in `crates/engine/tests/blend_render_consistency.rs`; both focused CPU cases pass. This is a redraw-bounds correction. Scores and hours unchanged. +- **Blend redraw bounds (#5179):** renderer bounds include the reach of keys and steps rotated along a curved spine, so changed pixels remain inside the advertised redraw area. The original straight-blend control and curved Replace Spine, move and Undo regressions are in `crates/engine/tests/it/blend_render_consistency.rs`; both focused CPU cases pass. This is a redraw-bounds correction. Scores and hours unchanged. - **Guide row highlight (#7344):** `guide_row_highlight_stays_selected_without_hover` in `crates/ui-egui/src/panels/layers/tests.rs` checks selected guide background after the pointer leaves, with unselected guide and ordinary row controls. Guide selection, dragging and deletion are unchanged. Scores and estimates unchanged. - **Trim View hides guides and the grid (#8363):** while View › Trim View is on, the canvas and tiled panes draw no ruler guides, no guide paths and no grid, the guides are neither snapped to nor picked, and Show/Hide Guides and Show/Hide Grid are greyed out (menu bar, canvas context menu, Properties) and refuse to run; the stored choices come back when it is turned off, and the rulers stay ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). A drag or double-click on a ruler makes no guide while it is on (no preview, no undo step, a status message). `trim_view_hides_the_guides_and_the_grid`, `trim_view_deselects_selected_guide_paths`, `trim_view_makes_no_guide_from_the_rulers` in `crates/ui-egui/src/canvas/tests.rs`; `trim_view_greys_out_show_guides_and_show_grid` in `crates/ui-egui/src/menus/tests.rs`. @@ -716,7 +716,7 @@ since 2026-10-01. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. -**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss with Object Selection by Path Only on or in Outline view, and with it off are picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. +**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss with Object Selection by Path Only on or in Outline view, and with it off are picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. - **Clicks inside unfilled shapes (#9175):** with Object Selection by Path Only off (the default), the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when the click hits no other object there, by its fill, stroke, path or bounds (a symbol instance, for example, is hit anywhere in its bounds); among such paths the topmost is picked, and Select Behind lists them after the objects that paint there. Open paths, guides and clipping paths are still picked by their path only, and Outline view and layers whose Preview is off are unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only` (MCP). Scores and estimates unchanged. @@ -727,7 +727,7 @@ since 2026-10-01. - **PDF Indic type (#5235, #6906):** `crates/pdf/src/tests/reshaped.rs` covers a vowel sign the file draws before its consonant (the line keeps the file's glyphs as outlines, with a note), text in reading order (stays type), a mark with no advance (stays on its line, not vertical type of its own), outlined glyphs stroked with different dashes and translucent outlined glyphs (each keeps its own path). Synthetic font only; one real Gujarati file checked by eye on page 1. Indic type in an uninstalled font keeps the file's glyphs as outlines; reordering signs so more lines stay editable is not done. Scores and hours stay at 75% / 10-20 h. -- **Selection — Space during an ordinary path's direction-handle drag (#7237, request 3 only).** Pressing Space during an ordinary path's Direct Selection handle drag translates the owning anchor and both handles; releasing Space while the mouse stays down resumes handle adjustment. The same gesture during the Pen's Cmd/Ctrl loan returns to drawing from the same endpoint. `crates/engine/tests/pen_space_handle.rs` covers first-motion Space, repeated toggles and Pen continuation (`pen_space_first_motion_repeated_toggle_and_pen_continuation`), one-step Undo/Redo (`pen_space_handle_drag_undo_redo_is_one_step`), and cancellation restoring the borrowed gesture (`pen_space_escape_restores_entire_borrowed_gesture`). Live type-on-path Space behavior is outside this increment; blend-spine editing is unchanged. This does not close the issue's separate handle-hover label request or change Cmd snapping or handle-coupling policy. Score and hours unchanged. +- **Selection — Space during an ordinary path's direction-handle drag (#7237, request 3 only).** Pressing Space during an ordinary path's Direct Selection handle drag translates the owning anchor and both handles; releasing Space while the mouse stays down resumes handle adjustment. The same gesture during the Pen's Cmd/Ctrl loan returns to drawing from the same endpoint. `crates/engine/tests/it/pen_space_handle.rs` covers first-motion Space, repeated toggles and Pen continuation (`pen_space_first_motion_repeated_toggle_and_pen_continuation`), one-step Undo/Redo (`pen_space_handle_drag_undo_redo_is_one_step`), and cancellation restoring the borrowed gesture (`pen_space_escape_restores_entire_borrowed_gesture`). Live type-on-path Space behavior is outside this increment; blend-spine editing is unchanged. This does not close the issue's separate handle-hover label request or change Cmd snapping or handle-coupling policy. Score and hours unchanged. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. @@ -834,7 +834,7 @@ since 2026-10-01. - **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged. - **Link cursor for loaded text:** with text loaded from a port, the Selection tool's pointer adds a link badge over a closed path, area type or type on a path that a click threads the text into, and keeps the loaded text elsewhere; a click on a frame already in a thread or a path inside a compound path makes a new frame instead of a `text.thread.add` error (`select::tests::loaded_text_shows_the_link_cursor_where_a_click_threads_it_into_the_object`, `cursors::tests::loaded_text_link_cursor_is_the_loaded_text_with_a_link_badge`); score unchanged. - **Copy and Cut of anchors picked with a lent Direct Selection (#6123):** with the Pen or the Curvature tool, Cmd/Ctrl held lends Direct Selection for the gesture; the anchors and segments it picks are what Edit › Copy and Cut take once the key is let go, as with Direct Selection chosen, while the last anchor the Pen leaves selected as it draws still makes Copy take the whole path (#2122). A Cmd gesture that leaves the selection as it was (a Shift marquee over nothing) picks nothing. Regression test: `tests::draw2::pen_cmd_selected_anchors_are_what_copy_and_cut_take`. -- **Mirrored handles in a Direct Selection drag (#7842):** Cmd/Ctrl added after a handle drag begins puts the anchor's other handle opposite the dragged one at the same length, on paths, type on a path and blend spines, and the anchor keeps its kind; Shift constrains the dragged handle first, and Alt keeps the handles independent. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without Cmd/Ctrl. When Cmd/Ctrl lends Direct Selection for the gesture while another tool, such as the Pen, is chosen, that press does not mirror; letting it go and pressing it again during the drag does. This is VectorCraft's own behavior. Regression tests: `crates/engine/tests/direct_handle_mirror.rs`. +- **Mirrored handles in a Direct Selection drag (#7842):** Cmd/Ctrl added after a handle drag begins puts the anchor's other handle opposite the dragged one at the same length, on paths, type on a path and blend spines, and the anchor keeps its kind; Shift constrains the dragged handle first, and Alt keeps the handles independent. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without Cmd/Ctrl. When Cmd/Ctrl lends Direct Selection for the gesture while another tool, such as the Pen, is chosen, that press does not mirror; letting it go and pressing it again during the drag does. This is VectorCraft's own behavior. Regression tests: `crates/engine/tests/it/direct_handle_mirror.rs`. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Commands run during a tool drag:** by VectorCraft's own rule, a command that changes the document while a tool drag is in progress (from a panel, a menu or `run_command`) records its own undo step before the drag's. The drag goes on with the art the command left, Escape cancels only the drag, and Undo takes back the drag first and the command next, with Real-time Drawing on or off. A selection the command makes does not change which objects the drag moves. Commands that keep the drag as a step first (Undo, Redo, `command.batch` and others), a Quick Pen press, and a copy made with `object.transform` during an Alt-drag work as before. Regression tests: `crates/engine/src/tests/interaction_commands.rs` and `tests::drag_commands` in `crates/ui-egui`. @@ -1594,10 +1594,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur VectorCraft's own Anchors field in the Ellipse dialog (a click with the Ellipse tool; `shape.ellipse {anchors}`, part of #7840) sets how many smooth anchors the ellipse has, 4 by default; 4 draws a live ellipse, and any other count from 2 to 1000 draws a plain path with the anchors spaced evenly by angle, fitted to the typed width and height. The count last confirmed stays as the Ellipse tool's `anchors` option, and the next Ellipse dialog opens on it (`ellipse_with_four_anchors_is_the_live_ellipse`, `ellipse_anchors_draw_that_many_anchors_on_the_ellipse`, `ellipse_refuses_a_bad_anchor_count`, `the_ellipse_dialog_draws_and_keeps_its_anchor_count`). In the Ellipse dialog, a click on the word Height copies the Width value into the Height field, so OK draws a circle of that width, as [the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=140) describes for drawing ellipses. The Rectangle and Rounded Rectangle dialogs keep plain labels. VectorCraft's own rules: the word Height is a button that Space or Enter also presses, and that Enter does not press OK (nor does Enter on the Constrain Width and Height Proportions button); with the link on, the link stays on and keeps the circle when a side is typed next; a Width that is empty or not a distance, including one the field refuses as the click leaves it, leaves Height as it is; Cancel discards the copy. Evidence: `dialogs::shapes::tests::{clicking_height_in_the_ellipse_dialog_copies_width_into_height, the_ellipse_height_button_copies_width_from_the_keyboard_and_keeps_the_link_round, enter_on_the_link_button_turns_the_link_on_without_pressing_ok, only_the_ellipse_dialog_has_the_height_button, copying_width_takes_only_a_width_that_reads}`. - The click-dialog field landed in #7964. While an ellipse is dragged out, Up/Down raises or lowers the same remembered Anchors count within 2…1000 (#7840), keeping the preview box and its Shift, Alt and Space behavior. Four anchors keep the live ellipse; other counts use the existing plain-path geometry. Releasing commits one undo step. Escape restores the count from before the drag, unless `tool.setOption` explicitly updated it during the gesture, in which case that value stays. Regression target: `crates/engine/tests/ellipse_drag_anchors.rs` (`ellipse_drag_anchors_`). + The click-dialog field landed in #7964. While an ellipse is dragged out, Up/Down raises or lowers the same remembered Anchors count within 2…1000 (#7840), keeping the preview box and its Shift, Alt and Space behavior. Four anchors keep the live ellipse; other counts use the existing plain-path geometry. Releasing commits one undo step. Escape restores the count from before the drag, unless `tool.setOption` explicitly updated it during the gesture, in which case that value stays. Regression target: `crates/engine/tests/it/ellipse_drag_anchors.rs` (`ellipse_drag_anchors_`). - **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes). - The Eraser cuts fill-only open contours as areas (#6582), retaining fill outside its sweep or Alt-drag marquee. An eligible appearance has a visible non-None fill and no visible non-None stroke of positive width. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. Cut pieces keep the existing path/compound representation and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths retain the outline-splitting behavior from main. `crates/engine/tests/eraser_open_fill.rs` covers fixed and varied tips on fill-only open/closed geometry and raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. The same public target includes container-own paint and evaluated-placement regression cases. This deliberately scoped fix does not claim to repair filled-and-stroked open-path fill behavior. Scores and hours are unchanged. - With Alt released, Scissors hover and cuts snap as the Pen does: onto paths and anchors, into alignment and onto intersections (#6470). The hover guides and cut use the same snapped point; the cursor follows the current hover target. The existing Smart Guides, Snap to Point, Snap to Pixel and Snap to Grid options keep their precedence. Pixel Preview turns off Smart Guides through the tool view context; Snap to Point keeps its existing rules. Alt Add Anchor and the cut's endpoint selection below are unchanged. Source: `crates/tools/src/draw2/anchor.rs`. Headless regressions: `scissors_snaps_intersections_with_the_drawing_options`, `scissors_shows_paths_alignment_and_configured_anchor_snaps`, `scissors_cursor_and_press_use_current_snaps` and `scissors_clears_its_snap_when_the_interaction_ends_or_alt_takes_over` in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. + The Eraser cuts fill-only open contours as areas (#6582), retaining fill outside its sweep or Alt-drag marquee. An eligible appearance has a visible non-None fill and no visible non-None stroke of positive width. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. Cut pieces keep the existing path/compound representation and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths retain the outline-splitting behavior from main. `crates/engine/tests/it/eraser_open_fill.rs` covers fixed and varied tips on fill-only open/closed geometry and raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. The same public target includes container-own paint and evaluated-placement regression cases. This deliberately scoped fix does not claim to repair filled-and-stroked open-path fill behavior. Scores and hours are unchanged. + With Alt released, Scissors hover and cuts snap as the Pen does: onto paths and anchors, into alignment and onto intersections (#6470). The hover guides and cut use the same snapped point; the cursor follows the current hover target. The existing Smart Guides, Snap to Point, Snap to Pixel and Snap to Grid options keep their precedence. Pixel Preview turns off Smart Guides through the tool view context; Snap to Point keeps its existing rules. Alt Add Anchor and the cut's endpoint selection below are unchanged. Source: `crates/tools/src/draw2/anchor.rs`. Headless regressions: `scissors_snaps_intersections_with_the_drawing_options`, `scissors_shows_paths_alignment_and_configured_anchor_snaps`, `scissors_cursor_and_press_use_current_snaps` and `scissors_clears_its_snap_when_the_interaction_ends_or_alt_takes_over` in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. A Scissors cut (`path.split`) leaves one of the two new end points selected and the rest of the path unselected, as [Cut paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) and the "Split a path" section of the [CS3 user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) describe: the two end points lie on top of each other, and a Direct Selection drag from them moves the selected one with its handles and no other anchor. A closed path cut once stays one open path. The paths a Scissors cut (`path.split`) or Cut Path at Selected Anchor Points (`path.cutAtAnchors`) makes keep the source path's fill and stroke settings, and every stroke's alignment becomes Center in the same undo step, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) describes. Resetting hidden stroke rows too, centering the strokes of a path's other subpaths and of the compound path a cut member belongs to are VectorCraft's own rules (`scissors_cut_paths_have_their_strokes_centered`, `cut_at_anchors_paths_have_their_strokes_centered`). While Alt is held, the Scissors tool works as the Add Anchor Point tool ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): a click on a segment adds an anchor point without cutting (`path.insertAnchor`), and the pointer shows the Add Anchor Point cursor. When Alt is let go, a click cuts again. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d131053a67..957cfa9479 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -25,7 +25,7 @@ ## Feature submission evidence -**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. +**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged. Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. @@ -204,12 +204,12 @@ tools, never checked side by side) isn't captured row by row. | Pen cursors (new path ×, continue /, close o, add +, delete −, convert ^) | done | the nib is a fountain-pen nib, tip on the hotspot, with the slit widening into the breather hole and the heel clipped square to its axis; bitmap tests at 1× and 2× pin the nib and the new-path asterisk, and in-app screenshots compare the Pen with Direct Selection | | Node-editing cursors: Direct Selection's white arrow with a hollow or filled square over an anchor (path unselected or selected); the Reshape Segment cursor over a curved segment (Direct Selection, Anchor Point, the Pen with Alt); the Anchor Point caret for the Pen with Alt; Group Selection's plus (also Direct Selection with Alt); a filled arrow while dragging that turns hollow on a snap; a double arrowhead for an Alt-drag copy | partial | as the public manual describes them, drawn in code; no cue over handles (none documented) | | Anchor Point and Curvature tools' own cursors | done | the caret on the anchor it converts; the pen nib with a curve badge | -| Scissors hover and cuts use the Pen's path, alignment, intersection and anchor snapping (#6470) | implemented | Existing Smart Guides, Snap to Point, pixel and grid options apply; Pixel Preview turns off Smart Guides. Alt still adds an anchor without cutting, and a cut still leaves one new endpoint selected. Headless regressions: `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. | -| Scissors cut-point preview (#8655) | implemented | Native marker at the actual anchor or curve target; current snapping, cut and Alt Add Anchor behavior retained. `crates/tools/src/draw2/anchor/tests.rs`, `crates/engine/tests/scissors_snap.rs`. | +| Scissors hover and cuts use the Pen's path, alignment, intersection and anchor snapping (#6470) | implemented | Existing Smart Guides, Snap to Point, pixel and grid options apply; Pixel Preview turns off Smart Guides. Alt still adds an anchor without cutting, and a cut still leaves one new endpoint selected. Headless regressions: `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. | +| Scissors cut-point preview (#8655) | implemented | Native marker at the actual anchor or curve target; current snapping, cut and Alt Add Anchor behavior retained. `crates/tools/src/draw2/anchor/tests.rs`, `crates/engine/tests/it/scissors_snap.rs`. | | Free Transform's Cmd/Ctrl side-shear cursor | done | two arrows passing along the side (ShearH, ShearV), instead of the resize arrow across it | | Live Paint Bucket cursors | partial | a filled bucket over a face a click fills, a brush over an edge it paints, an empty bucket where it paints nothing, following Paint Fills, Paint Strokes and Shift; the Eyedropper with Alt; the crosshair with Use Precise Cursors. No cursor swatch preview | | Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed | -| Eraser: filled open paths and compound holes | partial | Fill-only open paths preserve fill outside sweeps and Alt-drag marquees and keep compound holes under their fill rule (#6582). Path or Compound clipping masks retain all surviving contours or empty geometry in the same node, preserving the mask role; Path Eraser shares this behavior. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Focused engine tests cover fixed and varied tips and Alt-drag marquees on open/closed geometry, raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. `crates/engine/tests/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Filled-and-stroked open paths retain main behavior; that fill behavior is not claimed fixed. See G11 in [gaps.md](gaps.md#g11-correctness-bugs-in-core-tools). | +| Eraser: filled open paths and compound holes | partial | Fill-only open paths preserve fill outside sweeps and Alt-drag marquees and keep compound holes under their fill rule (#6582). Path or Compound clipping masks retain all surviving contours or empty geometry in the same node, preserving the mask role; Path Eraser shares this behavior. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Focused engine tests cover fixed and varied tips and Alt-drag marquees on open/closed geometry, raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. `crates/engine/tests/it/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Filled-and-stroked open paths retain main behavior; that fill behavior is not claimed fixed. See G11 in [gaps.md](gaps.md#g11-correctness-bugs-in-core-tools). | | Knife cursor | done | a knife, the blade's point on the hotspot, white blade and black handle, for the Knife and the Trim at Crossings Tool; the crosshair with Use Precise Cursors; `the_knife_shows_a_knife_with_its_point_on_the_hotspot`, `drawing_tools_show_their_own_cursor` | | Blob Brush and Eraser: the tip's outline at the pointer | done | before a press and while painting, the outline of the tip (its size, angle and roundness, at the zoom) follows the pointer, black on a white halo, round a small centre dot; `[` / `]` and Tool Options change it at once; precise cursors (Caps Lock) show only the crosshair; it goes when the pointer leaves the canvas, while Cmd/Ctrl lends a selection tool and while Alt lends the Blob Brush the Smooth tool (#4977); `crates/tools/src/draw2/gesture.rs` and its tests While the button is down a round Blob Brush shows the outline of the area it will add, rounded at both ends, not a line as wide as the brush that ends square (#4343). | | Eraser: an Alt-drag draws a marquee and the release erases everything inside it (closed shapes and fill-only open paths lose the rectangle's area, other open paths are cut where they cross its edges); Alt+Shift keeps the marquee square; Escape cancels it, and a click erases nothing | done | `path.eraseRegion {rect}`; [public behavior reference](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=133); `eraser_alt_drag_draws_a_marquee_and_erases_the_rectangle`, `eraser_alt_shift_drag_keeps_the_marquee_square`, `eraser_marquee_click_or_escape_erases_nothing`, `erase_region_rect_erases_everything_inside_it`, `erase_region_rect_refuses_bad_values` | @@ -250,7 +250,7 @@ tools, never checked side by side) isn't captured row by row. | Behaviour | Status | Notes | |---|---|---| -| Path and compound-path interior selection follows enabled non-None fill rows | done | #6625; lower visible fill beneath a top None row stays selectable; hidden-only/None interiors miss; zero-opacity, edge, Outline/path-only and hole controls in `crates/engine/tests/path_fill_hits.rs`; hidden-fill and no-fill stroke cap/join CPU regressions passed | +| Path and compound-path interior selection follows enabled non-None fill rows | done | #6625; lower visible fill beneath a top None row stays selectable; hidden-only/None interiors miss; zero-opacity, edge, Outline/path-only and hole controls in `crates/engine/tests/it/path_fill_hits.rs`; hidden-fill and no-fill stroke cap/join CPU regressions passed | | Backquote/~ arrow nudges move selected pattern fills and strokes | done | #7717: Selection, partial-anchor Direct Selection and other idle tools; Keyboard Increment/Shift; geometry, guides and anchor selection stay fixed. Tests: `crates/ui-egui/tests/pattern_only_nudge.rs` | | Deleting segments or anchors that disconnect an ordinary path creates independent selected objects | done | #3380, deletion only: first piece retains its ID, styles and transforms carry over in sibling order, bounds-fitted gradients keep their original placement, and one Undo restores the original. Existing multi-subpath paths and compound members stay intact. `delete_path_pieces` covers transformed/styled rectangles, cubic handles and Undo/Redo. Endpoint highlighting remains open. | | Click/Shift-click anchors; marquee toggles with Shift | done | #483 | @@ -269,7 +269,7 @@ tools, never checked side by side) isn't captured row by row. | Drag a curved segment to bend it, a straight one to move its anchors | done | | | Drag by an anchor of a path selected whole moves the whole path; Alt-drag by an anchor or a segment copies it, Alt toggles the copy during the drag, and the copy snaps by the anchor pressed, onto the original too | done | #1104 | | Handles shown are the handles that drag; tolerance from Selection & Anchor Display | done | #494 | -| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Control/Command added mid-drag (mirror the opposite handle), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan, and keeps Alt independent priority; the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again; `crates/engine/tests/direct_handle_mirror.rs`; Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) | +| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Control/Command added mid-drag (mirror the opposite handle), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan, and keeps Alt independent priority; the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again; `crates/engine/tests/it/direct_handle_mirror.rs`; Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) | | Show handles when multiple anchors are selected; Highlight anchors on mouse over; anchor and handle size | done | Preferences › Selection & Anchor Display | | Convert selected anchors to corner/smooth from the Control bar and Properties | done | | | Cut path at selected anchors, Remove Anchor Points, Delete removes segments | done | Open-path anchor Delete removes adjoining segments without bridging the gap; #3380 (deletion only): disconnected survivors of an ordinary contour become independent selected sibling objects, while multi-subpath paths and compound members stay intact; targeted core and full-frame Delete/Backspace regressions pass for survivor selection and Undo/Redo. Explicit Remove Anchor Points keeps its reconnect/refit behavior; #1278: segment Delete preserves neighboring edges and endpoint anchors; a second Delete removes all selected surviving objects; explicit anchor Delete retains its behavior; #1674: Delete removes every selected anchor of a closed path and objects selected whole along with them, and keeps the surviving objects selected; #2241: Remove Anchor Points then selects the next anchor along the path (the one before at an open end), so it can be run again without picking each anchor | @@ -405,7 +405,7 @@ tools, never checked side by side) isn't captured row by row. | Artboard Options › Display: Show Center Mark and Show Cross Hairs ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/modify-display-settings-of-artboards.html)) | done | Per-artboard checkboxes (`artboard.setProps`/`artboard.new` `showCenterMark`, `showCrossHairs`, one undo step); the canvas draws a cross 12 points across on screen at the center and lines from the middle of each side through it, 1 point wide on screen at any zoom and turned with the view; exports and print leave them out; tests `an_artboard_shows_its_center_mark_and_cross_hairs`, `artboard_options_show_center_mark_and_cross_hairs` | | View › Hide Artboards (Ctrl/Cmd+Shift+H) hides the artboards' edges, bleeds, marks and names and shows the whole canvas as paper (white, or Simulate Colored Paper's colour); the Artboard tool still shows them | done | #4038, `canvas::tests::hidden_artboards_leave_a_paper_canvas_without_edges` | | Artboard Options › Display: Show Video Safe Areas and Video Ruler Pixel Aspect Ratio ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)) | done | #2849; per artboard (`artboard.setProps`/`artboard.new` `showVideoSafeAreas`, `videoRulerPixelAspectRatio` 0.1–10, default 1; one undo step; native format). The page gives no safe-area numbers: our choice is [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf)'s, the action-safe area 3.5% and the title-safe area 5% in from each edge, outlined 1 point wide on the canvas and turned with the view; exports and print leave them out. Tests `an_artboard_shows_its_video_safe_areas`, `artboard_options_show_video_display_options`, `artboard_video_display_options_*` | -| Shape tools: Shift constrains, Alt from centre, Space moves while dragging, arrows change sides/points/rows and Ellipse anchors | done | #7840: Ellipse Up/Down changes the remembered Anchors count within 2…1000; four anchors keep a live ellipse, other counts a plain path. Release is one undo step; Escape restores the earlier count unless explicitly updated with `tool.setOption`. `crates/engine/tests/ellipse_drag_anchors.rs` | +| Shape tools: Shift constrains, Alt from centre, Space moves while dragging, arrows change sides/points/rows and Ellipse anchors | done | #7840: Ellipse Up/Down changes the remembered Anchors count within 2…1000; four anchors keep a live ellipse, other counts a plain path. Release is one undo step; Escape restores the earlier count unless explicitly updated with `tool.setOption`. `crates/engine/tests/it/ellipse_drag_anchors.rs` | | Eraser: Shift-drag erases along a horizontal, vertical or diagonal line ([public source](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=82)) | done | the line runs from the press point at the 45° step from the Constrain Angle nearest the pointer, taken once the pointer is 3 screen pixels from the press and kept until Shift is released; the tip outline follows the line; released, the drag goes on freehand from the last point on the line, and Shift again takes a new step from the press point (VectorCraft's own rules); `eraser_shift_keeps_the_stroke_on_a_45_degree_line` in `crates/tools/src/draw2/gesture/tests.rs` | | Polygon/Star exact-size placement remembers the chosen sides/points for later drags and dialog openings; Cancel preserves the previous count | done | Session tool options; existing dialog-opening gestures retained; regression in `toolbar.rs` | | Tool double-click opens its options | done | | From 49344097e40c724d9c5c21fe9a1cd6664f067601 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:39:42 -0800 Subject: [PATCH 55/69] Docs: keep the original preflight test command in the 2026-11-18 record The 2026-11-18 validation ran when preflight was its own test binary, so the record keeps `--test preflight`. A separate line gives the current command, `--test it preflight::`. --- docs/production-preflight.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/production-preflight.md b/docs/production-preflight.md index 77698662d8..cc84d2ef59 100644 --- a/docs/production-preflight.md +++ b/docs/production-preflight.md @@ -52,7 +52,7 @@ The same read-only report is available through `document.preflight`; see [MCP](m Checked on Windows with Rust 1.99.1, based on `main` at `36b5a5920c`: -- Engine integration tests: 9 passed (`cargo test -p vectorcraft-engine --test it preflight::`). +- Engine integration tests: 9 passed (`cargo test -p vectorcraft-engine --test preflight`). - Panel tests: 5 passed (`cargo test -p vectorcraft-ui-egui --lib preflight`), including pointer selection/zoom, edits and Undo, document switching, external-file polling and explicit Recheck. - Both test commands used `--offline --target-dir target --config profile.test.opt-level=0`. @@ -77,6 +77,9 @@ WebAssembly Clippy run also encounters existing target-specific lints in unchang (`drop_non_drop`) and `font_menu.rs` (`unnecessary_lazy_evaluations`); the WebAssembly typecheck and the native Clippy run above pass without source changes for those findings. +The engine preflight tests now live in the `it` test binary. Run them with +`cargo test -p vectorcraft-engine --test it preflight::`. + ### Review follow-up on `main` at `ee60c51fd` The exact-threshold and locked-artboard regressions were first run against the original From ab4e56934be4afed5f89b44b64945d0e389bb8b5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 07:48:08 -0800 Subject: [PATCH 56/69] Linux: the log says why a pen's window stays on Wayland, and names the pens XWayland lists Part of #5622. On a Wayland session winit 0.30 receives no input from a pen, so the app opens its window through XWayland when a pen is attached (#4967). When it did not, the log said nothing, and a report could not tell a pen that was not found from a session with no X display. - On a Wayland session the log now says why the window opens on Wayland: no pen in /proc/bus/input/devices, the device list could not be read, VECTORCRAFT_NATIVE_WAYLAND is set, or there is no X display (DISPLAY is unset, as in the Flatpak, which has --socket=fallback-x11). The pen-found line names the pen, and the missing-libraries warning no longer says Linux Display Server is X11 when a pen chose XWayland. - Under X11 the tablet reader logs the pens the X server lists (for example XWayland's "xwayland-tablet stylus:16"), again when that list changes, and the first event from each pen. - docs/development.md lists the new log lines, the Flatpak override that gives it an X display, and that GDK_BACKEND=x11 does not move the window to XWayland. --- apps/vectorcraft/src/main.rs | 29 ++++++- apps/vectorcraft/src/tablet.rs | 71 ++++++++++++++++- apps/vectorcraft/src/xwayland.rs | 130 ++++++++++++++++++++++++++----- docs/development.md | 2 +- 4 files changed, 204 insertions(+), 28 deletions(-) diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 6ab6778597..943c4c6302 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -396,15 +396,36 @@ fn read_command_line( /// Whether the window opens through XWayland, for Linux Display Server `pref` (`main`). #[cfg(target_os = "linux")] fn opens_through_xwayland(pref: Option<&str>) -> bool { - if !xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) { + use xwayland::Choice; + let choice = xwayland::choose(pref, |name| std::env::var_os(name), xwayland::pen_attached); + // On native Wayland winit 0.30 receives no pen input, so the log says why the window stays there. + match &choice { + Choice::NotWayland | Choice::Chosen | Choice::Pen(_) => {} + Choice::NoXDisplay { x11: true } => { + log::warn!("Linux Display Server is X11, but there is no X display (DISPLAY is unset): opening the window on Wayland") + } + Choice::NoXDisplay { x11: false } => log::info!( + "opening the window on Wayland, where a pen does not reach it: there is no X display (DISPLAY is unset) to open it through XWayland" + ), + Choice::NativeWayland => log::info!("VECTORCRAFT_NATIVE_WAYLAND is set: opening the window on Wayland, where a pen does not reach it"), + Choice::NoPen => log::info!("no pen in /proc/bus/input/devices: opening the window on Wayland"), + Choice::NoDeviceList(e) => log::warn!("can't look for a pen ({e}): opening the window on Wayland, where a pen does not reach it"), + } + if !choice.xwayland() { return false; } if !xwayland::x11_libraries_found() { - log::warn!("Linux Display Server is X11, but the X11 libraries aren't all installed: opening the window on Wayland"); + if let Choice::Pen(name) = &choice { + log::warn!( + "pen found ({name}), but the X11 libraries aren't all installed: opening the window on Wayland, where the pen does not reach it" + ); + } else { + log::warn!("Linux Display Server is X11, but the X11 libraries aren't all installed: opening the window on Wayland"); + } return false; } - if pref != Some("x11") { - log::info!("pen found: opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)"); + if let Choice::Pen(name) = &choice { + log::info!("pen found ({name}): opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)"); } else { log::info!("opening the window through XWayland (Preferences › Performance › Linux Display Server)"); } diff --git a/apps/vectorcraft/src/tablet.rs b/apps/vectorcraft/src/tablet.rs index 4dd8f7d9ec..2c6a8b68c1 100644 --- a/apps/vectorcraft/src/tablet.rs +++ b/apps/vectorcraft/src/tablet.rs @@ -41,7 +41,7 @@ //! the rotation's range is 0°, and an axis a pen lacks reads nothing. #![cfg_attr(not(target_os = "linux"), allow(dead_code))] -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use craft::behavior::PointerSample; use craft::ui::runtime::pen::PenSource; @@ -189,6 +189,8 @@ enum Update { struct Pens { devices: HashMap, last: HashMap; 5]>, + /// The pens an event has come from, for the log. + heard: HashSet, } impl Pens { @@ -197,10 +199,37 @@ impl Pens { /// same id starts without them. fn set_devices(&mut self, devices: impl IntoIterator) { let devices: HashMap = devices.into_iter().take(MAX_DEVICES).map(|d| (d.id, d)).collect(); - self.last.retain(|id, _| devices.get(id).is_some_and(|d| self.devices.get(id) == Some(d))); + let unchanged = |id: &u16| devices.get(id).is_some_and(|d| self.devices.get(id) == Some(d)); + self.last.retain(|id, _| unchanged(id)); + self.heard.retain(|id| unchanged(id)); self.devices = devices; } + /// The names of the pens listed, by device id, for the log. + fn pen_names(&self) -> Vec<&str> { + let mut pens: Vec<&Device> = self.devices.values().filter(|d| d.is_pen()).collect(); + pens.sort_by_key(|d| d.id); + pens.into_iter().map(|d| d.name.as_str()).collect() + } + + /// The pens listed, as the log line says it: under XWayland on a Wayland session this tells + /// whether XWayland lists the pen at all (#5622). + fn summary(&self) -> String { + let names = self.pen_names(); + if names.is_empty() { + "the X server lists no pen (a pointer device with an \"Abs Pressure\" valuator): a pen draws at full pressure".to_string() + } else { + format!("pens listed: {}", names.join(", ")) + } + } + + /// The name of pen `id` when this is the first event from it since it was listed, for the log: + /// it tells whether the pen's events reach the app at all. + fn first_event(&mut self, id: u16) -> Option<&str> { + let device = self.devices.get(&id).filter(|d| d.is_pen())?; + self.heard.insert(id).then_some(device.name.as_str()) + } + /// A raw motion or button event of device `id`, with the valuators that changed. fn handle(&mut self, id: u16, valuators: impl IntoIterator) -> Update { let Some(device) = self.devices.get(&id) else { return Update::Keep }; @@ -231,6 +260,9 @@ impl Pens { /// A raw event as the X server sends it: its valuator mask and the values of the valuators /// set in it. A pen's sample or another pointer's `None` goes into `pen`. fn raw_event(&mut self, pen: &PenSource, id: u16, mask: &[u32], values: &[f64]) { + if let Some(name) = self.first_event(id) { + log::info!("tablet: events arrive from the pen {name:?}"); + } if let Update::Set(sample) = self.handle(id, valuators(mask, values)) { pen.set(sample); } @@ -304,6 +336,7 @@ mod x11 { .map_err(|e| format!("XISelectEvents failed: {e}"))?; let mut pens = Pens::default(); pens.set_devices(query_devices(&conn)); + log::info!("tablet: {}", pens.summary()); std::thread::Builder::new() .name("vectorcraft-tablet-x11".into()) .spawn(move || run(&conn, &mut pens, &pen)) @@ -321,7 +354,14 @@ mod x11 { let values: Vec = e.axisvalues.iter().map(|v| fp3232(v.integral, v.frac)).collect(); pens.raw_event(pen, e.deviceid, &e.valuator_mask, &values); } - Event::XinputHierarchy(_) | Event::XinputDeviceChanged(_) => pens.set_devices(query_devices(conn)), + Event::XinputHierarchy(_) | Event::XinputDeviceChanged(_) => { + let before = pens.summary(); + pens.set_devices(query_devices(conn)); + let after = pens.summary(); + if after != before { + log::info!("tablet: {after}"); + } + } _ => {} } } @@ -623,6 +663,31 @@ mod tests { assert!(s.pressure < 0.001, "{}", s.pressure); } + /// #5622: the log names the pens the X server lists (XWayland's included) and the first event + /// from each, once, again after the pen is listed anew, and never for a mouse. + #[test] + fn the_log_names_the_pens_listed_and_the_first_event_from_each() { + let stylus = Device::new(11, "xwayland-tablet stylus:16", Some("xwayland-tablet stylus"), pen_valuators()); + let eraser = Device::new(12, "xwayland-tablet eraser:16", Some("xwayland-tablet eraser"), pen_valuators()); + let mut pens = Pens::default(); + assert!(pens.summary().contains("lists no pen"), "{}", pens.summary()); + pens.set_devices([eraser.clone(), mouse(4), stylus.clone()]); + assert_eq!(pens.summary(), "pens listed: xwayland-tablet stylus:16, xwayland-tablet eraser:16"); + assert_eq!(pens.first_event(11), Some("xwayland-tablet stylus:16")); + assert_eq!(pens.first_event(11), None, "once"); + assert_eq!(pens.first_event(4), None, "a mouse"); + assert_eq!(pens.first_event(99), None, "a device not listed"); + // Listed again unchanged: still heard. Another device under the same id: heard anew. + pens.set_devices([eraser.clone(), mouse(4), stylus]); + assert_eq!(pens.first_event(11), None); + pens.set_devices([eraser, mouse(4), pen(11)]); + assert_eq!(pens.first_event(11), Some("Wacom Intuos Pro M Pen stylus")); + // The events go into the feed as before. + let source = PenSource::default(); + pens.raw_event(&source, 12, &[0b100], &[65535.0]); + assert_eq!(source.current().map(|s| (s.eraser, s.pressure)), Some((true, 1.0))); + } + #[test] fn fixed_point_values() { assert_eq!(fp3232(3, 1 << 31), 3.5); diff --git a/apps/vectorcraft/src/xwayland.rs b/apps/vectorcraft/src/xwayland.rs index 38b210c05e..1471f44199 100644 --- a/apps/vectorcraft/src/xwayland.rs +++ b/apps/vectorcraft/src/xwayland.rs @@ -22,18 +22,61 @@ use std::path::{Path, PathBuf}; const X11_LIBS: &[&str] = &["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"]; -/// Whether the saved `linuxDisplayServer` and the environment ask for XWayland: `x11` chosen, or -/// any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen and -/// `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`); a Wayland session (winit picks Wayland whenever -/// `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set); and an X display to open. `pen` runs only after -/// the other checks. -pub fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option, pen: impl FnOnce() -> bool) -> bool { +/// What the pen check found: the name of the first pen, `None` when there is none, or why the +/// device list could not be read. +pub type PenProbe = Result, String>; + +/// Where the window opens, and why, as [`choose`] decides it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Choice { + /// Not a Wayland session: the window opens where winit opens it. + NotWayland, + /// XWayland, because Linux Display Server is X11 (XWayland). + Chosen, + /// XWayland, because the pen of this name is attached. + Pen(String), + /// Wayland: the session has no X display (`DISPLAY` is unset, as in the Flatpak on a Wayland + /// session), so XWayland can't be used. `x11` is whether X11 (XWayland) was chosen. + NoXDisplay { x11: bool }, + /// Wayland: `VECTORCRAFT_NATIVE_WAYLAND` keeps the window there. + NativeWayland, + /// Wayland: no pen is attached. + NoPen, + /// Wayland: the input devices could not be listed, for this reason. + NoDeviceList(String), +} + +impl Choice { + /// Whether the window opens through XWayland. + pub fn xwayland(&self) -> bool { + matches!(self, Self::Chosen | Self::Pen(_)) + } +} + +/// Where the saved `linuxDisplayServer` and the environment open the window: XWayland for `x11` +/// chosen, or for any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen +/// and `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`), on a Wayland session (winit picks Wayland +/// whenever `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set) with an X display to open. `pen` runs +/// only after the other checks. +pub fn choose(pref: Option<&str>, var: impl Fn(&str) -> Option, pen: impl FnOnce() -> PenProbe) -> Choice { let set = |name: &str| var(name).is_some_and(|v| !v.is_empty()); - let session = (set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET")) && set("DISPLAY"); - let native_wayland = var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0"); - match pref { - Some("x11") => session, - _ => session && !native_wayland && pen(), + if !set("WAYLAND_DISPLAY") && !set("WAYLAND_SOCKET") { + return Choice::NotWayland; + } + let x11 = pref == Some("x11"); + if !set("DISPLAY") { + return Choice::NoXDisplay { x11 }; + } + if x11 { + return Choice::Chosen; + } + if var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0") { + return Choice::NativeWayland; + } + match pen() { + Ok(Some(name)) => Choice::Pen(name), + Ok(None) => Choice::NoPen, + Err(e) => Choice::NoDeviceList(e), } } @@ -44,20 +87,28 @@ const BTN_TOOL_PEN: u32 = 0x140; const ABS_X: u32 = 0x00; const ABS_Y: u32 = 0x01; -/// Is a pen attached? Reads `/proc/bus/input/devices`; a file that can't be read has no pen. -pub fn pen_attached() -> bool { - std::fs::read_to_string("/proc/bus/input/devices").is_ok_and(|devices| has_pen(&devices)) +/// The pen attached, from `/proc/bus/input/devices`, or why that file could not be read. +pub fn pen_attached() -> PenProbe { + std::fs::read_to_string("/proc/bus/input/devices").map(|devices| find_pen(&devices)).map_err(|e| format!("/proc/bus/input/devices: {e}")) } -/// Is a pen among the input devices `/proc/bus/input/devices` lists? A pen is a device whose +/// Is a pen among the input devices `/proc/bus/input/devices` lists? +#[cfg(test)] +fn has_pen(devices: &str) -> bool { + find_pen(devices).is_some() +} + +/// The name of the first pen among the input devices `/proc/bus/input/devices` lists (its +/// `N: Name=` line without the quotes, empty when it has none). A pen is a device whose /// `B: KEY=` bitmap has `BTN_TOOL_PEN` and whose `B: ABS=` bitmap has `ABS_X` and `ABS_Y`, as /// libinput asks of a tablet tool. A virtual keyboard made with uinput can claim every key code, /// `BTN_TOOL_PEN` included, but has no absolute axes. -fn has_pen(devices: &str) -> bool { - devices.split("\n\n").any(|device| { - let bitmap = |name: &str| device.lines().find_map(|l| l.strip_prefix(name)); - bitmap("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN)) - && bitmap("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y)) +fn find_pen(devices: &str) -> Option { + devices.split("\n\n").find_map(|device| { + let field = |name: &str| device.lines().find_map(|l| l.strip_prefix(name)); + let pen = field("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN)) + && field("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y)); + pen.then(|| field("N: Name=").map_or_else(String::new, |n| n.trim().trim_matches('"').to_string())) }) } @@ -147,6 +198,11 @@ mod tests { panic!("the pen check ran") } + /// [`choose`] as a yes or no, with a pen check that finds a pen or none. + fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option, pen: impl FnOnce() -> bool) -> bool { + choose(pref, var, || Ok(pen().then(|| "Pen".to_string()))).xwayland() + } + #[test] fn xwayland_only_when_chosen_on_wayland_with_an_x_display() { let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]); @@ -183,6 +239,40 @@ mod tests { assert!(wanted(Some("x11"), &native, no_probe)); } + /// #5622: the choice names why the window stays on Wayland, where the pen does not reach it, + /// so that the log tells a missing X display (the Flatpak on a Wayland session) from a pen + /// that is not listed or a device list that can't be read. + #[test] + fn the_choice_says_why_the_window_stays_on_wayland() { + let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]); + let no_x = env(&[("WAYLAND_DISPLAY", "wayland-0")]); + let native = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), ("VECTORCRAFT_NATIVE_WAYLAND", "1")]); + let pen = || Ok(Some("ELAN9008:00 04F3:2C82 Stylus".to_string())); + let never = || -> PenProbe { panic!("the pen check ran") }; + assert_eq!(choose(None, env(&[("DISPLAY", ":0")]), never), Choice::NotWayland); + assert_eq!(choose(None, &no_x, never), Choice::NoXDisplay { x11: false }); + assert_eq!(choose(Some("x11"), &no_x, never), Choice::NoXDisplay { x11: true }); + assert_eq!(choose(Some("x11"), &wayland, never), Choice::Chosen); + assert_eq!(choose(Some("automatic"), &native, never), Choice::NativeWayland); + assert_eq!(choose(Some("automatic"), &wayland, pen), Choice::Pen("ELAN9008:00 04F3:2C82 Stylus".to_string())); + assert_eq!(choose(Some("x11WithPen"), &wayland, || Ok(None)), Choice::NoPen); + let unreadable = choose(None, &wayland, || Err("/proc/bus/input/devices: Permission denied".to_string())); + assert_eq!(unreadable, Choice::NoDeviceList("/proc/bus/input/devices: Permission denied".to_string())); + for stays in [Choice::NotWayland, Choice::NoXDisplay { x11: true }, Choice::NativeWayland, Choice::NoPen, unreadable] { + assert!(!stays.xwayland(), "{stays:?}"); + } + assert!(Choice::Chosen.xwayland() && Choice::Pen(String::new()).xwayland()); + } + + /// The pen check names the pen it found, for the log. + #[test] + fn the_pen_check_names_the_pen() { + assert_eq!(find_pen(WITH_PEN).as_deref(), Some("Wacom Intuos Pro M Pen")); + let without = WITH_PEN.split("\n\n").take(2).collect::>().join("\n\n"); + assert_eq!(find_pen(&without), None); + assert_eq!(find_pen("B: KEY=1c03 0 0 0 0 0\nB: ABS=3\n").as_deref(), Some(""), "a pen without a name line"); + } + /// `/proc/bus/input/devices` of a laptop with a Wacom Intuos Pro attached (64-bit longs: the /// pen's `KEY=1c03 0 0 0 0 0` has bit 0x140, `BTN_TOOL_PEN`), from PhotoCraft's tests. const WITH_PEN: &str = "I: Bus=0011 Vendor=0001 Product=0001 Version=ab83\n\ diff --git a/docs/development.md b/docs/development.md index 5a1b6efd95..ce215da81f 100644 --- a/docs/development.md +++ b/docs/development.md @@ -134,7 +134,7 @@ The window runs natively on Wayland (eframe's `wayland` feature) and on X11. On - **Clipboard owners that never answer (#510):** reading the clipboard waits on the app that owns it: arboard gives up on an X11 owner after 4 s for each format it tries, and a Wayland read waits for the owner to send its data. So on Linux the check that enables the Paste menu items runs on a background thread with a second clipboard handle (`crates/ui-egui/src/clipboard_probe.rs`, installed as `Services::clipboard_probe`), only while nothing is copied in the app and a document is open, and the window keeps drawing. Every arboard read on Linux and the BSDs, including the UI thread's (a paste, and a Copy or Cut checking what the clipboard held), runs on a worker thread with a handle of its own and waits 2 s at most: an owner that never sends its data costs one read that wait, and later reads fail at once until it answers. A paste's bitmap read waits up to 10 s on the paste's background thread, so the UI thread does not wait for it. When one of a paste's reads gets no answer in its 2 s, or a paste follows a read that has not been answered yet, such as the paste's own check whether the clipboard still holds what VectorCraft copied, the paste waits on that thread for that read's answer, up to 10 s after the read was sent, and pastes what it holds. When the answer is what VectorCraft copied, holds nothing to paste, or does not come, the paste takes the internal clipboard. On X11, quitting within 25 s of a read that got no answer waits for that read to end, so the app's own handle is the last one and hands what it copied to the clipboard manager when one runs. That includes a read of the Paste menu check's handle: quitting waits up to 27 s for the background thread to drop it before the app drops its own, and quits after that wait even when the handle has not been dropped. The app takes its windows off screen before these waits (`apps/vectorcraft/src/quit_windows.rs`). An X11 main window, an XWayland one included, is hidden. winit cannot hide a native Wayland window, so on Linux the app attaches no buffer to the main window's surface, which unmaps it while the window and its connection stay open for the Wayland clipboard. On Linux the X11 windows of floating panels and documents are unmapped through a second X11 connection. On native Wayland, floating panels and documents are normally drawn inside the main window; on the BSDs a native Wayland main window stays on screen until the waits end. Windows and macOS keep the check on the UI thread: Windows only asks which formats the clipboard holds, macOS asks the pasteboard server. - **Copied files:** files copied in a file manager (`text/uri-list`; `CF_HDROP` on Windows, file URLs on macOS) paste as the first one that is art (SVG, PDF, EPS, EMF/WMF or a bitmap; a `.ai` or `.ait` file from the editing data it holds, else as the PDF or PostScript it holds), before the clipboard's other formats (which include the files' paths as text). - **Dropping files on the window does not work under Wayland:** winit 0.30, which eframe 0.37 runs on, has no Wayland drag and drop ([winit#1881](https://github.com/rust-windowing/winit/issues/1881), added in winit 0.31; [egui#1563](https://github.com/emilk/egui/issues/1563)), so no `dropped_files` arrive. Until eframe moves to winit 0.31: copy the files in the file manager and paste them, use File › Place or Open, or open the window through XWayland, where drops work: set **Preferences › Performance › Linux Display Server** to **X11 (XWayland)** and restart (#1151), or start the app with `WAYLAND_DISPLAY= vectorcraft`. The preference (`linuxDisplayServer`, read at startup in `apps/vectorcraft/src/main.rs`, shown on Linux only) has winit open the window on X11 (`EventLoopBuilderExtX11::with_x11`) when the session is Wayland, `DISPLAY` is set and the X11 libraries winit loads are installed (`apps/vectorcraft/src/xwayland.rs` reads `ldconfig -p` and the usual library directories); otherwise the window opens on Wayland and the log says why. Unlike clearing `WAYLAND_DISPLAY`, it leaves the clipboard on the compositor's own. -- **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found: opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way. +- **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found (): opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). When the window stays on Wayland on such a session, the log says why (#5622): `no pen in /proc/bus/input/devices`, `can't look for a pen` with the reason, `VECTORCRAFT_NATIVE_WAYLAND is set`, `there is no X display (DISPLAY is unset)`, or that the X11 libraries aren't all installed. The Flatpak gets no X display on a Wayland session (`--socket=fallback-x11`); `flatpak override --user --socket=x11 ai.storyteller.vectorcraft` gives it one. `GDK_BACKEND=x11` does not move the window to XWayland: winit does not read it. Under X11 the log lists the pens the X server lists (`tablet: pens listed: …`, for example `xwayland-tablet stylus:16` under XWayland, or `the X server lists no pen`) and the first event from each pen (`tablet: events arrive from the pen …`). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way. - **Pen pressure under X11 and XWayland (#764):** winit 0.30 hands a pen to an X11 window as a mouse, without its pressure. When the window is on X11, XWayland included, the desktop app opens a second X connection (x11rb's `RustConnection`) and reads XInput2 raw events for every device (`apps/vectorcraft/src/tablet.rs`, from PhotoCraft's `crates/tablet`). A device with an `Abs Pressure` valuator is a pen, unless its XInput type is `TOUCHPAD` or `TOUCHSCREEN`. While a pen is the pointer that moved last, its pressure, scaled from the valuator's range to 0..1, reaches the tools that use pressure: the Paintbrush's pressure-sensitive brushes and the Liquify tools' Use Pressure Pen. The reader also reads `Abs Tilt X` and `Abs Tilt Y` (from a pen that has both) in degrees, scaled to ±60° when the valuator's range does not fit in ±90, and `Abs Rotary Z` (an Art Pen's barrel rotation) as a turn with the middle of the range at 0°; the Paintbrush records them for brushes with Tilt, Bearing and Rotation variation. A pen device whose name or XInput type contains `eraser` (in any case) is the pen's eraser end: while the pointer is over the window, the canvas selects the Eraser tool when the eraser end moves, and it selects the tool used before when the tip moves again (`crates/ui-egui/src/stylus.rs`). The X server needs XInput 2.1 or later; otherwise the log has a `tablet pressure:` warning with the reason, and the pen draws at full pressure. - **Pen tilt and rotation on macOS (#764):** with each tablet event's pressure (#852), `apps/vectorcraft/src/mac_tablet.rs` reads its `tilt`, −1..1 on each axis, scaled to ±60° with each axis keeping AppKit's sign (x positive to the right, y positive towards the bottom and the user), and its `rotation`, negated to run clockwise. Until a pen reports a tilt or a rotation other than 0 after it comes near the tablet, that value reads as none, since a pen without one reports 0. The Paintbrush records them as it does under X11. From 7310a8eb4f63ee0fc478c882cfecffd3204100c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 07:49:50 -0800 Subject: [PATCH 57/69] Dimension: Alt whole-path measure takes the outside of the stroke with Use Preview Bounds off too With Alt held, the Dimension tool's box over a path and the dimension of the whole path it places now reach the outside of the path's strokes whether Use Preview Bounds is on or off. Before, they did so only with Use Preview Bounds on, and with it off they went through the outermost points of the path. Every dimension of a whole path the tool places now records `"preview": true` in its extent source. Dimensions saved without it keep measuring between the outermost points, and `dimension.create` still defaults `preview` to false. --- crates/doc/src/dimension.rs | 14 +++--- crates/tools/src/dimension.rs | 80 +++++++++++++++++------------------ docs/dimensions.md | 16 ++++--- docs/target-app-parity.md | 2 +- 4 files changed, 58 insertions(+), 54 deletions(-) diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index 537a1d6e60..8a5c4e24fb 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -394,9 +394,11 @@ pub enum DimensionSource { /// it is vertical. Versions without this source do not open the file. Extent { node: NodeId, - /// Placed with Use Preview Bounds on: the points are moved out to the outside of the - /// strokes the path paints ([`preview_extents`]), the width or height that W and H show. - /// Versions without it measure between the outermost points themselves. + /// The points are moved out to the outside of the strokes the path paints + /// ([`preview_extents`]), the width or height that W and H show with Use Preview Bounds on. + /// The Dimension tool sets it on every dimension of a whole path it places. Without it, + /// as in files saved before the tool set it and in versions without it, the dimension + /// measures between the outermost points themselves. #[serde(default, skip_serializing_if = "std::ops::Not::not")] preview: bool, }, @@ -431,9 +433,9 @@ impl DimensionSource { } /// Whether a path it measures differs between `before` and `after`, or is in only one of them. /// A node without a path, or missing from both, counts as changed. For a dimension of a whole - /// path placed with Use Preview Bounds on, so does a change to the strokes the path paints - /// ([`stroked_by`]): their appearance, the node they come from, or which arrowheads they draw - /// on it, and the path being made into a guide or released from one. + /// path measured to the outside of its strokes (`preview`), so does a change to the strokes the + /// path paints ([`stroked_by`]): their appearance, the node they come from, or which arrowheads + /// they draw on it, and the path being made into a guide or released from one. pub fn art_changed(&self, before: &Document, after: &Document) -> bool { let strokes = matches!(self, Self::Extent { preview: true, .. }); self.nodes().into_iter().any(|id| match (before.node(id), after.node(id)) { diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 7f2a652e1f..e2337b5be0 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -42,35 +42,37 @@ impl Kind { } /// What the pointer is over. `Extent` is a path hovered with Alt held: its overall width or height, -/// with `preview` (Use Preview Bounds on) to the outside of its strokes. +/// to the outside of its strokes. #[derive(Clone, Debug, PartialEq)] enum Target { Segment(SegmentRef), Corner { first: SegmentRef, second: SegmentRef, at: Point }, Radial { source: DimensionSource, center: Point, radius: f64 }, - Extent { node: NodeId, preview: bool }, + Extent { node: NodeId }, } -/// A path, whether its points are moved out to its strokes, and the document its outermost points -/// ([`whole_ends`]) were read from ([`whole_box_source`]). -type WholeBoxKey = (NodeId, bool, (u64, u64, usize)); +/// A path and the document its outermost points ([`whole_ends`]) were read from +/// ([`whole_box_source`]). +type WholeBoxKey = (NodeId, (u64, u64, usize)); /// The key of a path's outermost points ([`WholeBoxKey`]), with the points. type WholeBox = (WholeBoxKey, Option<[(Point, Point); 2]>); /// The document a path's box is read from, with what identifies it: while an interaction is in /// progress, the document as it began; otherwise the document `cx` shows, at its revision. -fn whole_box_source<'a>(cx: &ToolContext<'a>, node: NodeId, preview: bool) -> (&'a vectorcraft_doc::Document, WholeBoxKey) { +fn whole_box_source<'a>(cx: &ToolContext<'a>, node: NodeId) -> (&'a vectorcraft_doc::Document, WholeBoxKey) { match cx.interaction_doc { - Some(began) => (began, (node, preview, (cx.revision.0, 0, std::ptr::from_ref(began).addr()))), - None => (cx.doc, (node, preview, (cx.revision.0, cx.revision.1, 0))), + Some(began) => (began, (node, (cx.revision.0, 0, std::ptr::from_ref(began).addr()))), + None => (cx.doc, (node, (cx.revision.0, cx.revision.1, 0))), } } -/// The outermost points a dimension of the whole path `node` measures: [`dimension::extents`], or -/// with `preview` [`dimension::preview_extents`], moved out to the outside of the path's strokes. -fn whole_ends(doc: &vectorcraft_doc::Document, node: NodeId, preview: bool) -> Option<[(Point, Point); 2]> { - if preview { dimension::preview_extents(doc, node) } else { dimension::extents(doc, node) } +/// The outermost points a dimension the tool places on the whole path `node` measures +/// ([`dimension::preview_extents`]): moved out to the outside of the path's strokes, whether Use +/// Preview Bounds is on or off. The dimension records `"preview": true`, so it measures to there +/// after later edits too. +fn whole_ends(doc: &vectorcraft_doc::Document, node: NodeId) -> Option<[(Point, Point); 2]> { + dimension::preview_extents(doc, node) } #[derive(Default)] @@ -1045,23 +1047,23 @@ impl DimensionTool { /// document changes. While an interaction is in progress they are read from the document as /// the interaction began, which each preview starts again from (as the levels in /// [`Self::preview`] are), so the previews themselves do not make the tool read the path again. - fn whole_box(&mut self, cx: &ToolContext, node: NodeId, preview: bool) -> Option<[(Point, Point); 2]> { - let (from, key) = whole_box_source(cx, node, preview); + fn whole_box(&mut self, cx: &ToolContext, node: NodeId) -> Option<[(Point, Point); 2]> { + let (from, key) = whole_box_source(cx, node); if let Some((kept, ends)) = self.whole_box && kept == key { return ends; } - let ends = whole_ends(from, node, preview); + let ends = whole_ends(from, node); self.whole_box = Some((key, ends)); ends } /// What the pointer at `p` is over. A Linear path hovered with `alt` held, before any point - /// is picked, is the whole path: with Use Preview Bounds on, to the outside of its strokes. + /// is picked, is the whole path, to the outside of its strokes. fn target(&self, cx: &ToolContext, p: Point, alt: bool) -> Option { let edge = pick(cx, p)?; match self.kind { - Kind::Linear if alt && self.points.is_empty() => Some(Target::Extent { node: edge.node, preview: cx.preview_bounds }), + Kind::Linear if alt && self.points.is_empty() => Some(Target::Extent { node: edge.node }), Kind::Linear => Some(Target::Segment(edge)), Kind::Angular => { let (anchor, at) = anchor_near(cx, &edge, p)?; @@ -1113,8 +1115,8 @@ impl DimensionTool { let mode = if p.distance(*center) >= *radius { DimensionMode::Radius } else { DimensionMode::Diameter }; self.recipe(mode, *center, p, Point::ZERO, Some(source.clone())) } - Target::Extent { node, preview } => { - let source = DimensionSource::Extent { node: *node, preview: *preview }; + Target::Extent { node } => { + let source = DimensionSource::Extent { node: *node, preview: true }; let mut d = self.recipe(DimensionMode::Linear, Point::ZERO, Point::new(1.0, 0.0), Point::ZERO, Some(source)); d.orientation = Orientation::Horizontal; d @@ -1139,7 +1141,7 @@ impl DimensionTool { } self.level_guide = None; let whole = match self.pending.as_ref().and_then(|d| d.source.as_ref()) { - Some(DimensionSource::Extent { node, preview }) => Some(self.whole_box(cx, *node, *preview)), + Some(DimensionSource::Extent { node, .. }) => Some(self.whole_box(cx, *node)), _ => None, }; let Some(d) = &mut self.pending else { return vec![] }; @@ -1408,8 +1410,8 @@ impl Tool for DimensionTool { } self.hover = self.target(cx, ev.pos, ev.mods.alt); let whole = match self.hover { - Some(Target::Extent { node, preview }) => { - self.whole_box(cx, node, preview); + Some(Target::Extent { node }) => { + self.whole_box(cx, node); true } _ => false, @@ -1562,15 +1564,14 @@ impl Tool for DimensionTool { out.push(Overlay::Line { a: *center, b: *center + toward / toward.hypot() * *radius, color, dashed: true }); } } - Some(Target::Extent { node, preview }) => { - // The box through the path's outermost points (with Use Preview Bounds on, out - // to its strokes): a Smart Guide, or with Smart Guides off a line in the - // tool's own color. Read again when the path changed since the pointer last - // moved. - let (from, at) = whole_box_source(cx, *node, *preview); + Some(Target::Extent { node }) => { + // The box through the path's outermost points, out to its strokes: a Smart + // Guide, or with Smart Guides off a line in the tool's own color. Read again + // when the path changed since the pointer last moved. + let (from, at) = whole_box_source(cx, *node); let b = match self.whole_box { Some((key, ends)) if key == at => ends, - _ => whole_ends(from, *node, *preview), + _ => whole_ends(from, *node), } .map(extent_box); if let Some(b) = b { @@ -2890,7 +2891,7 @@ mod tests { }; let mut t = DimensionTool::default(); t.pointer(&c, &held(PointerKind::Move, 150.0, 100.0)); - assert_eq!(t.hover, Some(Target::Extent { node: id, preview: false })); + assert_eq!(t.hover, Some(Target::Extent { node: id })); assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Line { color, .. } if *color == c.smart_guide_color))); // With Smart Guides off the box is not a Smart Guide, and at a high zoom the size stays by // the pointer. @@ -2907,7 +2908,7 @@ mod tests { t.pointer(&c, &held(PointerKind::Up, 150.0, 100.0)); assert!(t.pending.is_some() && t.points.is_empty()); let above = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 60.0))); - assert_eq!(above["source"], json!({"kind":"extent","node":id})); + assert_eq!(above["source"], json!({"kind":"extent","node":id,"preview":true})); assert_eq!(above["orientation"], json!("horizontal")); // Past a corner, the side the pointer is farther out on decides. let corner = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 280.0, 70.0))); @@ -2954,29 +2955,28 @@ mod tests { assert!(o.iter().any(near), "{o:?}"); } - /// With Use Preview Bounds on, the box Alt shows over a stroked path reaches the outside of its - /// stroke, and the dimension of the whole path it places measures to there, as W and H do; it - /// keeps doing so after the art changes (`"preview": true`). With the preference off, the box - /// and the dimension go through the outermost points. + /// With Use Preview Bounds on or off, the box Alt shows over a stroked path reaches the outside + /// of its stroke, and the dimension of the whole path it places measures to there; it keeps + /// doing so after the art changes (`"preview": true`). #[test] - fn with_preview_bounds_an_alt_placed_dimension_measures_the_outside_of_the_stroke() { + fn an_alt_placed_dimension_measures_the_outside_of_the_stroke_with_preview_bounds_on_or_off() { let (d, id) = doc_with_rect(); let (s, p) = (Selection::default(), paint()); let held = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y).with_mods(Mods { alt: true, ..Mods::default() }); let near = |a: f64, b: f64| (a - b).abs() < 1e-9; - for (preview, (left, right)) in [(true, (99.5, 200.5)), (false, (100.0, 200.0))] { + let (left, right) = (99.5, 200.5); + for preview in [true, false] { let c = ToolContext { preview_bounds: preview, ..cx(&d, &s, &p) }; let mut t = DimensionTool::default(); t.pointer(&c, &held(PointerKind::Move, 150.0, 100.0)); - assert_eq!(t.hover, Some(Target::Extent { node: id, preview })); + assert_eq!(t.hover, Some(Target::Extent { node: id })); let xs: Vec = t.overlays(&c).iter().filter_map(|o| if let Overlay::Line { a, .. } = o { Some(a.x) } else { None }).collect(); assert!(xs.iter().any(|x| near(*x, left)) && xs.iter().any(|x| near(*x, right)), "preview {preview}: {xs:?}"); t.pointer(&c, &held(PointerKind::Down, 150.0, 100.0)); t.pointer(&c, &held(PointerKind::Up, 150.0, 100.0)); let acts = t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 60.0)); let Some(Action::Preview(_, params)) = acts.last() else { panic!("{acts:?}") }; - let source = if preview { json!({"kind":"extent","node":id,"preview":true}) } else { json!({"kind":"extent","node":id}) }; - assert_eq!(params["source"], source); + assert_eq!(params["source"], json!({"kind":"extent","node":id,"preview":true}), "preview {preview}"); let (a, b) = (params["a"][0].as_f64().unwrap_or(f64::NAN), params["b"][0].as_f64().unwrap_or(f64::NAN)); assert!(near(a, left) && near(b, right), "preview {preview}: {a} to {b}"); } diff --git a/docs/dimensions.md b/docs/dimensions.md index ab5003a2b9..27972418af 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -105,12 +105,14 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers that starts no segment is left out. They are read again whenever the path changes, so a turned path shows its new overall width or height rather than that of its bounding box before the turn. The line keeps its distance from the whole path when the path changes or the dimension - changes orientation. With Use Preview Bounds on, the box and the dimension reach the outside of - the path's strokes, the width or height that W and H show: each outermost point moves out to the - edge of the box the strokes paint (a member of a compound path takes the compound path's - strokes, with an arrowhead only where the compound path draws one on that member), and a dimension placed that way measures to there again when the path or its strokes - change. Geometry effects are not included. Alt has this effect only before the first point is - clicked. + changes orientation. With Use Preview Bounds on or off, the box and the dimension reach the + outside of the path's strokes, the width or height that W and H show with Use Preview Bounds + on: each outermost point moves out to the edge of the box the strokes paint (a member of a + compound path takes the compound path's strokes, with an arrowhead only where the compound path + draws one on that member), and a dimension placed that way measures to there again when the + path or its strokes change. Geometry effects are not included. A dimension of a whole path saved + without `"preview":true` keeps measuring between the outermost points. Alt has this effect only + before the first point is clicked. - **Angular:** hover a corner where two straight segments meet and drag outwards. Or click two straight lines that meet (or would, extended), then click to place. - **Radial:** hover a circle, or a segment that is a perfect arc, and drag: outwards gives its @@ -205,7 +207,7 @@ another document. `vertical`), offset and style; returns the group id and label. `{"kind":"extent","node":}` measures a whole path, linear only: between its leftmost and rightmost points when horizontal or aligned, and its topmost and bottommost points when vertical. With `"preview":true` (what - the tool records with Use Preview Bounds on; `false` when omitted, and any value other than + the tool records for an Alt-placed dimension; `false` when omitted, and any value other than `true` or `false` is an error) those points move out to the outside of the path's strokes. A version without the extent source does not open a file that holds one, and a version without `preview` measures such a dimension between the points themselves. `offset` is the distance of diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9469046bc4..51ba964c82 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -757,7 +757,7 @@ since 2026-10-01. **Drawing tools, Ellipse tool circle from its center sized to touch a path:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a circle drawn from its center (Alt and Shift) snaps its radius so that the circle touches a nearby path whenever the radius comes within the snapping tolerance of that size. The touch point is where the line from the center meets a straight segment or a curve square, inside a segment or at an anchor where the path runs smoothly, also where a curve's handle lies on that anchor. A circle can touch another circle from outside or touch it from inside, and a center inside a closed path gives a circle that touches the path from within. A corner or an open path's end is not offered, nor a curve around the same center. The touch point shows the "tangent" label and the line from the center as guides; the radius is measured along the Constrain Angle's axes, as the drawn box is, and Space moves the circle at the size it snapped to, which it keeps when Space is let go. The snap does not apply to an ellipse (no Shift). When an anchor, center or crossing is within the snapping tolerance of the pointer, or the dragged corner snapped onto one, the circle is not resized to touch a path. Snap to Grid and pixel snapping place the drawn point instead, also when turned on during the drag, and turning Snap to Tangent off during the drag stops the snap. A press with a small jitter is still a click rather than a drag. At most 256 segments near that radius are measured per pointer move, the ones nearest the pointer. `a_circle_from_its_center_snaps_its_radius_to_touch_a_line`, `a_circle_from_its_center_snaps_to_touch_another_circle_from_outside_and_inside`, `a_circle_from_its_center_snaps_to_touch_a_curve`, `a_circle_from_its_center_keeps_its_radius_without_the_snap_or_a_smooth_touch`, `a_circle_from_its_center_prefers_an_anchor_and_measures_the_segments_nearest_the_pointer`, `a_circle_snapped_to_touch_keeps_to_the_constrain_angle`, `a_circle_from_its_center_does_not_snap_to_touch_with_the_grid_or_pixels`, `a_jittered_alt_shift_press_beside_a_path_is_a_click`, `a_circle_from_its_center_prefers_an_anchor_or_a_crossing_at_the_pointer` and `a_circle_from_its_center_touches_a_path_at_an_anchor_with_retracted_handles` cover it. **Drawing tools, selected Dimension extension-line style (#7078):** Properties › Dimension exposes the selected editable dimension's existing extension-line color and weight. Both extension lines share that style, independently of the main dimension line and label. Apply to All keeps its full-style behavior for editable dimensions, leaving a protected dimension unchanged; Set as Default keeps the whole style for a new dimension created without explicit options, without changing existing dimensions. The dimension remains editable. Four cases in `crates/ui-egui/tests/dimension_extension_properties.rs` verify actual Properties input, both canvas extension lines, independent main-line/label styling, full-style Apply to All, locked and unselected controls, defaults/new dimensions, Undo/Redo, and native save/reopen with further editing. Existing document-color conversion is unchanged. The measured geometry and existing snapping behavior are unchanged; no whole-Dimension completion or score/hour change is claimed. **Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it. -**Drawing tools, Dimension tool overall width and height of a path:** The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions with Alt (Option on macOS) held over its path. By VectorCraft's own rule, hovering a path with Alt held shows a box through its outermost points (a Smart Guide when Smart Guides are on); a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, and the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. With Use Preview Bounds on, the box and the dimension reach the outside of the path's strokes, which is the size W and H show when the path is not rotated and has no geometry effect (geometry effects such as Offset Path are not included), and the source records `"preview":true` so the dimension measures to there after later edits, a new stroke weight included. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `with_preview_bounds_an_alt_placed_dimension_measures_the_outside_of_the_stroke`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height`, `a_dimension_of_a_whole_path_with_preview_bounds_measures_the_outside_of_the_stroke`, `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` and `a_dimension_of_a_whole_path_survives_a_native_file` cover it. +**Drawing tools, Dimension tool overall width and height of a path:** The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions with Alt (Option on macOS) held over its path. By VectorCraft's own rule, hovering a path with Alt held shows a box through its outermost points (a Smart Guide when Smart Guides are on); a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, and the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. With Use Preview Bounds on or off, the box and the dimension reach the outside of the path's strokes, which is the size W and H show with Use Preview Bounds on when the path is not rotated and has no geometry effect (geometry effects such as Offset Path are not included), and the source records `"preview":true` so the dimension measures to there after later edits, a new stroke weight included; a dimension saved without it keeps measuring between the outermost points. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `an_alt_placed_dimension_measures_the_outside_of_the_stroke_with_preview_bounds_on_or_off`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height`, `a_dimension_of_a_whole_path_with_preview_bounds_measures_the_outside_of_the_stroke`, `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` and `a_dimension_of_a_whole_path_survives_a_native_file` cover it. **Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it. **Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. From ed0859d0d0a8809adc95feab96190324aa532b9f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 07:51:17 -0800 Subject: [PATCH 58/69] Scripts: kept-default option enumerations and refusal of non-UTF-8 real paths The enumerations whose default member an option keeps (OutputFlattening, CompressionQuality, the PDF color, compression, mark and security enums, and the SVG encoding, DTD, CSS and font enums) are now defined, so a script that sets an option to its default no longer throws a ReferenceError; another member still throws as not available yet. saveAs, exportFile, app.open and close with SAVECHANGES refuse a path whose real file name is not valid UTF-8 instead of writing to or opening a file named with a lossy copy of it. --- crates/engine/src/script/dom/save_open.rs | 88 +++++++++++++++++-- crates/engine/src/tests/script_save_open.rs | 86 ++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 37 +++++++- docs/mcp.md | 8 +- docs/target-app-parity.md | 2 +- 5 files changed, 209 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 060454798a..510364d249 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -110,6 +110,76 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[ ("PDFOverprint", &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"]), ("UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"]), ("SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"]), + // The enumerations of the options that keep their defaults (`Default::Member`). + ("OutputFlattening", &["PRESERVEAPPEARANCE", "PRESERVEPATHS"]), + ( + "CompressionQuality", + &[ + "AUTOMATICJPEG2000HIGH", + "AUTOMATICJPEG2000LOSSLESS", + "AUTOMATICJPEG2000LOW", + "AUTOMATICJPEG2000MAXIMUM", + "AUTOMATICJPEG2000MEDIUM", + "AUTOMATICJPEG2000MINIMUM", + "AUTOMATICJPEGHIGH", + "AUTOMATICJPEGLOW", + "AUTOMATICJPEGMAXIMUM", + "AUTOMATICJPEGMEDIUM", + "AUTOMATICJPEGMINIMUM", + "JPEG2000HIGH", + "JPEG2000LOSSLESS", + "JPEG2000LOW", + "JPEG2000MAXIMUM", + "JPEG2000MEDIUM", + "JPEG2000MINIMUM", + "JPEGHIGH", + "JPEGLOW", + "JPEGMAXIMUM", + "JPEGMEDIUM", + "JPEGMINIMUM", + "None", + "ZIP4BIT", + "ZIP8BIT", + ], + ), + ("ColorConversion", &["COLORCONVERSIONREPURPOSE", "COLORCONVERSIONTODEST", "None"]), + ( + "ColorDestination", + &[ + "COLORDESTINATIONDOCCMYK", + "COLORDESTINATIONDOCRGB", + "COLORDESTINATIONPROFILE", + "COLORDESTINATIONWORKINGCMYK", + "COLORDESTINATIONWORKINGRGB", + "None", + ], + ), + ("ColorProfile", &["INCLUDEALLPROFILE", "INCLUDEDESTPROFILE", "INCLUDERGBPROFILE", "LEAVEPROFILEUNCHANGED", "None"]), + ("DownsampleMethod", &["AVERAGEDOWNSAMPLE", "BICUBICDOWNSAMPLE", "NODOWNSAMPLE", "SUBSAMPLE"]), + ("MonochromeCompression", &["CCIT3", "CCIT4", "MONOZIP", "None", "RUNLENGTH"]), + ("PageMarksTypes", &["Japanese", "Roman"]), + ( + "PDFChangesAllowedEnum", + &[ + "CHANGE128ANYCHANGES", + "CHANGE128COMMENTING", + "CHANGE128EDITPAGE", + "CHANGE128FILLFORM", + "CHANGE128NONE", + "CHANGE40ANYCHANGES", + "CHANGE40COMMENTING", + "CHANGE40NONE", + "CHANGE40PAGELAYOUT", + ], + ), + ("PDFPrintAllowedEnum", &["PRINT128HIGHRESOLUTION", "PRINT128LOWRESOLUTION", "PRINT128NONE", "PRINT40HIGHRESOLUTION", "PRINT40NONE"]), + ("PDFTrimMarkWeight", &["TRIMMARKWEIGHT0125", "TRIMMARKWEIGHT025", "TRIMMARKWEIGHT05"]), + ("PDFXStandard", &["PDFX1A2001", "PDFX1A2003", "PDFX32002", "PDFX32003", "PDFX42007", "PDFXNONE"]), + ("SVGCSSPropertyLocation", &["ENTITIES", "PRESENTATIONATTRIBUTES", "STYLEATTRIBUTES", "STYLEELEMENTS"]), + ("SVGDocumentEncoding", &["ASCII", "UTF16", "UTF8"]), + ("SVGDTDVersion", &["SVG1_0", "SVG1_1", "SVGBASIC1_1", "SVGTINY1_1", "SVGTINY1_1PLUS", "SVGTINY1_2"]), + ("SVGFontSubsetting", &["ALLGLYPHS", "COMMONENGLISH", "COMMONROMAN", "GLYPHSUSED", "GLYPHSUSEDPLUSENGLISH", "GLYPHSUSEDPLUSROMAN", "None"]), + ("SVGFontType", &["CEFFONT", "OUTLINEFONT", "SVGFONT"]), ]; const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS"; @@ -676,9 +746,9 @@ fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer { Ok(answer) } -/// The path to give a command for the real path `real`. -fn plain(real: std::path::PathBuf) -> String { - crate::cmd::findfiles::plain(real).to_string_lossy().into_owned() +/// The path to give a command for the real path `real`, or an error when it is not valid UTF-8. +fn plain(real: std::path::PathBuf) -> std::result::Result { + crate::cmd::findfiles::plain(real).into_os_string().into_string().map_err(|_| HostError::Error("Script file path is not valid UTF-8".into())) } /// The built-in preset names scripts use that VectorCraft's built-in presets name otherwise, and the @@ -738,7 +808,7 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { p.insert("format".into(), json!(format)); } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; - p.insert("path".into(), json!(plain(real))); + p.insert("path".into(), json!(plain(real)?)); exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "saveAs", "file.saveAs", &Value::Object(p))))?; Ok(Data::Undefined) } @@ -793,7 +863,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { } let named = with_extension(path, &kind, svgz); let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; - p.insert("path".into(), json!(plain(real))); + p.insert("path".into(), json!(plain(real)?)); exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportFile", "document.export", &Value::Object(p))))?; Ok(Data::Undefined) } @@ -841,8 +911,10 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { if p.contains_key("cropTo") { p.insert("editingData".into(), json!(false)); } - h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; - p.insert("path".into(), json!(plain(std::path::PathBuf::from(path)))); + // 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))?; + plain(real)?; + p.insert("path".into(), json!(plain(std::path::PathBuf::from(path))?)); let r = exactly(h, || warned(h, "open", "document.open", &Value::Object(p)))?; let index = match &r { Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { @@ -1012,7 +1084,7 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { // A refusal names the document, as `fullName` does when the read roots hide its file. let name = super::with_doc(h, doc, |_, st| st.title()); let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?; - let p = json!({"path": plain(real), "format": format}); + let p = json!({"path": plain(real)?, "format": format}); exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "close", "file.saveAs", &p)))?; } _ => return Err(HostError::Error(UNSAVED_CHANGES.into())), diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 064ff3c15a..e8bd8675cb 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -212,6 +212,92 @@ fn omitted_options_are_a_new_options_objects_defaults() { let _ = std::fs::remove_dir_all(base); } +/// A path that resolves to a name that is not valid UTF-8 is refused before anything is written or +/// opened, so no file with a lossy copy of the name is touched. +#[cfg(unix)] +#[test] +fn script_file_commands_refuse_non_utf8_resolved_paths() { + use std::os::unix::ffi::OsStringExt; + + let base = folder("non-utf8-target"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let original = dir.join("original.vectorcraft"); + s.execute("file.saveAs", &json!({"path": original.to_string_lossy()})).unwrap(); + let bytes = std::fs::read(&original).unwrap(); + let target = dir.join(std::ffi::OsString::from_vec(b"target-\xff.vectorcraft".to_vec())); + // A file system that refuses such a name has nothing to refuse. + if std::fs::write(&target, &bytes).is_err() { + let _ = std::fs::remove_dir_all(base); + return; + } + let link = dir.join("alias.vectorcraft"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + let lossy = PathBuf::from(target.to_string_lossy().into_owned()); + std::fs::write(&lossy, &bytes).unwrap(); + for call in ["app.activeDocument.saveAs(f);", "app.activeDocument.exportFile(f, ExportType.SVG);", "app.open(f);"] { + let alias = if call.contains("exportFile") { + let alias = dir.join("alias.svg"); + std::os::unix::fs::symlink(&target, &alias).unwrap(); + alias + } else { + link.clone() + }; + let count = s.documents().len(); + let error = failure(&mut s, &base, &format!("Folder.userData; var f = new File({}); {call}", quoted(&alias))); + assert!(error.contains("Script file path is not valid UTF-8"), "{call}: {error}"); + assert_eq!(s.documents().len(), count); + assert_eq!(std::fs::read(&target).unwrap(), bytes); + assert_eq!(std::fs::read(&lossy).unwrap(), bytes); + } + let _ = std::fs::remove_dir_all(base); +} + +/// Every enumeration an option keeps its default in is defined: the default member is accepted, and +/// another member of the same enumeration is refused as not available yet. +#[test] +fn kept_enum_options_accept_their_default_member() { + let base = folder("keptenums"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let file = |n: &str| format!("new File({})", quoted(&dir.join(n))); + let cases: &[(&str, &str, &str, &str)] = &[ + ("IllustratorSaveOptions", "flattenOutput", "OutputFlattening.PRESERVEAPPEARANCE", "OutputFlattening.PRESERVEPATHS"), + ("PDFSaveOptions", "colorCompression", "CompressionQuality.None", "CompressionQuality.ZIP8BIT"), + ("PDFSaveOptions", "colorConversionID", "ColorConversion.None", "ColorConversion.COLORCONVERSIONTODEST"), + ("PDFSaveOptions", "colorDestinationID", "ColorDestination.None", "ColorDestination.COLORDESTINATIONPROFILE"), + ("PDFSaveOptions", "colorDownsamplingMethod", "DownsampleMethod.NODOWNSAMPLE", "DownsampleMethod.SUBSAMPLE"), + ("PDFSaveOptions", "colorProfileID", "ColorProfile.None", "ColorProfile.INCLUDEALLPROFILE"), + ("PDFSaveOptions", "monochromeCompression", "MonochromeCompression.None", "MonochromeCompression.CCIT4"), + ("PDFSaveOptions", "pageMarksType", "PageMarksTypes.Roman", "PageMarksTypes.Japanese"), + ("PDFSaveOptions", "pDFAllowPrinting", "PDFPrintAllowedEnum.PRINT128HIGHRESOLUTION", "PDFPrintAllowedEnum.PRINT40NONE"), + ("PDFSaveOptions", "pDFChangesAllowed", "PDFChangesAllowedEnum.CHANGE128ANYCHANGES", "PDFChangesAllowedEnum.CHANGE40NONE"), + ("PDFSaveOptions", "pDFXStandard", "PDFXStandard.PDFXNONE", "PDFXStandard.PDFX42007"), + ("PDFSaveOptions", "trimMarkWeight", "PDFTrimMarkWeight.TRIMMARKWEIGHT0125", "PDFTrimMarkWeight.TRIMMARKWEIGHT05"), + ("ExportOptionsSVG", "cssProperties", "SVGCSSPropertyLocation.STYLEATTRIBUTES", "SVGCSSPropertyLocation.ENTITIES"), + ("ExportOptionsSVG", "documentEncoding", "SVGDocumentEncoding.ASCII", "SVGDocumentEncoding.UTF8"), + ("ExportOptionsSVG", "DTD", "SVGDTDVersion.SVG1_1", "SVGDTDVersion.SVGTINY1_2"), + ("ExportOptionsSVG", "fontSubsetting", "SVGFontSubsetting.ALLGLYPHS", "SVGFontSubsetting.GLYPHSUSED"), + ("ExportOptionsSVG", "fontType", "SVGFontType.CEFFONT", "SVGFontType.OUTLINEFONT"), + ]; + for (i, (class, key, default, other)) in cases.iter().enumerate() { + let call = |value: &str, n: String| { + let set = format!("var o = new {class}(); o.{key} = {value};"); + match *class { + "ExportOptionsSVG" => format!("{set} app.activeDocument.exportFile({}, ExportType.SVG, o);", file(&format!("{n}.svg"))), + "PDFSaveOptions" => format!("{set} app.activeDocument.saveAs({}, o);", file(&format!("{n}.pdf"))), + _ => format!("{set} app.activeDocument.saveAs({}, o);", file(&format!("{n}.ai"))), + } + }; + logged(&mut s, &base, &format!("Folder.userData; {}", call(default, format!("ok{i}")))); + let e = failure(&mut s, &base, &format!("Folder.userData; {}", call(other, format!("no{i}")))); + assert!(e.contains("is not available yet"), "{class}.{key} = {other}: {e}"); + } + let _ = std::fs::remove_dir_all(base); +} + /// A raster export at 100% has one pixel per point, whatever the document's raster effects /// resolution. #[test] diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 4263fad910..b55418acb2 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -192,9 +192,42 @@ const INSIDE: &[(&str, &str)] = &[ // The enumerations of saving, exporting and opening. ( "", - "Compatibility EPSPostScriptLevelEnum EPSPreview ExportType PDFBoxType PDFCompatibility PDFOverprint SaveOptions \ - UserInteractionLevel", + "ColorConversion ColorDestination ColorProfile Compatibility CompressionQuality DownsampleMethod EPSPostScriptLevelEnum \ + EPSPreview ExportType MonochromeCompression OutputFlattening PDFBoxType PDFChangesAllowedEnum PDFCompatibility \ + PDFOverprint PDFPrintAllowedEnum PDFTrimMarkWeight PDFXStandard PageMarksTypes SVGCSSPropertyLocation SVGDTDVersion \ + SVGDocumentEncoding SVGFontSubsetting SVGFontType SaveOptions UserInteractionLevel", ), + ("ColorConversion.", "COLORCONVERSIONREPURPOSE COLORCONVERSIONTODEST None"), + ( + "ColorDestination.", + "COLORDESTINATIONDOCCMYK COLORDESTINATIONDOCRGB COLORDESTINATIONPROFILE COLORDESTINATIONWORKINGCMYK \ + COLORDESTINATIONWORKINGRGB None", + ), + ("ColorProfile.", "INCLUDEALLPROFILE INCLUDEDESTPROFILE INCLUDERGBPROFILE LEAVEPROFILEUNCHANGED None"), + ( + "CompressionQuality.", + "AUTOMATICJPEG2000HIGH AUTOMATICJPEG2000LOSSLESS AUTOMATICJPEG2000LOW AUTOMATICJPEG2000MAXIMUM AUTOMATICJPEG2000MEDIUM \ + AUTOMATICJPEG2000MINIMUM AUTOMATICJPEGHIGH AUTOMATICJPEGLOW AUTOMATICJPEGMAXIMUM AUTOMATICJPEGMEDIUM AUTOMATICJPEGMINIMUM \ + JPEG2000HIGH JPEG2000LOSSLESS JPEG2000LOW JPEG2000MAXIMUM JPEG2000MEDIUM JPEG2000MINIMUM JPEGHIGH JPEGLOW JPEGMAXIMUM \ + JPEGMEDIUM JPEGMINIMUM None ZIP4BIT ZIP8BIT", + ), + ("DownsampleMethod.", "AVERAGEDOWNSAMPLE BICUBICDOWNSAMPLE NODOWNSAMPLE SUBSAMPLE"), + ("MonochromeCompression.", "CCIT3 CCIT4 MONOZIP None RUNLENGTH"), + ("OutputFlattening.", "PRESERVEAPPEARANCE PRESERVEPATHS"), + ( + "PDFChangesAllowedEnum.", + "CHANGE128ANYCHANGES CHANGE128COMMENTING CHANGE128EDITPAGE CHANGE128FILLFORM CHANGE128NONE CHANGE40ANYCHANGES \ + CHANGE40COMMENTING CHANGE40NONE CHANGE40PAGELAYOUT", + ), + ("PDFPrintAllowedEnum.", "PRINT128HIGHRESOLUTION PRINT128LOWRESOLUTION PRINT128NONE PRINT40HIGHRESOLUTION PRINT40NONE"), + ("PDFTrimMarkWeight.", "TRIMMARKWEIGHT0125 TRIMMARKWEIGHT025 TRIMMARKWEIGHT05"), + ("PDFXStandard.", "PDFX1A2001 PDFX1A2003 PDFX32002 PDFX32003 PDFX42007 PDFXNONE"), + ("PageMarksTypes.", "Japanese Roman"), + ("SVGCSSPropertyLocation.", "ENTITIES PRESENTATIONATTRIBUTES STYLEATTRIBUTES STYLEELEMENTS"), + ("SVGDTDVersion.", "SVG1_0 SVG1_1 SVGBASIC1_1 SVGTINY1_1 SVGTINY1_1PLUS SVGTINY1_2"), + ("SVGDocumentEncoding.", "ASCII UTF16 UTF8"), + ("SVGFontSubsetting.", "ALLGLYPHS COMMONENGLISH COMMONROMAN GLYPHSUSED GLYPHSUSEDPLUSENGLISH GLYPHSUSEDPLUSROMAN None"), + ("SVGFontType.", "CEFFONT OUTLINEFONT SVGFONT"), ( "Compatibility.", "ILLUSTRATOR10 ILLUSTRATOR11 ILLUSTRATOR12 ILLUSTRATOR13 ILLUSTRATOR14 ILLUSTRATOR15 ILLUSTRATOR16 ILLUSTRATOR17 \ diff --git a/docs/mcp.md b/docs/mcp.md index d4cb072175..3e795ea765 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3131,7 +3131,13 @@ through `$`: explicit `null` throws a type error. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, `EPSPostScriptLevelEnum`, `PDFOverprint`, `SaveOptions` and `UserInteractionLevel` hold strings such as - `"ExportType.PNG24"`. + `"ExportType.PNG24"`. The enumerations of the options that keep their defaults (`OutputFlattening`, + `CompressionQuality`, `ColorConversion`, `ColorDestination`, `ColorProfile`, `DownsampleMethod`, + `MonochromeCompression`, `PageMarksTypes`, `PDFChangesAllowedEnum`, `PDFPrintAllowedEnum`, `PDFTrimMarkWeight`, + `PDFXStandard`, `SVGCSSPropertyLocation`, `SVGDocumentEncoding`, `SVGDTDVersion`, `SVGFontSubsetting` and + `SVGFontType`) are defined too: the default member is accepted, and another member throws as not available yet. A + path whose real file name is not valid UTF-8 throws `Script file path is not valid UTF-8` before anything is written + or opened. VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4e695e800b..0547365012 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1127,7 +1127,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - 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: `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, and read and write only where the script's `File` objects may; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.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`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `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`. From aa3415aa5e6d8a4f0b09a2511a80f191d739d34c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 08:09:18 -0800 Subject: [PATCH 59/69] Dimension: the Alt hover box is described as reaching the outside of the stroke The parity doc, docs/dimensions.md and two comments said the box shown while hovering a path with Alt held goes through the path's outermost points. It follows the box the strokes paint, which reaches 0.5 pt past those points for a centered 1 pt stroke. --- crates/tools/src/dimension.rs | 5 +++-- docs/dimensions.md | 4 ++-- docs/target-app-parity.md | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index e2337b5be0..b63dc44d9a 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -177,7 +177,8 @@ fn orientation_at(a: Point, b: Point, p: Point) -> Orientation { .map_or(Orientation::Aligned, |(_, orientation)| orientation) } -/// The box through a path's outermost points ([`whole_ends`]): left, top, right and bottom. +/// The box through a path's outermost points moved out to its strokes ([`whole_ends`]): left, top, +/// right and bottom. fn extent_box([(left, right), (top, bottom)]: [(Point, Point); 2]) -> Rect { Rect::new(left.x, top.y, right.x, bottom.y) } @@ -2875,7 +2876,7 @@ mod tests { } } - /// With Alt held, hovering a path shows the box through its outermost points as a Smart Guide, + /// With Alt held, hovering a path shows the box its strokes paint as a Smart Guide, /// and a click starts placing a dimension of the whole path: above or below it, its width; /// beside it, its height. A drag places it on release. Without Alt the same click picks a point. #[test] diff --git a/docs/dimensions.md b/docs/dimensions.md index 27972418af..a7359497aa 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -93,8 +93,8 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions by holding Alt - (Option on macOS) over its path. With Alt held, hovering a path shows a box through the path's - outermost points, as a Smart Guide when Smart Guides are on and in the tool's own color when + (Option on macOS) over its path. With Alt held, hovering a path shows the box the path's strokes + paint (described below), as a Smart Guide when Smart Guides are on and in the tool's own color when they are off, with its width and height beside the pointer when Measurement Labels are on. Clicking the path, then moving and clicking, places a dimension of the whole path; dragging out from the path places it on release. The rest is VectorCraft's own rule. With diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 51ba964c82..fa9187df61 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -757,7 +757,7 @@ since 2026-10-01. **Drawing tools, Ellipse tool circle from its center sized to touch a path:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a circle drawn from its center (Alt and Shift) snaps its radius so that the circle touches a nearby path whenever the radius comes within the snapping tolerance of that size. The touch point is where the line from the center meets a straight segment or a curve square, inside a segment or at an anchor where the path runs smoothly, also where a curve's handle lies on that anchor. A circle can touch another circle from outside or touch it from inside, and a center inside a closed path gives a circle that touches the path from within. A corner or an open path's end is not offered, nor a curve around the same center. The touch point shows the "tangent" label and the line from the center as guides; the radius is measured along the Constrain Angle's axes, as the drawn box is, and Space moves the circle at the size it snapped to, which it keeps when Space is let go. The snap does not apply to an ellipse (no Shift). When an anchor, center or crossing is within the snapping tolerance of the pointer, or the dragged corner snapped onto one, the circle is not resized to touch a path. Snap to Grid and pixel snapping place the drawn point instead, also when turned on during the drag, and turning Snap to Tangent off during the drag stops the snap. A press with a small jitter is still a click rather than a drag. At most 256 segments near that radius are measured per pointer move, the ones nearest the pointer. `a_circle_from_its_center_snaps_its_radius_to_touch_a_line`, `a_circle_from_its_center_snaps_to_touch_another_circle_from_outside_and_inside`, `a_circle_from_its_center_snaps_to_touch_a_curve`, `a_circle_from_its_center_keeps_its_radius_without_the_snap_or_a_smooth_touch`, `a_circle_from_its_center_prefers_an_anchor_and_measures_the_segments_nearest_the_pointer`, `a_circle_snapped_to_touch_keeps_to_the_constrain_angle`, `a_circle_from_its_center_does_not_snap_to_touch_with_the_grid_or_pixels`, `a_jittered_alt_shift_press_beside_a_path_is_a_click`, `a_circle_from_its_center_prefers_an_anchor_or_a_crossing_at_the_pointer` and `a_circle_from_its_center_touches_a_path_at_an_anchor_with_retracted_handles` cover it. **Drawing tools, selected Dimension extension-line style (#7078):** Properties › Dimension exposes the selected editable dimension's existing extension-line color and weight. Both extension lines share that style, independently of the main dimension line and label. Apply to All keeps its full-style behavior for editable dimensions, leaving a protected dimension unchanged; Set as Default keeps the whole style for a new dimension created without explicit options, without changing existing dimensions. The dimension remains editable. Four cases in `crates/ui-egui/tests/dimension_extension_properties.rs` verify actual Properties input, both canvas extension lines, independent main-line/label styling, full-style Apply to All, locked and unselected controls, defaults/new dimensions, Undo/Redo, and native save/reopen with further editing. Existing document-color conversion is unchanged. The measured geometry and existing snapping behavior are unchanged; no whole-Dimension completion or score/hour change is claimed. **Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it. -**Drawing tools, Dimension tool overall width and height of a path:** The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions with Alt (Option on macOS) held over its path. By VectorCraft's own rule, hovering a path with Alt held shows a box through its outermost points (a Smart Guide when Smart Guides are on); a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, and the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. With Use Preview Bounds on or off, the box and the dimension reach the outside of the path's strokes, which is the size W and H show with Use Preview Bounds on when the path is not rotated and has no geometry effect (geometry effects such as Offset Path are not included), and the source records `"preview":true` so the dimension measures to there after later edits, a new stroke weight included; a dimension saved without it keeps measuring between the outermost points. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `an_alt_placed_dimension_measures_the_outside_of_the_stroke_with_preview_bounds_on_or_off`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height`, `a_dimension_of_a_whole_path_with_preview_bounds_measures_the_outside_of_the_stroke`, `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` and `a_dimension_of_a_whole_path_survives_a_native_file` cover it. +**Drawing tools, Dimension tool overall width and height of a path:** The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions with Alt (Option on macOS) held over its path. By VectorCraft's own rule, hovering a path with Alt held shows the box its strokes paint, which reaches 0.5 pt past its outermost points for a centered 1 pt stroke (a Smart Guide when Smart Guides are on); a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, and the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. With Use Preview Bounds on or off, the box and the dimension reach the outside of the path's strokes, which is the size W and H show with Use Preview Bounds on when the path is not rotated and has no geometry effect (geometry effects such as Offset Path are not included), and the source records `"preview":true` so the dimension measures to there after later edits, a new stroke weight included; a dimension saved without it keeps measuring between the outermost points. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `an_alt_placed_dimension_measures_the_outside_of_the_stroke_with_preview_bounds_on_or_off`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height`, `a_dimension_of_a_whole_path_with_preview_bounds_measures_the_outside_of_the_stroke`, `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` and `a_dimension_of_a_whole_path_survives_a_native_file` cover it. **Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it. **Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. From 3d628608c6a488ec490fe759f888402cd84eb9d8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 08:09:21 -0800 Subject: [PATCH 60/69] Docs: the Flatpak override clears fallback-x11 before it allows X11 --- docs/development.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/development.md b/docs/development.md index ce215da81f..d176088bcb 100644 --- a/docs/development.md +++ b/docs/development.md @@ -134,7 +134,7 @@ The window runs natively on Wayland (eframe's `wayland` feature) and on X11. On - **Clipboard owners that never answer (#510):** reading the clipboard waits on the app that owns it: arboard gives up on an X11 owner after 4 s for each format it tries, and a Wayland read waits for the owner to send its data. So on Linux the check that enables the Paste menu items runs on a background thread with a second clipboard handle (`crates/ui-egui/src/clipboard_probe.rs`, installed as `Services::clipboard_probe`), only while nothing is copied in the app and a document is open, and the window keeps drawing. Every arboard read on Linux and the BSDs, including the UI thread's (a paste, and a Copy or Cut checking what the clipboard held), runs on a worker thread with a handle of its own and waits 2 s at most: an owner that never sends its data costs one read that wait, and later reads fail at once until it answers. A paste's bitmap read waits up to 10 s on the paste's background thread, so the UI thread does not wait for it. When one of a paste's reads gets no answer in its 2 s, or a paste follows a read that has not been answered yet, such as the paste's own check whether the clipboard still holds what VectorCraft copied, the paste waits on that thread for that read's answer, up to 10 s after the read was sent, and pastes what it holds. When the answer is what VectorCraft copied, holds nothing to paste, or does not come, the paste takes the internal clipboard. On X11, quitting within 25 s of a read that got no answer waits for that read to end, so the app's own handle is the last one and hands what it copied to the clipboard manager when one runs. That includes a read of the Paste menu check's handle: quitting waits up to 27 s for the background thread to drop it before the app drops its own, and quits after that wait even when the handle has not been dropped. The app takes its windows off screen before these waits (`apps/vectorcraft/src/quit_windows.rs`). An X11 main window, an XWayland one included, is hidden. winit cannot hide a native Wayland window, so on Linux the app attaches no buffer to the main window's surface, which unmaps it while the window and its connection stay open for the Wayland clipboard. On Linux the X11 windows of floating panels and documents are unmapped through a second X11 connection. On native Wayland, floating panels and documents are normally drawn inside the main window; on the BSDs a native Wayland main window stays on screen until the waits end. Windows and macOS keep the check on the UI thread: Windows only asks which formats the clipboard holds, macOS asks the pasteboard server. - **Copied files:** files copied in a file manager (`text/uri-list`; `CF_HDROP` on Windows, file URLs on macOS) paste as the first one that is art (SVG, PDF, EPS, EMF/WMF or a bitmap; a `.ai` or `.ait` file from the editing data it holds, else as the PDF or PostScript it holds), before the clipboard's other formats (which include the files' paths as text). - **Dropping files on the window does not work under Wayland:** winit 0.30, which eframe 0.37 runs on, has no Wayland drag and drop ([winit#1881](https://github.com/rust-windowing/winit/issues/1881), added in winit 0.31; [egui#1563](https://github.com/emilk/egui/issues/1563)), so no `dropped_files` arrive. Until eframe moves to winit 0.31: copy the files in the file manager and paste them, use File › Place or Open, or open the window through XWayland, where drops work: set **Preferences › Performance › Linux Display Server** to **X11 (XWayland)** and restart (#1151), or start the app with `WAYLAND_DISPLAY= vectorcraft`. The preference (`linuxDisplayServer`, read at startup in `apps/vectorcraft/src/main.rs`, shown on Linux only) has winit open the window on X11 (`EventLoopBuilderExtX11::with_x11`) when the session is Wayland, `DISPLAY` is set and the X11 libraries winit loads are installed (`apps/vectorcraft/src/xwayland.rs` reads `ldconfig -p` and the usual library directories); otherwise the window opens on Wayland and the log says why. Unlike clearing `WAYLAND_DISPLAY`, it leaves the clipboard on the compositor's own. -- **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found (): opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). When the window stays on Wayland on such a session, the log says why (#5622): `no pen in /proc/bus/input/devices`, `can't look for a pen` with the reason, `VECTORCRAFT_NATIVE_WAYLAND is set`, `there is no X display (DISPLAY is unset)`, or that the X11 libraries aren't all installed. The Flatpak gets no X display on a Wayland session (`--socket=fallback-x11`); `flatpak override --user --socket=x11 ai.storyteller.vectorcraft` gives it one. `GDK_BACKEND=x11` does not move the window to XWayland: winit does not read it. Under X11 the log lists the pens the X server lists (`tablet: pens listed: …`, for example `xwayland-tablet stylus:16` under XWayland, or `the X server lists no pen`) and the first event from each pen (`tablet: events arrive from the pen …`). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way. +- **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found (): opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). When the window stays on Wayland on such a session, the log says why (#5622): `no pen in /proc/bus/input/devices`, `can't look for a pen` with the reason, `VECTORCRAFT_NATIVE_WAYLAND is set`, `there is no X display (DISPLAY is unset)`, or that the X11 libraries aren't all installed. The Flatpak gets no X display on a Wayland session (`--socket=fallback-x11`); `flatpak override --user --nosocket=fallback-x11 --socket=x11 ai.storyteller.vectorcraft` gives it one and keeps its Wayland socket. `--socket=x11` alone is not enough: while `fallback-x11` is set, Flatpak gives the app no X display whenever Wayland is available. `GDK_BACKEND=x11` does not move the window to XWayland: winit does not read it. Under X11 the log lists the pens the X server lists (`tablet: pens listed: …`, for example `xwayland-tablet stylus:16` under XWayland, or `the X server lists no pen`) and the first event from each pen (`tablet: events arrive from the pen …`). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way. - **Pen pressure under X11 and XWayland (#764):** winit 0.30 hands a pen to an X11 window as a mouse, without its pressure. When the window is on X11, XWayland included, the desktop app opens a second X connection (x11rb's `RustConnection`) and reads XInput2 raw events for every device (`apps/vectorcraft/src/tablet.rs`, from PhotoCraft's `crates/tablet`). A device with an `Abs Pressure` valuator is a pen, unless its XInput type is `TOUCHPAD` or `TOUCHSCREEN`. While a pen is the pointer that moved last, its pressure, scaled from the valuator's range to 0..1, reaches the tools that use pressure: the Paintbrush's pressure-sensitive brushes and the Liquify tools' Use Pressure Pen. The reader also reads `Abs Tilt X` and `Abs Tilt Y` (from a pen that has both) in degrees, scaled to ±60° when the valuator's range does not fit in ±90, and `Abs Rotary Z` (an Art Pen's barrel rotation) as a turn with the middle of the range at 0°; the Paintbrush records them for brushes with Tilt, Bearing and Rotation variation. A pen device whose name or XInput type contains `eraser` (in any case) is the pen's eraser end: while the pointer is over the window, the canvas selects the Eraser tool when the eraser end moves, and it selects the tool used before when the tip moves again (`crates/ui-egui/src/stylus.rs`). The X server needs XInput 2.1 or later; otherwise the log has a `tablet pressure:` warning with the reason, and the pen draws at full pressure. - **Pen tilt and rotation on macOS (#764):** with each tablet event's pressure (#852), `apps/vectorcraft/src/mac_tablet.rs` reads its `tilt`, −1..1 on each axis, scaled to ±60° with each axis keeping AppKit's sign (x positive to the right, y positive towards the bottom and the user), and its `rotation`, negated to run clockwise. Until a pen reports a tilt or a rotation other than 0 after it comes near the tablet, that value reads as none, since a pen without one reports 0. The Paintbrush records them as it does under X11. From 53ec5af6c866e9201b88a583762f31144e7597bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 10:28:37 -0800 Subject: [PATCH 61/69] Smooth Bridge: a refusal says why an object is not a circle Smooth Bridge only joins circles. Anything else in the selection gave "select two or more circles to bridge", the same message as for one circle. An ellipse drawn by dragging without Shift is a few tenths of a point off a circle and was refused with that message, which did not say which object was at fault or why. The refusal now names the first object that is not a circle and why: an ellipse whose width and height differ (draw it with Shift held, or give it equal width and height), a compound path (release it first), an object that is hidden or locked, or another object. The message shows on the status line while the dialog previews and after OK. --- .../engine/src/cmd/addons/pathtools/bridge.rs | 47 +++++++++++++++---- .../src/cmd/addons/pathtools/bridge/tests.rs | 34 ++++++++++++++ crates/ui-egui/src/addons/pathtools/bridge.rs | 23 +++++++++ docs/mcp.md | 4 +- 4 files changed, 99 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs index 457114f820..449853d683 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -3,7 +3,7 @@ //! the bridges connect, replacing the circles or added above them. use serde_json::{Value, json}; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind}; use vectorcraft_geom::PathData; use vectorcraft_pathops::addons::pathtools as pt; @@ -34,7 +34,7 @@ pub(super) fn specs() -> Vec { "Smooth Bridge", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles", + "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles", has_selection, bridge )] @@ -61,17 +61,30 @@ fn bridge(s: &mut Session, p: &Value) -> Result { if roots.len() > pt::MAX_BRIDGED_CIRCLES { return Err(bad(C, "select at most 2000 circles to bridge")); } - let circles: Vec<(NodeId, pt::Circle)> = { + // The circles, and why the first object that is not one is refused. + let (circles, why): (Vec<(NodeId, pt::Circle)>, Option<&str>) = { let d = &s.doc()?.doc; let editable = d.editable(); - d.paint_order(roots.iter().copied()) + let mut why = None; + let circles = d + .paint_order(roots.iter().copied()) .into_iter() - .filter_map(|id| match &d.node(id)?.kind { - NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => Some((id, pt::circle_of(path)?)), - _ => None, + .filter_map(|id| { + let found = match &d.node(id)?.kind { + NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => pt::circle_of(path).map(|c| (id, c)), + _ => None, + }; + if found.is_none() && why.is_none() { + why = Some(not_a_circle(d, id, editable(id))); + } + found }) - .collect() + .collect(); + (circles, why) }; + if let Some(why) = why { + return Err(bad(C, format!("select two or more circles to bridge: {why}"))); + } if circles.len() != roots.len() || circles.len() < 2 { return Err(bad(C, "select two or more circles to bridge")); } @@ -156,6 +169,24 @@ fn members(d: &Document, ids: &[NodeId]) -> Vec { out } +/// Why object `id`, which is not a circle the command bridges, is refused; `editable` says whether it can be +/// edited (not hidden or locked). +fn not_a_circle(d: &Document, id: NodeId, editable: bool) -> &'static str { + // A pie spanning the whole turn, or none of it, is the whole ellipse. + let whole = |(start, end): (f64, f64)| { + let span = (end - start).rem_euclid(360.0); + span < 1e-9 || 360.0 - span < 1e-9 + }; + match d.node(id).map(|n| &n.kind) { + _ if !editable => "a selected object is hidden or locked", + Some(NodeKind::Path { live: Some(live), guide: false, clipping: false, .. }) if matches!(**live, LiveShape::Ellipse { pie, .. } if whole(pie)) => { + "an ellipse whose width and height differ is not a circle: draw it with Shift held, or give it equal width and height" + } + Some(NodeKind::Compound { .. }) => "a compound path is not a circle: release it first", + _ => "a selected object is not a circle", + } +} + /// The ids of `circles` at indices `at`, in paint order (the circles are listed in paint order). fn roots_of(circles: &[(NodeId, pt::Circle)], at: &[usize]) -> Vec { at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect() diff --git a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs index 8409ac2be6..caaa0b1b42 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs @@ -173,6 +173,40 @@ fn far_apart_nested_and_other_objects_are_refused() { assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step"); } +#[test] +fn a_refusal_says_why_an_object_is_not_a_circle() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + // A hand-drawn ellipse 1 pt taller than wide. + let oval = NodeId(s.execute("shape.ellipse", &json!({"x": 200, "y": 80, "width": 40, "height": 41})).unwrap()["id"].as_u64().unwrap()); + let square = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let steps = s.doc().unwrap().history.undo.len(); + let e = err(&mut s, json!({"ids": [a.0, oval.0]})); + assert!( + e.ends_with( + "select two or more circles to bridge: an ellipse whose width and height differ is not a circle: draw it with Shift held, or give it equal width and height" + ), + "{e}" + ); + let e = err(&mut s, json!({"ids": [a.0, square.0]})); + assert!(e.ends_with("select two or more circles to bridge: a selected object is not a circle"), "{e}"); + let e = err(&mut s, json!({"ids": [a.0]})); + assert!(e.ends_with("select two or more circles to bridge"), "one circle: {e}"); + select(&mut s, &[b]); + s.execute("object.hide", &json!({})).unwrap(); + let e = err(&mut s, json!({"ids": [a.0, b.0]})); + assert!(e.ends_with("select two or more circles to bridge: a selected object is hidden or locked"), "{e}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step for a refusal"); + + select(&mut s, &[a, b]); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let c = circle(&mut s, 300.0, 200.0, 20.0); + let e = err(&mut s, json!({"ids": [compound.0, c.0]})); + assert!(e.ends_with("select two or more circles to bridge: a compound path is not a circle: release it first"), "{e}"); +} + /// A 3 × 3 grid of circles of radius 10, 4 apart (centers 24 apart), in rows from (100, 100). fn grid(s: &mut Session) -> Vec { (0..9).map(|k| circle(s, 100.0 + 24.0 * (k % 3) as f64, 100.0 + 24.0 * (k / 3) as f64, 10.0)).collect() diff --git a/crates/ui-egui/src/addons/pathtools/bridge.rs b/crates/ui-egui/src/addons/pathtools/bridge.rs index 9cdf738b18..5ddeee621b 100644 --- a/crates/ui-egui/src/addons/pathtools/bridge.rs +++ b/crates/ui-egui/src/addons/pathtools/bridge.rs @@ -228,4 +228,27 @@ mod tests { let top: Vec = app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); assert_eq!(top, [ids[2], ids[3]], "one shape in the topmost joined circle's place, and the far circle"); } + + #[test] + fn the_status_line_says_why_an_ellipse_is_refused() { + use crate::tests::panel_harness::Panel; + + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let a = circle(&mut app, 100.0, 10.0); + let oval = app.run("shape.ellipse", json!({"x": 130, "y": 90, "width": 20, "height": 21})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, oval]})).unwrap(); + let original = geometry(&app); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + let before = panel.app().session.doc().unwrap().history.undo.len(); + menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); + panel.frame(); + let why = "an ellipse whose width and height differ is not a circle"; + assert!(panel.app().ui.status.contains(why), "the preview's refusal: {}", panel.app().ui.status); + panel.click("OK"); + panel.frame(); + assert!(panel.app().ui.status.contains(why), "OK's refusal: {}", panel.app().ui.status); + assert_eq!(geometry(&panel.app()), original); + assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before, "no undo step"); + } } diff --git a/docs/mcp.md b/docs/mcp.md index 7d8a3743ed..88a10b3ad0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -16854,7 +16854,9 @@ Commands: circle of the smaller circle's size about the arc's center. For equal circles that gap apart, that center is where a third circle the gap from both would sit, as in a triangular grid, so the channels around an empty place in such a grid are one width; in a square grid they are not. Giving both `radius` and `gap` is an error. Overlapping and - touching circles are joined at every radius. One circle inside the other is an error, and so are circles too far apart + touching circles are joined at every radius. An object that is not a circle is an error that says why: an ellipse whose + width and height differ, a compound path, an object that is hidden or locked, or another object. One circle inside the + other is an error, and so are circles too far apart for the radius or gap: the arcs would not reach both circles, or would cross before they do. The error suggests a larger radius or gap only when the largest (1,000% or 1,000 pt) would bridge the circles. The outline replaces the two circles, painted as the upper one (a plain path), unless `keepOriginals` is true: then it goes directly above the From 84dddbefd7a9c3fcee4e7b99237655319f574183 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 11:14:03 -0800 Subject: [PATCH 62/69] Docs: Feature areas rows drop gaps main already closes The Path operations row no longer lists Live Paint Gap Options, which ship with Gap Detection, custom sizes, Close Gaps With Paths and Preview. The Strokes row names the stylus wheel on native Wayland as the one place it is not read. The Type core row lists Optical Margin Alignment as done for point, area and path type, right-to-left paragraphs included. The Symbols row says embedded-document saves reopen with editable 9-slice guides only when that document is current and readable. --- docs/target-app-parity.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 77e2e3d54c..278cff6813 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -350,13 +350,13 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de |---|---:|---:|---|---:|---| | Selection, transform & align tools | 6 | 86% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 88% | Shaper construction widget, Pencil/Pen nuances; Touch Type (#2469), the Dimension tool (#1788) and the Blob Brush options (#2367) are done; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; 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 and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged | -| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 85% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; 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; compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | +| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 85% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options | 4–8 | estimated; 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; compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005); the Color Wheel panel's Show Opacity sets the opacity of the fill, stroke, gradient stop or freeform point it edits (part of #978), score and hours unchanged; gradient stop editor color-mode menu (#7918) | -| Strokes, brushes, width profiles | 5 | 90% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | +| Strokes, brushes, width profiles | 5 | 90% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, the stylus wheel on native Wayland (it is read under X11 and XWayland, on macOS, on Windows through Wintab and in the web build), more built-in brush libraries, tilt, bearing and rotation on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Appearance panel row context menus (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with unselected-row targeting, Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | -| Type core | 9 | 83% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | +| Type core | 9 | 83% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Optical Margin Alignment is done for point and area type and type on a path, right-to-left paragraphs included; remaining: Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | editable ruby text in standard SVG and PDF artwork (written as outlines; see [type-parity.md](type-parity.md)), custom Mojikumi sets and the Mojikumi Settings dialog, Retype from images, Retype panel matching depth and fused glyphs (see [type-parity.md](type-parity.md)), Touch Type along a line for a character with no immediately preceding logical character on the same line in the same direction (movement along the baseline is disabled; baseline shift still works) | 20–28 | estimated; Retype (`type.retype`, exact and tolerance-based outline matches, #4934); No Break suppresses automatic breaks within the marked run (a forced line break still breaks); upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | remaining: other apps ignore dynamic symbol instance overrides in the `.ai` editing copy, and VectorCraft restores them on instances the copy keeps live, within the limits the File formats row lists (fill and stroke changes to type are not reproduced, none of an instance's changes is written when they take more than 1 MiB together, and a change can apply to a different part when the copy leaves out an earlier one), further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guide settings in the standard SVG data and in the `.ai` editing data written for other apps (the scaled appearance is kept, and `.ai` or SVG saves that embed the VectorCraft document reopen with editable guides); Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | +| Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | remaining: other apps ignore dynamic symbol instance overrides in the `.ai` editing copy, and VectorCraft restores them on instances the copy keeps live, within the limits the File formats row lists (fill and stroke changes to type are not reproduced, none of an instance's changes is written when they take more than 1 MiB together, and a change can apply to a different part when the copy leaves out an earlier one), further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guide settings in the standard SVG data and in the `.ai` editing data written for other apps (the scaled appearance is kept, and `.ai` or SVG saves that embed the VectorCraft document reopen with editable guides when the embedded document is current and readable); Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | | Image Trace, graphs, image tools | 3 | 78% | Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, 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, so Paths is monotone on the code-drawn sweep; large images trace with a warning or are downsampled, and images beyond the size and decode limits in `crates/trace/src/raster.rs` are rejected; Auto Color keeps rare distinct colors in coherent regions when the Automatic palette classifies the image as flat artwork) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); Ignore Color canvas sampling reads the original pixels without changing View, keeps a missed pick armed, and retains the manual picker and Preview controls (#8068; scores, gaps and hours unchanged); Create Object Mosaic's dialog with New Size, Constrain Ratio, Resize Using Percentages and Use Ratio is covered by `dialogs::object_mosaic::tests` (score, gaps and hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged 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; runtime pending). | | Live vector effects | 5 | 90% | depth of individual effects | 4–8 | measured count 50/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | | 3D and Materials (and Turntable) | 4 | ~35% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows from lights after the first and in Classic effects (only the first light can cast a shadow in Revolve, Extrude & Bevel, Inflate and Rotate), ray tracing, Turntable views, shading and paint fidelity in 3D export (gradient stops are averaged, pattern paint is replaced with gray, and graphics mapped onto the sides of Extrude & Bevel objects and Map Art on the Classic effects are left out of Export 3D Object) | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); Revolve (Classic) is covered by the `revolve::classic` tests; `a_3d_row_sets_its_param_previews_and_applies_in_one_step` in `crates/ui-egui/src/dialogs/revolve/tests.rs` checks its Angle preview, OK, Cancel and single-step undo; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | From 9a060cfbf7e5dfa9fb06e98aa8a66b873e65411d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 11:17:57 -0800 Subject: [PATCH 63/69] Smooth Bridge: a stretched circle is not called an ellipse of unequal width and height A transform that stretches an ellipse keeps its stored width and height, so a circle stretched into an oval still stores equal ones. The refusal now names unequal width and height only when the stored values differ, and gives the general message otherwise. docs/mcp.md notes that more than 2,000 objects are refused by the circle limit before any object is checked. --- crates/engine/src/cmd/addons/pathtools/bridge.rs | 4 +++- .../engine/src/cmd/addons/pathtools/bridge/tests.rs | 12 +++++++++++- docs/mcp.md | 4 +++- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs index 449853d683..ea4f940ab9 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -179,7 +179,9 @@ fn not_a_circle(d: &Document, id: NodeId, editable: bool) -> &'static str { }; match d.node(id).map(|n| &n.kind) { _ if !editable => "a selected object is hidden or locked", - Some(NodeKind::Path { live: Some(live), guide: false, clipping: false, .. }) if matches!(**live, LiveShape::Ellipse { pie, .. } if whole(pie)) => { + // A transform that stretches an ellipse leaves its stored width and height as they were, so one stored with + // equal width and height gets the general message. + Some(NodeKind::Path { live: Some(live), guide: false, clipping: false, .. }) if matches!(**live, LiveShape::Ellipse { w, h, pie, .. } if whole(pie) && w != h) => { "an ellipse whose width and height differ is not a circle: draw it with Shift held, or give it equal width and height" } Some(NodeKind::Compound { .. }) => "a compound path is not a circle: release it first", diff --git a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs index caaa0b1b42..f9b9ea23ef 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs @@ -2,7 +2,7 @@ //! gap, many circles joined to their neighbors within reach, and what it refuses. use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{LiveShape, NodeId, NodeKind}; use vectorcraft_geom::kurbo::Shape; use crate::Session; @@ -181,6 +181,8 @@ fn a_refusal_says_why_an_object_is_not_a_circle() { // A hand-drawn ellipse 1 pt taller than wide. let oval = NodeId(s.execute("shape.ellipse", &json!({"x": 200, "y": 80, "width": 40, "height": 41})).unwrap()["id"].as_u64().unwrap()); let square = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let stretched = circle(&mut s, 300.0, 100.0, 20.0); + s.execute("object.transform", &json!({"ids": [stretched.0], "matrix": [2.0, 0.0, 0.0, 1.0, 0.0, 0.0]})).unwrap(); let steps = s.doc().unwrap().history.undo.len(); let e = err(&mut s, json!({"ids": [a.0, oval.0]})); assert!( @@ -191,6 +193,14 @@ fn a_refusal_says_why_an_object_is_not_a_circle() { ); let e = err(&mut s, json!({"ids": [a.0, square.0]})); assert!(e.ends_with("select two or more circles to bridge: a selected object is not a circle"), "{e}"); + // A circle stretched by a transform keeps its equal stored width and height, so it is not called unequal. + let equal = match s.doc().unwrap().doc.node(stretched).map(|n| &n.kind) { + Some(NodeKind::Path { live: Some(live), .. }) => matches!(**live, LiveShape::Ellipse { w, h, .. } if w == h), + _ => false, + }; + assert!(equal, "the stretched circle keeps a live ellipse of equal width and height"); + let e = err(&mut s, json!({"ids": [a.0, stretched.0]})); + assert!(e.ends_with("select two or more circles to bridge: a selected object is not a circle"), "{e}"); let e = err(&mut s, json!({"ids": [a.0]})); assert!(e.ends_with("select two or more circles to bridge"), "one circle: {e}"); select(&mut s, &[b]); diff --git a/docs/mcp.md b/docs/mcp.md index 88a10b3ad0..3797b2b3f6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -16855,7 +16855,9 @@ Commands: third circle the gap from both would sit, as in a triangular grid, so the channels around an empty place in such a grid are one width; in a square grid they are not. Giving both `radius` and `gap` is an error. Overlapping and touching circles are joined at every radius. An object that is not a circle is an error that says why: an ellipse whose - width and height differ, a compound path, an object that is hidden or locked, or another object. One circle inside the + width and height differ, a compound path, an object that is hidden or locked, or another object. More than 2,000 + objects (with groups counted as the objects inside them) are refused as more than 2,000 circles before any of them is + checked, so that error does not say which object is not a circle. One circle inside the other is an error, and so are circles too far apart for the radius or gap: the arcs would not reach both circles, or would cross before they do. The error suggests a larger radius or gap only when the largest (1,000% or 1,000 pt) would bridge the circles. The outline replaces the two From 798a029bfcb4f445b42f6c545d220b7d554131eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 11:44:20 -0800 Subject: [PATCH 64/69] Smooth Bridge: a group the bridged circles leave empty goes When outlines replace circles that sit in different groups, the circles that go left their groups behind with nothing in them. Each group or compound path left empty now goes in the same undo step, and so does each group above it left empty in turn; layers and sublayers stay. --- .../engine/src/cmd/addons/pathtools/bridge.rs | 25 ++++- .../src/cmd/addons/pathtools/bridge/tests.rs | 97 +++++++++++++++++++ docs/mcp.md | 4 +- 3 files changed, 123 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs index 4d4eb9cdf8..6742183bb8 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -34,7 +34,7 @@ pub(super) fn specs() -> Vec { "Smooth Bridge", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles", + "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles", has_selection, bridge )] @@ -117,7 +117,8 @@ fn bridge(s: &mut Session, p: &Value) -> Result { } beside.finish(d)?; } else { - // Each shape's topmost circle becomes its outline (a plain path now) and the others go. + // Each shape's topmost circle becomes its outline (a plain path now) and the others go, + // with each group they leave empty. let mut gone = vec![]; for (members, outline) in shapes { let Some((&top, rest)) = members.split_last() else { continue }; @@ -128,7 +129,9 @@ fn bridge(s: &mut Session, p: &Value) -> Result { made.push(top); gone.extend_from_slice(rest); } + let parents: Vec = gone.iter().filter_map(|id| d.parent_of(*id)).collect(); remove_each(d, &gone)?; + remove_emptied(d, parents)?; } sel.set(made.iter().chain(&alone).copied()); Ok(made) @@ -140,6 +143,24 @@ fn bridge(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// Remove each of `parents` that is left with nothing in it, and then each group above it left with +/// nothing in it in turn. Layers stay. +fn remove_emptied(d: &mut vectorcraft_doc::Document, parents: Vec) -> Result<()> { + for parent in parents { + let mut at = Some(parent); + while let Some(id) = at { + match d.node(id) { + Some(n) if !n.is_layer() && n.children().is_some_and(|c| c.is_empty()) => { + at = d.parent_of(id); + d.remove(id)?; + } + _ => break, + } + } + } + Ok(()) +} + /// The ids of `circles` at indices `at`, in paint order (the circles are listed in paint order). fn roots_of(circles: &[(NodeId, pt::Circle)], at: &[usize]) -> Vec { at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect() diff --git a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs index 745f216b68..726277b8b7 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs @@ -329,6 +329,103 @@ fn an_id_given_twice_is_one_circle() { assert_eq!(top_level(&s), [b]); } +/// The objects directly inside `id`. +fn inside(s: &Session, id: NodeId) -> Vec { + s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect() +} + +fn make(s: &mut Session, command: &str, ids: &[NodeId]) -> NodeId { + select(s, ids); + NodeId(s.execute(command, &json!({})).unwrap()["id"].as_u64().unwrap()) +} + +#[test] +fn a_group_the_bridged_circles_leave_empty_goes_in_the_same_undo_step() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let ga = make(&mut s, "object.group", &[a]); + let gb = make(&mut s, "object.group", &[b]); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!(r["id"], json!(b.0)); + assert_eq!(top_level(&s), [gb], "the lower circle's group, left empty, goes"); + assert_eq!(inside(&s, gb), [b], "the outline stays in the upper circle's group"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(top_level(&s), [ga, gb]); + assert_eq!((inside(&s, ga), inside(&s, gb)), (vec![a], vec![b])); + + // Kept circles leave their groups as they are. + s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "keepOriginals": true})).unwrap(); + assert_eq!(top_level(&s), [ga, gb]); + assert_eq!(inside(&s, ga), [a]); +} + +#[test] +fn groups_above_an_emptied_group_go_in_turn_and_a_group_with_other_objects_stays() { + let mut s = session(); + // a in a group that is all of another group; c in a group with a square; b on the layer. + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 20.0); + let c = circle(&mut s, 200.0, 100.0, 20.0); + let square = NodeId(s.execute("shape.rectangle", &json!({"x": 300, "y": 200, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let inner = make(&mut s, "object.group", &[a]); + let outer = make(&mut s, "object.group", &[inner]); + let gc = make(&mut s, "object.group", &[square, c]); + let layer = s.doc().unwrap().doc.layers[0].id; + let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0]})).unwrap(); + assert_eq!(ids(&r["ids"]), [c], "one shape, in the topmost circle's place"); + assert_eq!(top_level(&s), [gc], "both groups around a go, b goes from the layer"); + assert_eq!(inside(&s, gc), [c, square], "the group with the square stays"); + let d = &s.doc().unwrap().doc; + assert!(d.node(inner).is_none() && d.node(outer).is_none()); + assert!(d.node(layer).is_some(), "the layer stays"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(inside(&s, outer), [inner]); + assert_eq!(inside(&s, inner), [a]); +} + +#[test] +fn a_compound_path_the_bridged_circles_leave_empty_goes() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let compound = make(&mut s, "object.compoundPath.make", &[a]); + assert_eq!(inside(&s, compound), [a]); + s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!(top_level(&s), [b]); + assert!(s.doc().unwrap().doc.node(compound).is_none()); +} + +#[test] +fn layers_and_sublayers_the_bridged_circles_leave_empty_stay() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let upper = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": upper.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let c = circle(&mut s, 220.0, 100.0, 20.0); + // a below in the first layer, b and c in the sublayer: c's shape takes a's and b's places. + s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0], "reach": 30})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.layers.iter().any(|l| l.id != upper && l.children().is_some_and(|c| c.is_empty())), "the emptied layer stays"); + assert_eq!(inside(&s, sub), [c]); + // The sublayer left with nothing in it stays too. + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let upper = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": upper.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let b = circle(&mut s, 160.0, 100.0, 20.0); + s.execute("layer.setCurrent", &json!({"id": upper.0})).unwrap(); + let c = circle(&mut s, 220.0, 100.0, 20.0); + s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0], "reach": 30})).unwrap(); + assert_eq!(inside(&s, sub), Vec::::new(), "the emptied sublayer stays"); + assert_eq!(inside(&s, upper), [sub, c]); +} + #[test] fn small_circles_at_the_default_reach_bridge_the_pairs_the_arcs_can_join() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index e0e702d1cc..47247d1b8c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -16869,7 +16869,9 @@ Commands: larger radius or gap only when the largest (1,000% or 1,000 pt) would bridge the circles. The outline replaces the two circles, painted as the upper one (a plain path), unless `keepOriginals` is true: then it goes directly above the upper circle, painted as it, and the circles stay. The outline is selected. Two circles are bridged however far apart - their outlines are; `reach` does not apply to them. + their outlines are; `reach` does not apply to them. When outlines replace circles (with any number of circles), a group + or compound path that the circles leave with nothing in it is removed, and so is each group above it left empty in + turn; layers stay. With three or more circles, every two whose outlines are at most `reach` apart (0 to 10,000 pt, 10 by default; overlapping ones included) are bridged the same way, and the bridges that connect are united into one shape each, which can have holes where bridges enclose space; holes smaller than 1% of the smallest circle's area are filled. A From 0c722fbf2a6b9561a7597be6697242951797b5c4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 11:53:03 -0800 Subject: [PATCH 65/69] Docs: a clipping group counts as one object toward the Smooth Bridge limit docs/mcp.md said every group counts as the objects inside it toward the 2,000-object limit. The command expands only groups other than clipping groups (bridge.rs, the clip: false arm), so a clipping group counts as one object, which is not a circle. --- docs/mcp.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 32e0a0617b..033bdf6bc5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -16867,7 +16867,8 @@ Commands: grid are one width; in a square grid they are not. Giving both `radius` and `gap` is an error. Overlapping and touching circles are joined at every radius. An object that is not a circle is an error that says why: an ellipse whose width and height differ, a compound path, an object that is hidden or locked, or another object. More than 2,000 - objects (with groups counted as the objects inside them) are refused as more than 2,000 circles before any of them is + objects (with each group other than a clipping group counted as the objects inside it, and a clipping group as one + object, which is not a circle) are refused as more than 2,000 circles before any of them is checked, so that error does not say which object is not a circle. One circle inside the other is an error, and so are circles too far apart for the radius or gap: the arcs would not reach both circles, or would cross before they do. The error suggests a From 1d880065f3168180a251a4a9102238f8d02d113c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 12:17:05 -0800 Subject: [PATCH 66/69] Smooth Bridge: test a selected group of grouped circles A selected group that holds two groups of one circle each keeps the group with the outline, and the lower circle's group is removed. --- .../src/cmd/addons/pathtools/bridge/tests.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs index 088b707af3..3630bd6650 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs @@ -398,6 +398,21 @@ fn a_compound_path_the_bridged_circles_leave_empty_goes() { assert!(s.doc().unwrap().doc.node(compound).is_none()); } +#[test] +fn a_selected_group_of_grouped_circles_keeps_only_the_outlines_group() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let ga = make(&mut s, "object.group", &[a]); + let gb = make(&mut s, "object.group", &[b]); + let outer = make(&mut s, "object.group", &[ga, gb]); + select(&mut s, &[outer]); + s.execute(BRIDGE, &json!({})).unwrap(); + assert_eq!(top_level(&s), [outer]); + assert_eq!(inside(&s, outer), [gb], "the lower circle's group goes, the outline's stays"); + assert_eq!(inside(&s, gb), [b]); +} + #[test] fn layers_and_sublayers_the_bridged_circles_leave_empty_stay() { let mut s = session(); From 58923e0d78e25618be1f4af63775718e593f354d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 12:21:21 -0800 Subject: [PATCH 67/69] Menus: a menu opens under its title on a monitor beside a portrait one Moves craft-libs to a5669ed2f, which places overlays in the room of the monitor the window is on (craft-libs f31beb26d, merged in #4506). The old room assumed monitors tile the desktop by their size, so on a landscape monitor to the right of a portrait one the File menu opened at (726, 442), far from its title, with scroll arrows. The new pin is craft-libs main just before #4278, whose dialog changes need VectorCraft test updates that come with a later pin bump. The new test menu_on_second_monitor opens the File menu with the window on the landscape monitor at 1x and 1.5x; it fails on the old pin with the menu at (726, 442). --- Cargo.lock | 172 +++++++++--------- Cargo.toml | 76 ++++---- apps/vectorcraft-web/Cargo.toml | 2 +- .../ui-egui/tests/menu_on_second_monitor.rs | 110 +++++++++++ xtask/src/pdf_deps.rs | 2 +- 5 files changed, 236 insertions(+), 126 deletions(-) create mode 100644 crates/ui-egui/tests/menu_on_second_monitor.rs diff --git a/Cargo.lock b/Cargo.lock index 170ad40f3d..cf605de0f7 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "egui", ] @@ -1381,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "rayon", ] @@ -1444,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "serde", ] @@ -1494,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "gif", ] @@ -1619,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "flate2", ] @@ -1627,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" 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=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-keymap", @@ -1839,7 +1839,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "flate2", "serde", @@ -1850,7 +1850,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1862,7 +1862,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "async-channel", "async-io", @@ -1895,7 +1895,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1904,7 +1904,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-host", @@ -1928,7 +1928,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1939,7 +1939,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-eps", "flate2", @@ -1953,7 +1953,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "encoding_rs", "flate2", @@ -1964,7 +1964,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "dispatch2", "egui", @@ -1977,7 +1977,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1996,7 +1996,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-atomic", "craft-host", @@ -2013,7 +2013,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "fax", "hayro-ccitt", @@ -2024,7 +2024,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2045,7 +2045,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-keymap", @@ -2057,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2082,7 +2082,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2097,7 +2097,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-atomic", "craft-behavior", @@ -2112,7 +2112,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "serde", "thiserror 2.0.21", @@ -2122,7 +2122,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "serde", "thiserror 2.0.21", @@ -2131,7 +2131,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-keymap", @@ -2146,12 +2146,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2165,7 +2165,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-i18n", @@ -2181,7 +2181,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "accesskit", "craft-behavior", @@ -2219,7 +2219,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2230,7 +2230,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-host", @@ -2248,7 +2248,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-host", @@ -2269,7 +2269,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-host", @@ -2290,7 +2290,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-behavior", "craft-host", @@ -2309,7 +2309,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "base64 0.22.1", "chrono", @@ -2341,7 +2341,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "flate2", "serde", @@ -2352,7 +2352,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2362,7 +2362,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "js-sys", "serde_json", @@ -2373,7 +2373,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "winsafe", ] @@ -2381,7 +2381,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "craft-appkit", "craft-atomic", @@ -2413,7 +2413,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3772,7 +3772,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3781,7 +3781,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3799,7 +3799,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3817,12 +3817,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "flate2", "hayro-ccitt", @@ -4805,7 +4805,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4962,7 +4962,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=2680a3b3fe464c7afa3d260b33a828fa94e12f6d#2680a3b3fe464c7afa3d260b33a828fa94e12f6d" +source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index 7720ce4b8a..e1a20cac68 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,51 +10,51 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -194,13 +194,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 2dedefa32f..30d529a5e7 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/ui-egui/tests/menu_on_second_monitor.rs b/crates/ui-egui/tests/menu_on_second_monitor.rs new file mode 100644 index 0000000000..30fd5f6363 --- /dev/null +++ b/crates/ui-egui/tests/menu_on_second_monitor.rs @@ -0,0 +1,110 @@ +//! A menu bar menu opens under its title when the window sits on a second monitor that does not start at a multiple +//! of its own size (a landscape monitor beside a portrait one, their bottoms aligned). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::{Arc, Mutex}; + +use craft::behavior::{Monitor, MonitorKey}; +use craft::ui::testing::windows::FakeSystem; +use egui::accesskit::Role; +use egui::{Event, Pos2, RawInput, Rect, pos2, vec2}; +use serde_json::json; +use vectorcraft_engine::Session; +use vectorcraft_ui_egui::{VectorcraftApp, i18n}; + +// Integration tests link the production global shortcut mirror; each App owns it until its case ends. +static INPUT: Mutex<()> = Mutex::new(()); + +/// The window's content size in pixels, below a 44 px title bar on the landscape monitor. +const WINDOW_PX: [f32; 2] = [1920.0, 1156.0]; +/// Where the window's content starts on the desktop, in pixels. +const WINDOW_AT_PX: [f32; 2] = [1200.0, 764.0]; + +/// A portrait monitor at the desktop's origin and a landscape one to its right, their bottoms aligned. +fn monitors(scale: f32) -> Vec { + let portrait = Monitor::new(MonitorKey::new("portrait", [1200, 1920]), [0, 0], [1200, 1920], scale); + let landscape = Monitor::new(MonitorKey::new("landscape", [1920, 1200]), [1200, 720], [1920, 1200], scale); + vec![portrait, landscape] +} + +struct Scene { + app: VectorcraftApp, + ctx: egui::Context, + time: f64, + scale: f32, +} + +impl Scene { + fn new(scale: f32) -> Self { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let system = FakeSystem::new(); + system.set_monitors(monitors(scale)); + let spec = craft::ui::InstallSpec::new(craft::host::target::ShellInfo::default(), Arc::new(system)); + craft::ui::shell::embed::install(&ctx, spec, &vectorcraft_ui_egui::ui_fonts()).unwrap(); + Self { app, ctx, time: 0.0, scale } + } + + /// One frame of the whole window; returns the accessibility nodes with their bounds. + fn frame(&mut self, events: Vec) -> Vec<(Role, String, Rect)> { + self.time += 1.0 / 30.0; + let points = |[x, y]: [f32; 2]| pos2(x, y) / self.scale; + let size = points(WINDOW_PX).to_vec2(); + let mut raw = + RawInput { events, time: Some(self.time), focused: true, screen_rect: Some(Rect::from_min_size(Pos2::ZERO, size)), ..Default::default() }; + let viewport = raw.viewports.entry(egui::ViewportId::ROOT).or_default(); + viewport.native_pixels_per_point = Some(self.scale); + viewport.monitor_size = Some(vec2(1920.0, 1200.0) / self.scale); + viewport.inner_rect = Some(Rect::from_min_size(points(WINDOW_AT_PX), size)); + viewport.outer_rect = Some(Rect::from_min_size(points(WINDOW_AT_PX) - vec2(0.0, 44.0 / self.scale), size + vec2(0.0, 44.0 / self.scale))); + craft::ui::shell::embed::before_input(&self.ctx, |out| self.app.frame_input(out)); + let mut out = self.ctx.run_ui(raw, |ui| self.app.ui(ui)); + let _ = self.app.frame_input(craft::ui::runtime::frame::take_output(&self.ctx)); + out.textures_delta.clear(); + let update = out.platform_output.accesskit_update.take().unwrap(); + update + .nodes + .into_iter() + .filter_map(|(_, node)| { + let b = node.bounds()?; + let rect = Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)); + Some((node.role(), node.label().unwrap_or_default().to_string(), rect)) + }) + .collect() + } +} + +#[test] +fn the_file_menu_opens_under_its_title_on_a_monitor_beside_a_portrait_one() { + let _input = INPUT.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let previous = i18n::current(); + i18n::set_current(i18n::Lang::EN); + for scale in [1.0, 1.5] { + let mut scene = Scene::new(scale); + for _ in 0..3 { + scene.frame(vec![]); + } + let nodes = scene.frame(vec![]); + let title = nodes.iter().find(|(role, label, _)| *role == Role::MenuItem && label == "File").map(|(_, _, rect)| *rect); + let title = title.unwrap_or_else(|| panic!("no File title at {scale}x: {nodes:?}")); + let at = title.center(); + let button = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + scene.frame(vec![Event::PointerMoved(at)]); + scene.frame(vec![button(true)]); + scene.frame(vec![button(false)]); + let nodes = scene.frame(vec![]); + let menu = nodes.iter().filter(|(role, _, _)| *role == Role::Menu).map(|(_, _, rect)| *rect).next(); + let menu = menu.unwrap_or_else(|| panic!("the File menu did not open at {scale}x: {nodes:?}")); + // The menu's list sits inside the popup's frame, a few points in from the title's corner. + assert!( + (menu.left() - title.left()).abs() <= 8.0 && (menu.top() - title.bottom()).abs() <= 8.0, + "at {scale}x the File menu opens at {menu:?}, not under its title at {title:?}" + ); + // The whole menu shows: the window's content lies on the landscape monitor, so nothing cuts its room. + let items = nodes.iter().filter(|(role, _, rect)| *role == Role::MenuItem && menu.contains_rect(*rect)).count(); + assert!(items >= 15, "at {scale}x the File menu shows {items} items in {menu:?}"); + } + i18n::set_current(previous); +} diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 3e24ddc83c..216d23d43d 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 = "2680a3b3fe464c7afa3d260b33a828fa94e12f6d"; +const REV: &str = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From 77ed30177516bc6c2ef7f1de6a564a0692ae50d8 Mon Sep 17 00:00:00 2001 From: BFlat Date: Tue, 1 Dec 2026 03:42:59 +0700 Subject: [PATCH 68/69] SVG import: refuse an SVG the memory can't hold instead of running out (#10303) * SVG import: refuse an SVG the memory can't hold instead of running out The element limit now follows the installed memory, or the process's cgroup limit where that is lower: about 8 KB an element, up to the 999,999 elements usvg reads. Past it the SVG is refused with an error naming the memory, before usvg makes its tree. Fixes #10165 * Tests: the shared element limit test follows the machine's limit --- Cargo.lock | 1 + crates/svg/Cargo.toml | 2 + crates/svg/src/import.rs | 13 +++++-- crates/svg/src/import/budget.rs | 54 ++++++++++++++++++++++++--- crates/svg/src/import/files.rs | 8 ++-- crates/svg/src/lib.rs | 6 ++- crates/svg/tests/it/import_details.rs | 21 +++++++++-- xtask/src/layers.rs | 2 + 8 files changed, 89 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 170ad40f3d..5aff7bd0a3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9049,6 +9049,7 @@ dependencies = [ "vectorcraft-effects", "vectorcraft-geom 0.25.1", "vectorcraft-pathops 0.25.1", + "vectorcraft-render", "vectorcraft-testkit", "vectorcraft-text", ] diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 310b9c8e6f..08fcbbd3de 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -21,6 +21,8 @@ vectorcraft-effects = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-text = { workspace = true } vectorcraft-pathops = { workspace = true } +# Installed memory (cgroup limits included), which sizes the element limit. +vectorcraft-render = { workspace = true } kurbo = { workspace = true } # Image elements still go through usvg's image href resolution (src/import/files.rs, src/import/budget.rs). usvg = { workspace = true } diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 5e7afdd55a..20261eef95 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -28,6 +28,11 @@ pub(crate) use fx::BLEND; /// expansion bombs (#3564). pub const MAX_NODES: usize = if cfg!(target_arch = "wasm32") { 500_000 } else { 2_000_000 }; +/// Most elements an SVG may expand to on this machine, its memory considered (#10165). +pub fn max_elements() -> usize { + budget::max_elements() as usize +} + mod convert; mod importer; mod layers; @@ -112,7 +117,7 @@ pub(crate) fn svg_filters(svg: &str, room: usize, taken: impl Fn(&str) -> bool) } let xml = parse(svg)?; // Before the style cascade of `depth::height`, as `import` measures it. - budget::check(&xml, budget::Cost::LIMITS, depth::MAX_ELEMENT_DEPTH)?; + budget::check(&xml, budget::Cost::limits(), depth::MAX_ELEMENT_DEPTH)?; if depth::height(&xml, depth::MAX_ELEMENT_DEPTH).is_none() { return Err(too_deep()); } @@ -142,7 +147,7 @@ pub(crate) fn import_finding( let xml = parse(svg)?; // Before the style cascade of `depth::height` and the prepass, which keeps the declarations of // each element it reads; measured again below on the text usvg reads when that differs. - let spent = budget::check(&xml, budget::Cost::LIMITS, depth::MAX_ELEMENT_DEPTH)?; + let spent = budget::check(&xml, budget::Cost::limits(), depth::MAX_ELEMENT_DEPTH)?; let Some(height) = depth::height(&xml, depth::MAX_ELEMENT_DEPTH) else { return Err(too_deep()); }; @@ -165,8 +170,8 @@ pub(crate) fn import_finding( // Before usvg copies what ``s show and the style values of each copy: the text usvg reads. let spent = match &src { Cow::Borrowed(_) if !rewritten => spent, - Cow::Borrowed(_) => budget::check(&xml, budget::Cost::LIMITS, usize::MAX)?, - Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::Cost::LIMITS, usize::MAX)?, + Cow::Borrowed(_) => budget::check(&xml, budget::Cost::limits(), usize::MAX)?, + Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::Cost::limits(), usize::MAX)?, }; let files = found.files; files.spent_by_svg(spent); diff --git a/crates/svg/src/import/budget.rs b/crates/svg/src/import/budget.rs index 2520a8932a..b7b45f03da 100644 --- a/crates/svg/src/import/budget.rs +++ b/crates/svg/src/import/budget.rs @@ -6,8 +6,9 @@ //! sheets and the `style` attribute give the element, so a long style on an element that ``s //! copy, again and again in a chain, or that a style sheet rule gives to many elements, takes more //! memory than the file holds many times over. usvg stops past 1,000,000 elements, but only after -//! it has made them and copied their styles. An SVG past [`MAX_SVG_ELEMENTS`] elements or -//! [`MAX_COPIED_STYLES`] bytes of copied styles is refused here instead. +//! it has made them and copied their styles. An SVG past [`max_elements`] elements (fewer than +//! [`MAX_SVG_ELEMENTS`] when the machine's memory has room for fewer) or [`MAX_COPIED_STYLES`] +//! bytes of copied styles is refused here instead. //! //! The copies are counted, never made: each element's count is worked out once and added up, so a //! `` of an element costs one addition, however many elements its copy holds. References @@ -43,6 +44,32 @@ use crate::{MAX_ELEMENT_DEPTH, SvgError}; /// which usvg stops (its count includes a root of its own). pub(crate) const MAX_SVG_ELEMENTS: usize = if MAX_NODES < 999_999 { MAX_NODES } else { 999_999 }; +/// Memory an element takes, about, from reading the SVG to drawing what is made of it (bytes): a +/// 400,000-path SVG converted to PNG peaked at about 4.4 KB a path (#10165), with room to spare. +const ELEMENT_BYTES: u64 = 8 << 10; + +/// Most elements usvg may make of an SVG on this machine: [`MAX_SVG_ELEMENTS`], fewer when the +/// installed memory (or the process's cgroup limit) has room for fewer, so a large SVG is refused +/// with an error instead of running out of memory. +pub(crate) fn max_elements() -> u64 { + static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + *LIMIT.get_or_init(|| elements_for(vectorcraft_render::installed_memory())) +} + +/// [`max_elements`] with `memory` bytes installed (`None` or 0: not known). +fn elements_for(memory: Option) -> u64 { + memory.filter(|&m| m > 0).map_or(MAX_SVG_ELEMENTS as u64, |m| (m / ELEMENT_BYTES).min(MAX_SVG_ELEMENTS as u64)) +} + +/// The error for an SVG past [`max_elements`]: naming the memory when that is what limits it. +fn too_many_elements() -> SvgError { + let most = max_elements(); + match vectorcraft_render::installed_memory() { + Some(memory) if most < MAX_SVG_ELEMENTS as u64 => SvgError::TooLargeForMemory(most as usize, memory >> 20), + _ => SvgError::TooLarge(MAX_SVG_ELEMENTS), + } +} + /// Most bytes of style values usvg may copy into the elements of an SVG and the SVG images it /// shows, all together: VectorCraft's own limit. pub(crate) const MAX_COPIED_STYLES: u64 = 64 << 20; @@ -209,7 +236,9 @@ pub(crate) struct Cost { impl Cost { /// The most an SVG and the SVG images it shows may cost together. - pub(crate) const LIMITS: Cost = Cost { elements: MAX_SVG_ELEMENTS as u64, bytes: MAX_COPIED_STYLES, tests: MAX_SELECTOR_TESTS }; + pub(crate) fn limits() -> Cost { + Cost { elements: max_elements(), bytes: MAX_COPIED_STYLES, tests: MAX_SELECTOR_TESTS } + } pub(crate) fn add(self, other: Cost) -> Cost { Cost { @@ -408,7 +437,7 @@ pub(super) fn check(xml: &roxmltree::Document, left: Cost, depth: usize) -> Resu pub(super) fn check_spending(xml: &roxmltree::Document, left: Cost, depth: usize) -> (Result, u64) { let (result, tests) = measure_spending(xml, left, depth); let result = result.map_err(|past| match past { - Past::Elements => SvgError::TooLarge(MAX_SVG_ELEMENTS), + Past::Elements => too_many_elements(), Past::Bytes => SvgError::StylesTooLarge((MAX_COPIED_STYLES >> 20) as usize), Past::Tests => SvgError::StylesTooComplex, Past::Depth => SvgError::TooDeep(MAX_ELEMENT_DEPTH), @@ -562,6 +591,19 @@ mod tests { assert_eq!(MAX_SVG_ELEMENTS, if cfg!(target_arch = "wasm32") { 500_000 } else { 999_999 }); } + #[test] + fn less_memory_reads_fewer_elements_up_to_the_element_limit() { + let most = MAX_SVG_ELEMENTS as u64; + assert_eq!(elements_for(None), most, "unknown memory"); + assert_eq!(elements_for(Some(0)), most, "unknown memory"); + assert_eq!(elements_for(Some(1 << 40)), most, "plenty of memory"); + // A 1 GiB container can't hold the 400,000 paths that took 1.77 GB (#10165). + let small = elements_for(Some(1 << 30)); + assert!(small < 400_000, "{small}"); + assert!(elements_for(Some(512 << 20)) < small); + assert!(max_elements() <= most); + } + #[test] fn style_sheet_rules_count_where_they_match() { let groups = "".repeat(4); @@ -614,7 +656,7 @@ mod tests { let xml = roxmltree::Document::parse(&deep).unwrap(); assert_eq!(measure(&xml, NO_LIMITS, MAX_ELEMENT_DEPTH).err(), Some(Past::Depth)); assert!(super::super::depth::height(&xml, MAX_ELEMENT_DEPTH).is_none()); - assert!(matches!(check(&xml, Cost::LIMITS, MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_)))); + assert!(matches!(check(&xml, Cost::limits(), MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_)))); for text in [chain(5, ""), svg("")] { let xml = roxmltree::Document::parse(&text).unwrap(); let height = super::super::depth::height(&xml, usize::MAX).unwrap_or(0); @@ -674,7 +716,7 @@ mod tests { fn a_selector_that_never_matches_stops_at_the_test_limit() { let never = nested(60, &format!(".missing{} {{fill:red}}", " g".repeat(20))); let xml = roxmltree::Document::parse(&never).unwrap(); - assert_eq!(measure(&xml, Cost::LIMITS, usize::MAX).err(), Some(Past::Tests)); + assert_eq!(measure(&xml, Cost::limits(), usize::MAX).err(), Some(Past::Tests)); let before = super::super::css::selector_tests(); let err = super::super::import(&never, &crate::ImportOptions::default(), MAX_NODES).err(); assert!(matches!(err, Some(SvgError::StylesTooComplex)), "{err:?}"); diff --git a/crates/svg/src/import/files.rs b/crates/svg/src/import/files.rs index 631bed3d0c..525e900c87 100644 --- a/crates/svg/src/import/files.rs +++ b/crates/svg/src/import/files.rs @@ -478,7 +478,7 @@ impl Files { // reads it ([`Files::svg_tree`]), which then refuses one past the limits, within what the // linked SVG files measured before it left: past it, its links aren't read, and the // selector tests it made still count. - let (result, tests) = budget::check_spending(&xml, budget::Cost::LIMITS.less(reading.measured), left); + let (result, tests) = budget::check_spending(&xml, budget::Cost::limits().less(reading.measured), left); match result { Ok(cost) => reading.measured = reading.measured.add(cost), Err(e) => { @@ -593,13 +593,13 @@ impl Files { } /// What usvg makes of the SVG holding the images ([`budget::check`]): its images make at most - /// what is left of [`budget::Cost::LIMITS`]. + /// what is left of [`budget::Cost::limits()`]. pub(in crate::import) fn spent_by_svg(&self, spent: budget::Cost) { self.set_spent(spent); } fn spent(&self) -> budget::Cost { - self.spent.lock().map(|s| *s).unwrap_or(budget::Cost::LIMITS) + self.spent.lock().map(|s| *s).unwrap_or(budget::Cost::limits()) } fn set_spent(&self, spent: budget::Cost) { @@ -807,7 +807,7 @@ impl Files { // with theirs while usvg reads it, and only when it decodes. Too deep, it is left out; // past the other limits, the whole SVG is refused. let spent = self.spent(); - let cost = match budget::check(&xml, budget::Cost::LIMITS.less(spent), left) { + let cost = match budget::check(&xml, budget::Cost::limits().less(spent), left) { Ok(cost) => cost, Err(SvgError::TooDeep(_)) => return leave_out(&self.too_deep, true), Err(e) => { diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index ad3e91588f..0bcd5999b7 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -363,6 +363,10 @@ pub enum SvgError { /// nested-image expansion bombs, #3564). #[error("the SVG expands to more than {0} objects")] TooLarge(usize), + /// The SVG expands to more objects (the first number) than this machine's memory, or the + /// process's memory limit (the second number, in MB), has room to read (#10165). + #[error("the SVG expands to more than {0} objects, more than the {1} MB of memory available has room for")] + TooLargeForMemory(usize, u64), /// The SVG expands to more nested SVG images than the reader takes (a guard against /// nested-image expansion bombs, #3564). #[error("the SVG expands to more than {0} nested SVG images")] @@ -536,7 +540,7 @@ pub fn svg_filters(svg: &str, room: usize, taken: impl Fn(&str) -> bool) -> Resu pub use glyph::glyph_art; pub use import::{ MAX_DATA_URL_BYTES, MAX_ELEMENT_DEPTH, MAX_FOREIGN, MAX_FOREIGN_VALUE, MAX_NESTED_SVG_IMAGES, MAX_NESTED_SVG_READS, MAX_NESTED_SVG_TEXT, - MAX_NODES, + MAX_NODES, max_elements, }; /// Import an SVG document reading the files it links to as `opts` says, also returning warnings. diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index 25c5152de9..a4046e3fe7 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -892,11 +892,22 @@ fn styles_that_expand_past_the_limit_are_refused() { assert_eq!(art(&d).len(), 5000); } +/// `err` refuses an SVG past the element limit: the most usvg reads, or fewer on a machine whose +/// memory has room for fewer (#10165). +fn past_the_element_limit(err: &SvgError) -> bool { + let most = vectorcraft_svg::MAX_NODES.min(999_999); + match *err { + SvgError::TooLarge(n) => n == most, + SvgError::TooLargeForMemory(n, _) => n < most && n == vectorcraft_svg::max_elements(), + _ => false, + } +} + /// A chain of ``s that makes more elements than usvg reads is refused before usvg makes them. #[test] fn a_use_chain_past_the_elements_usvg_reads_is_refused() { let err = import_with(&use_chain(20, ""), &ImportOptions::default()).unwrap_err(); - assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}"); + assert!(past_the_element_limit(&err), "{err:?}"); } /// An SVG image whose styles expand past the limit refuses the SVG showing it, and the SVG images @@ -927,9 +938,13 @@ fn svg_images_share_the_element_limit() { assert_ne!(chain, unshown); let image = image_of("image/svg+xml", &unshown); let rect = r#""#; - assert!(import_with(&svg(&format!("{rect}{image}")), &ImportOptions::default()).is_ok()); + // One image fits, unless this machine's memory has room for fewer elements than it makes. + match import_with(&svg(&format!("{rect}{image}")), &ImportOptions::default()) { + Ok(_) => {} + Err(err) => assert!(vectorcraft_svg::max_elements() < 700_000 && past_the_element_limit(&err), "{err:?}"), + } let err = import_with(&svg(&format!("{rect}{}", image.repeat(2))), &ImportOptions::default()).unwrap_err(); - assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}"); + assert!(past_the_element_limit(&err), "{err:?}"); } /// A `:not()` rule, which only the import's own style cascade reads, counts toward the style limit diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index f2fb1f1ce0..869074b03f 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -80,6 +80,8 @@ pub const INTRA_LAYER_ORDER: &[&[&str]] = &[ &["pathops", "trace"], &["text", "effects"], &["render", "eps"], + // SVG import sizes its element limit from the installed memory the renderer reads (#10165). + &["render", "svg"], &["metafile", "eps"], // Non-native art in Illustrator editing data is a PDF, drawn by the PDF importer. &["pdf", "eps"], From cf2d168d49e50f92ff03fd9b89e51de247c67219 Mon Sep 17 00:00:00 2001 From: BFlat Date: Tue, 1 Dec 2026 05:05:57 +0700 Subject: [PATCH 69/69] PDF import: inline images with the same dictionary keep their own pixels (#10313) An inline image has no object of its own, and the interpreter keys an image by its dictionary alone, so every inline image of one size and encoding got the key of the first one and was imported with its pixels: Type 3 glyphs drawn as inline stencil images came in as the wrong letters. An inline raster image is now keyed by its samples too, and a stencil image by its decoded pixels. Fixes #9247 --- crates/pdf/src/import/device.rs | 10 +++++++- crates/pdf/src/tests/import_fidelity.rs | 33 +++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index 70aacd89cf..cd40578cec 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -246,8 +246,13 @@ impl<'a> Device<'a> for Builder<'_> { // replaces DeviceCMYK, so it is cached apart from the same image drawn where one does. let intent = !white && self.intent_cmyk.is_some() && self.scan.cmyk_defaults.get(&r.stream().dict().obj_id()) == Some(&false); // Inside an alpha mask the same image is read again, white (its own cache key). - let key = craft::pdf::interpret::CacheKey::cache_key(&r) ^ if white { WHITE_KEY } else { 0 } ^ if intent { INTENT_KEY } else { 0 }; let st = r.stream(); + // An inline image (no object of its own) is keyed by its samples too: the + // interpreter keys an image by its dictionary, the same for inline images of one + // size and encoding (#9247). + let inline = if st.dict().obj_id().is_none() { crate::import_scan::hash128(&*st.raw_data()) } else { 0 }; + let key = + craft::pdf::interpret::CacheKey::cache_key(&r) ^ inline ^ if white { WHITE_KEY } else { 0 } ^ if intent { INTENT_KEY } else { 0 }; let (w, h) = (r.width(), r.height()); // CMYK images keep their samples (read once per image). let known = !white && self.cmyk_keys.contains(&key); @@ -370,6 +375,9 @@ impl<'a> Device<'a> for Builder<'_> { None, ); let Some((px, w, h, sf)) = decoded else { return }; + // Keyed by its pixels too, as an inline raster image is by its samples: a stencil + // doesn't show its stream, and inline ones of one size share a dictionary (#9247). + let key = key ^ crate::import_scan::hash128(&px); let xf = transform * Affine::scale_non_uniform(sf.0 as f64, sf.1 as f64); match colorize { // Its own key: its pixels are the gray ones, whatever color paints it. diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 0be8dce82f..5fdafeb5fc 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -507,6 +507,39 @@ fn a_form_drawn_many_times_reads_its_font_resources_once() { assert_eq!(walk.fonts.len(), 1); } +/// Inline images with the same dictionary but other samples come in with their own pixels: the +/// stencil glyphs of a Type 3 font (#9247) and raster images on the page. +#[test] +fn inline_images_with_the_same_dictionary_keep_their_own_pixels() { + let n = first_extra(1); + let glyph = |hex: &str| { + stream("", &format!("1000 0 0 0 1000 1000 d1 q 1000 0 0 1000 0 0 cm BI /IM true /W 8 /H 8 /BPC 1 /D [1 0] /F /AHx ID\n{hex}>\nEI Q")) + }; + let objects = [ + format!( + "<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << /a {} 0 R /b {} 0 R >> /Encoding << /Type /Encoding /Differences [97 /a /b] >> /FirstChar 97 /LastChar 98 /Widths [1000 1000] /Resources << >> >>", + n + 1, + n + 2 + ), + glyph("1818181818181818"), + glyph("000000FFFF000000"), + ]; + let raster = |hex: &str| format!("q 10 0 0 10 0 0 cm BI /W 2 /H 1 /CS /RGB /BPC 8 /F /AHx ID\n{hex}>\nEI Q "); + let content = format!("BT /T3 24 Tf 10 30 Td (ab) Tj ET {}{}", raster("FF000000FF00"), raster("0000FFFFFFFF")); + let extra: Vec<&str> = objects.iter().map(String::as_str).collect(); + let d = open(&one_page(&content, &format!("/Font << /T3 {n} 0 R >>"), &extra)); + let blobs: Vec>> = all(&d) + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Image(im) => Some(d.images[&im.key].bytes.clone()), + _ => None, + }) + .collect(); + assert_eq!(blobs.len(), 4, "two glyphs and two raster images"); + let distinct: std::collections::HashSet<&Arc>> = blobs.iter().collect(); + assert_eq!(distinct.len(), blobs.len(), "each image has its own pixels"); +} + /// A Type 3 font that every page lists in a font dictionary of its own, and a form lists in its /// resources, has its glyph procedures read once for the document. Each page still maps the font's /// glyphs, and the font whose glyphs set their own color (`d0`) is told from the one whose glyphs