From c70eb7fc986a581b49d34ccf046f3434115eb9af Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:53:40 -0800 Subject: [PATCH 01/22] Scripts: character attributes set the fill and stroke of text A text range and its characterAttributes now have fillColor, strokeColor and strokeWeight. The colors take and give the same color objects as a path's fill and stroke; a NoColor takes the paint away, and a color out of range or of a kind that cannot be assigned yet throws with nothing changed. strokeWeight is 0 to 1000 points and reads in document points on scaled type. Setting the value a range already has records no undo step. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom/text.rs | 43 +++++++++-- crates/engine/src/tests/script_text.rs | 72 +++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 12 ++-- docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 5 files changed, 122 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 233ba56621..6595cfb926 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -3,7 +3,8 @@ //! `paragraphAttributes`, and `app.textFonts`, as the help pages //! , //! , -//! and +//! , +//! and //! describe them. //! //! VectorCraft's own rules, which the help pages do not state: @@ -33,6 +34,8 @@ //! value; set on an empty range it changes nothing. A paragraph attribute reads the first //! paragraph the range touches and sets every one of them. A text range has the members of //! both its `characterAttributes` and its `paragraphAttributes`. +//! - `fillColor` and `strokeColor` take and give color objects as a path's do; a `NoColor` takes +//! the paint away. `strokeWeight` is 0 to 1000 points. use std::cell::{Cell, RefCell}; use std::collections::{HashMap, VecDeque}; @@ -40,13 +43,14 @@ use std::rc::Rc; use std::sync::{Arc, Weak}; use serde_json::{Value, json}; +use vectorcraft_color::Paint; use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref}; use super::{ - Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, command, doc_of, doc_ref, edit_item, editable, float, - frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, text, typename_of, - whole, with_doc, + Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, colors, command, doc_of, doc_ref, edit_item, editable, + float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, text, + typename_of, whole, with_doc, }; use crate::{DocState, Document, NodeId, NodeKind}; @@ -789,9 +793,12 @@ enum Attr { Underline, StrikeThrough, TextFont, + FillColor, + StrokeColor, + StrokeWeight, } -const ATTRS: [(&str, Attr); 11] = [ +const ATTRS: [(&str, Attr); 14] = [ ("size", Attr::Size), ("leading", Attr::Leading), ("autoLeading", Attr::AutoLeading), @@ -803,6 +810,9 @@ const ATTRS: [(&str, Attr); 11] = [ ("underline", Attr::Underline), ("strikeThrough", Attr::StrikeThrough), ("textFont", Attr::TextFont), + ("fillColor", Attr::FillColor), + ("strokeColor", Attr::StrokeColor), + ("strokeWeight", Attr::StrokeWeight), ]; /// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with @@ -905,9 +915,18 @@ fn attr_value(h: &Host, attr: Attr, t: &TextObject, s: &CharStyle, para: usize) Attr::Underline => Data::Bool(s.underline), Attr::StrikeThrough => Data::Bool(s.strikethrough), Attr::TextFont => font_ref(h, &s.font_family, &s.font_style), + Attr::FillColor => colors::of_paint(&s.fill), + Attr::StrokeColor => colors::of_paint(&s.stroke), + Attr::StrokeWeight => num(s.stroke_width * stroke_scale(t)), } } +/// Document points per text-space point of a character stroke, as `text.setRangeStyle` scales a +/// `strokeWidth` it is given. +fn stroke_scale(t: &TextObject) -> f64 { + vectorcraft_doc::Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0) +} + /// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after. fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &CharStyle, usize)) -> std::result::Result<(Value, Data), HostError> { let finite = || number(v, name); @@ -976,6 +995,20 @@ fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, & let (family, style) = font_of(h, v)?; (json!({"font": family, "style": style}), font_ref(h, &family, &style)) } + Attr::FillColor | Attr::StrokeColor => { + let color = colors::assigned(v, name)?; + let paint = color.map_or(Paint::None, Paint::solid); + let given = color.map_or_else(|| json!("none"), |c| colors::param(&c)); + let key = if matches!(attr, Attr::FillColor) { "fill" } else { "stroke" }; + (json!({ key: given }), colors::of_paint(&paint)) + } + Attr::StrokeWeight => { + let n = finite()?; + if !(0.0..=1000.0).contains(&n) { + return Err(HostError::Range("strokeWeight must be from 0 to 1000 points".into())); + } + (json!({"strokeWidth": n}), num(n)) + } }) } diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index a357ecfe40..7d70741e69 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -225,6 +225,78 @@ fn setting_the_value_a_range_has_records_no_undo_step() { assert_eq!(undo_steps(&s), before); } +fn paints(s: &Session, id: NodeId) -> Vec<(String, Paint, Paint, f64)> { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.fill.clone(), r.style.stroke.clone(), r.style.stroke_width)).collect(), + _ => panic!("not text"), + } +} + +#[test] +fn character_attributes_paint_only_their_own_characters() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].textRange, b = r.characters[1].characterAttributes;\ + var red = new RGBColor(); red.red = 255; b.fillColor = red;\ + var k = new CMYKColor(); k.black = 100; b.strokeColor = k; b.strokeWeight = 2;\ + vc.log([b.fillColor.typename, b.fillColor.red, b.strokeColor.typename, b.strokeColor.black, b.strokeWeight]);\ + vc.log([r.characters[0].fillColor.red, r.characters[0].strokeColor.typename]);", + ); + let n = |v: &Value| v.as_f64().unwrap_or(f64::NAN); + assert_eq!((out[0][0].as_str(), out[0][2].as_str()), (Some("RGBColor"), Some("CMYKColor")), "{out:?}"); + assert_eq!((n(&out[0][1]), n(&out[0][3]), n(&out[0][4])), (255.0, 100.0, 2.0), "the paint reads back as given"); + assert_ne!(n(&out[1][0]), 255.0, "the first character keeps its fill"); + assert_eq!(out[1][1], json!("NoColor"), "the first character keeps no stroke"); + let runs = paints(&s, id); + let b = runs.iter().find(|r| r.0 == "b").expect("b is a run of its own"); + assert_eq!(b.1, Paint::solid(Color::rgb(1.0, 0.0, 0.0))); + assert_eq!(b.2, Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + assert!(b.3 > 1.0); + assert!(runs.iter().filter(|r| r.0 != "b").all(|r| r.1 != b.1 && r.2 == Paint::None), "{runs:?}"); + assert!(undo_steps(&s) > before); + + let steps = undo_steps(&s); + log(&mut s, "var b = app.activeDocument.textFrames[0].textRange.characters[1]; b.fillColor = b.fillColor; b.strokeWeight = b.strokeWeight;"); + assert_eq!(undo_steps(&s), steps, "setting the paint a range has records no undo step"); + log(&mut s, "app.activeDocument.textFrames[0].textRange.characters[1].strokeColor = new NoColor();"); + assert!(paints(&s, id).iter().all(|r| r.2 == Paint::None), "a NoColor takes the stroke away"); +} + +#[test] +fn stroke_weight_reads_back_in_document_points_on_scaled_type() { + let (mut s, id) = doc_with("abc"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.strokeWeight = 2; vc.log(r.strokeWeight);"); + assert!((out[0].as_f64().unwrap_or(f64::NAN) - 2.0).abs() < 1e-9, "{out:?}"); + let stored = paints(&s, id)[0].3; + assert!(stored < 2.0, "the type's own scale draws the stored width wider: {stored}"); + let steps = undo_steps(&s); + log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.strokeWeight = r.strokeWeight;"); + assert_eq!(undo_steps(&s), steps, "the weight read back is the weight it has"); +} + +#[test] +fn bad_text_paint_is_refused_without_a_change() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + let runs = paints(&s, id); + for (src, want) in [ + ("r.fillColor = 'red';", "fillColor must be a color object"), + ("var c = new RGBColor(); c.red = 300; r.strokeColor = c;", "RGBColor.red"), + ("r.fillColor = new GradientColor();", "not available yet"), + ("r.strokeWeight = -1;", "strokeWeight must be from 0 to 1000"), + ("r.characterAttributes.strokeWeight = 'thick';", "strokeWeight must be a finite number"), + ] { + let e = failure(&mut s, &format!("var r = app.activeDocument.textFrames[0].textRange; {src}")); + assert!(e.contains(want), "{src}: {e}"); + } + assert_eq!(undo_steps(&s), before); + assert_eq!(paints(&s, id), runs); +} + #[test] fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() { let (mut s, id) = doc_with("abc"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index a1893c17cf..016b0acd37 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -177,12 +177,14 @@ const INSIDE: &[(&str, &str)] = &[ "TextRange.prototype.", "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \ characterOffset= characterStyles characterStyles= characters constructor contents contents= deSelect deSelect= \ - duplicate duplicate= end end= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \ + duplicate duplicate= end end= fillColor fillColor= firstLineIndent firstLineIndent= getLocalCharOverridesJSON \ + getLocalCharOverridesJSON= \ getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \ horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \ leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles paragraphStyles= \ paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \ - spaceBefore spaceBefore= start start= story story= strikeThrough strikeThrough= textFont textFont= textRanges \ + spaceBefore spaceBefore= start start= story story= strikeThrough strikeThrough= strokeColor strokeColor= \ + strokeWeight strokeWeight= textFont textFont= textRanges \ textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \ verticalScale= words", ), @@ -195,9 +197,9 @@ const INSIDE: &[(&str, &str)] = &[ ("CharacterAttributes.", "prototype"), ( "CharacterAttributes.prototype.", - "autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \ - rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \ - underline= verticalScale verticalScale=", + "autoLeading autoLeading= baselineShift baselineShift= constructor fillColor fillColor= horizontalScale horizontalScale= \ + leading leading= rotation rotation= size size= strikeThrough strikeThrough= strokeColor strokeColor= strokeWeight \ + strokeWeight= textFont textFont= tracking tracking= typename underline underline= verticalScale verticalScale=", ), ("ParagraphAttributes.", "prototype"), ( diff --git a/docs/mcp.md b/docs/mcp.md index 08f1c2fc98..afa5506833 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2719,8 +2719,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot `add(contents, relativeObject?, insertionLocation?)` and `addBefore(contents)`, which insert the text and give its range, as one `text.editRange`. Character attributes are `size` (0.1 to 1296 pt), `leading` (0.1 to 5000 pt), `autoLeading`, `tracking` (-1000 to 10000), `baselineShift` (-1296 to 1296 pt), `horizontalScale` and - `verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough` and `textFont`, - set with `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are + `verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough`, `textFont`, + `fillColor` and `strokeColor` (color objects, as a path takes them; a `NoColor` takes the paint away) and + `strokeWeight` (0 to 1000 pt) (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/), set with + `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are `justification` (a `Justification` value, set with `text.setStyle`; the Auto alignment new type has reads as `LEFT`, or `RIGHT` in a right-to-left paragraph, and setting a value replaces it), `firstLineIndent`, `leftIndent`, `rightIndent`, `spaceBefore` and `spaceAfter` (-1296 to 1296 pt, set with `text.setFormat`). `app.textFonts` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 50d76e869f..57c3304e95 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,7 +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 and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font, fill and stroke colors, stroke weight) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles and tab stops are not there yet. `crates/engine/src/tests/script_text.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.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`. From a22c730c03e89ec97c037043dec337924ef188f2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:21:28 -0800 Subject: [PATCH 02/22] Scripts: text edits refuse hidden or locked type, and lists start with the topmost frame - Text edits (contents, added text, character and paragraph attributes) throw Cannot edit with nothing changed when the frame, or a layer or group it is in, is hidden or locked. - Text added after a range that ends inside a character goes after that character, and styling an empty range changes nothing. - Point changes that wait are written before a call that is put back on failure, and before the points of another path are read, so a failed call does not drop them. - A new path's id is read exactly from the command's result. - A saved or Recent preset's rows above 1,000 read as 1,000, so file.new takes the preset as file.newPresets lists it. - textFrames lists type topmost first, as pageItems does on main; the tests and docs/mcp.md follow. --- crates/engine/src/cmd/newdoc.rs | 11 +++- crates/engine/src/script/dom.rs | 4 +- crates/engine/src/script/dom/paths.rs | 19 ++++--- crates/engine/src/script/dom/text.rs | 39 +++++++++----- crates/engine/src/tests/newdoc.rs | 19 +++++++ crates/engine/src/tests/script_dom_paths.rs | 22 ++++++++ crates/engine/src/tests/script_text.rs | 59 ++++++++++++++++++--- docs/mcp.md | 2 +- 8 files changed, 140 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 4aad006ff1..6aabd654c3 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -171,8 +171,9 @@ pub struct DocSettings { pub layout: ArtboardLayout, /// Columns of a grid layout. pub columns: u32, - /// Rows of a grid by column, in place of `columns` when more than 0. - #[serde(skip_serializing_if = "is_zero")] + /// Rows of a grid by column, in place of `columns` when more than 0 (a saved or Recent preset's + /// value above `MAX_ARTBOARDS` is read as `MAX_ARTBOARDS`). + #[serde(skip_serializing_if = "is_zero", deserialize_with = "de_rows")] pub rows: u32, /// Space between artboards, points: 0 to `MAX_SPACING` (a saved or Recent preset's value /// outside that range is read as the nearer end). @@ -594,6 +595,12 @@ fn de_artboards<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result { + Ok(f64::deserialize(d)?.round().clamp(0.0, MAX_ARTBOARDS as f64) as u32) +} + /// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points. fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING)) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 1823b25a34..5537ab5d61 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -158,11 +158,13 @@ impl State { /// Runs `f`, whose commands are kept together or put back together: when `f` fails, every /// document, the selection and the undo histories are as they were before it, with no undo step -/// and no change to the document's saved state. +/// and no change to the document's saved state. Point changes that wait in [`State`] are written +/// first, so a failure in `f` does not put them back. fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { if h.dom.saving.get() { return f(h); } + flush(h)?; let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate"); h.dom.saving.set(true); let r = f(h); diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 823ed46d41..ea57a3f49b 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -164,13 +164,15 @@ fn same_path(a: Item, b: Item) -> bool { a.doc.uid == b.doc.uid && a.id == b.id } -/// Reads the subpaths of the path of `item` with `f`, its waiting point changes included. +/// Reads the subpaths of the path of `item` with `f`, its waiting point changes included. The +/// waiting point changes of another path are written first. fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) -> std::result::Result { if let Some((waiting, subs)) = &*h.dom.pending.borrow() && same_path(*waiting, item) { return Ok(f(subs)); } + flush(h)?; read_path(h, item, |_, _, pd| f(&pd.subpaths)) } @@ -372,20 +374,17 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// The id in the result of a command that made an object. -fn made_id(r: &Data) -> std::result::Result { - let id = match r { - Data::Object(o) => o.iter().find(|(k, _)| k == "id").and_then(|(_, v)| if let Data::Number(n) = v { whole(*n) } else { None }), - _ => None, - }; - id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) +/// The id in the JSON result of a command that made an object, read exactly, as the text creators +/// read it. +fn made_id(r: &(Data, Value)) -> std::result::Result { + r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) } /// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept, /// and reverses the new path's direction when `reversed`. → the new path. fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { let made = on_doc(h, doc.uid, true, |h| { - let id = made_id(&drawing_normally(h, || command(h, id, params))?)?; + let id = made_id(&drawing_normally(h, || super::command_value(h, id, params))?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -544,7 +543,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; - let id = made_id(&drawing_normally(h, || command(h, "path.create", &json!({"d": ""})))?)?; + let id = made_id(&drawing_normally(h, || super::command_value(h, "path.create", &json!({"d": ""})))?)?; if unpainted { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 6595cfb926..4a25a8300f 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -193,7 +193,7 @@ type Spans = [(usize, usize)]; #[derive(Default)] pub(in crate::script) struct TextState { frames: RefCell>, - /// A document's uid, the document, and the ids of its type objects in paint order. + /// A document's uid, the document, and the ids of its type objects, topmost first. list: RefCell>, /// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character /// names that is not installed is added at the end. @@ -301,6 +301,15 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u }) } +/// Runs command `id` with `params` on the text frame of `item`. Throws `Cannot edit`, with nothing +/// changed, when the frame or a layer or group it is in is hidden or locked. +fn edit_text(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { + if !with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)) { + return Err(HostError::Error(format!("Cannot edit TextFrame {}: it, or a layer or group it is in, is hidden or locked", item.id.0))); + } + edit_item(h, item, id, params) +} + /// Records an edit the model made to the frame: `removed` units at `at` replaced by `inserted`. /// When the text is not what that edit gives, every earlier range goes stale. fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> { @@ -445,7 +454,7 @@ fn write_contents(h: &Host, r: Span, value: &Data) -> Answer { return Ok(Data::Undefined); } let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count()); - edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?; + edit_text(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?; record(h, r.item, &index, s, e - s, &insert)?; Ok(Data::Undefined) } @@ -719,16 +728,17 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { let (r, part) = this_part(h, a)?; let contents = contents_of(arg(a, 1))?; let (index, s, e, _) = resolve(h, r)?; - let at = if before || matches!(arg(a, 2), Data::Undefined) { + // The place, and whether it is the end of a range, which rounds up to a character boundary. + let (at, after) = if before || matches!(arg(a, 2), Data::Undefined) { let (items, spans) = part_spans(&index, part, s, e); let span = |k: usize| match spans { None => index.char_span(k), Some(list) => list.get(k).copied(), }; if before { - items.clone().next().and_then(span).map_or(s, |(x, _)| x) + (items.clone().next().and_then(span).map_or(s, |(x, _)| x), false) } else { - items.clone().next_back().and_then(span).map_or(e, |(_, y)| y) + (items.clone().next_back().and_then(span).map_or(e, |(_, y)| y), true) } } else { let rel = arg(a, 2); @@ -741,13 +751,15 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { return Err(HostError::Error("relativeObject must be text of the same text frame".into())); } let (_, ts, te, _) = resolve(h, target)?; - if text_placement(arg(a, 3))? { te } else { ts } + if text_placement(arg(a, 3))? { (te, true) } else { (ts, false) } }; + // A place inside a character (between the two halves of a surrogate pair) moves to its edge. + let b = index.byte(at, after); + let at = index.text[..b].encode_utf16().count(); if contents.is_empty() { let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; return Ok(range_ref(h, r.item, at, at, stamp, "TextRange")); } - let b = index.byte(at, false); let (prev, next) = (index.text[..b].chars().next_back(), index.text[b..].chars().next()); let (lead, trail) = match part { Part::Characters => ("", ""), @@ -763,7 +775,7 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { ), }; let insert = format!("{lead}{contents}{trail}"); - edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?; + edit_text(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?; record(h, r.item, &index, at, 0, &insert)?; let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; let start = at + lead.encode_utf16().count(); @@ -1042,7 +1054,8 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1))?; // A leading set on characters with auto leading fixes it even where auto gives that value. let has = |st: &CharStyle, p: usize| (!matches!(attr, Attr::Leading) || st.leading.is_some()) && same(&attr_value(h, attr, t, st, p), &wants); - let unchanged = ba == bb || styles.iter().all(|(st, p)| has(st, *p)); + // An empty range changes nothing, also one inside a character that `ba..bb` widens to it. + let unchanged = s == e || ba == bb || styles.iter().all(|(st, p)| has(st, *p)); let fixed = match (attr, &wants) { (Attr::AutoLeading, Data::Bool(false)) if !unchanged => Some(auto_leading_spans(t, ba, bb)?), _ => None, @@ -1060,7 +1073,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { super::atomically(h, |h| { for (start, end, leading) in &spans { let p = json!({"id": r.item.id.0, "start": start, "end": end, "leading": leading}); - edit_item(h, r.item, "text.setRangeStyle", &p)?; + edit_text(h, r.item, "text.setRangeStyle", &p)?; } Ok(()) })?; @@ -1072,7 +1085,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { o.insert("start".into(), json!(ba)); o.insert("end".into(), json!(bb)); } - let answer = edit_item(h, r.item, "text.setRangeStyle", &p)?; + let answer = edit_text(h, r.item, "text.setRangeStyle", &p)?; if let Attr::TextFont = attr { let wants = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); font_applied(h, r.item, (ba, bb), (&wants("font"), &wants("style")), &answer)?; @@ -1234,7 +1247,7 @@ fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer { o.insert("start".into(), json!(ba)); o.insert("end".into(), json!(bb)); } - edit_item(h, r.item, id, &p)?; + edit_text(h, r.item, id, &p)?; Ok(Data::Undefined) } @@ -1250,7 +1263,7 @@ pub(super) fn doc_text_frames(link: &Link) -> HostMember { get(link, doc_text_frames_impl) } -/// The ids of the document's type objects in paint order, kept while the document is unchanged. +/// The ids of the document's type objects, topmost first, kept while the document is unchanged. fn frame_ids(h: &Host, st: &DocState) -> Rc> { if let Some((uid, doc, ids)) = &*h.dom.text.list.borrow() && *uid == st.uid diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 89e050d68f..473077d8e6 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -272,6 +272,25 @@ fn a_saved_preset_with_values_out_of_range_reads_in_range() { assert_eq!(boards(&s).iter().map(|r| r.x0).collect::>(), [0.0, 100.0, 200.0], "side by side, not overlapping"); } +/// A saved preset whose rows the preferences hold above the most `file.new` takes reads as that +/// most, so `file.new` takes the preset as `file.newPresets` lists it; no rows stay no rows. +#[test] +fn a_saved_preset_with_too_many_rows_reads_in_range() { + let mut s = Session::new(); + let prefs = json!({ + "newDocPresets": [ + {"name": "Tall", "width": 10, "height": 10, "artboards": 4, "layout": "gridByColumn", "rows": 1001}, + {"name": "Plain", "width": 10, "height": 10, "artboards": 4, "layout": "gridByColumn", "rows": 0}, + ], + }); + s.apply_prefs(serde_json::from_value(prefs).unwrap()); + let saved = presets(&mut s, "Saved"); + assert_eq!(saved[0]["artboardLayout"]["rows"], json!(1000), "{}", saved[0]); + assert_eq!(saved[1]["artboardLayout"].get("rows"), None, "{}", saved[1]); + s.execute("file.new", &saved[0]).unwrap(); + assert_eq!(boards(&s).len(), 4); +} + /// `file.new` and `artboard.new` take the same largest artboard side (the canvas less the largest /// bleed on both sides) and refuse a side just past it, or of 0 or less, with an error that names /// the limit in points and, when the document's units aren't points, in those units too. diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index edd359282e..06c4670e93 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1207,3 +1207,25 @@ fn assigning_guides_throws_in_both_directions_while_guides_are_locked() { log(&mut s, "var ps = app.activeDocument.pathItems; ps[0].guides = true; ps[1].guides = false;"); assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps), "a value the path has runs no command"); } + +/// A point change made before a call that fails and is put back, here a new document whose +/// profile cannot be read, is kept. +#[test] +fn a_point_change_before_a_failed_new_document_is_kept() { + let dir = std::env::temp_dir().join(format!("vc-script-points-new-doc-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap(); + let (mut s, a, _) = doc(); + s.attach_new_doc_profiles(dir.clone()); + let before = node(&s, a).path_data().unwrap().subpaths.clone(); + let out = log( + &mut s, + "app.activeDocument.pathItems[0].pathPoints[0].anchor = [5, 7];\ + try { app.documents.addDocument('Print'); } catch (e) { vc.log('refused'); }", + ); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(out, vec![json!("refused")]); + assert_eq!(s.documents().len(), 1); + assert_ne!(node(&s, a).path_data().unwrap().subpaths, before, "the point change is kept"); +} diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 7d70741e69..dcecba422f 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -56,13 +56,13 @@ fn text_frames_add_point_area_and_path_type() { let out = log( &mut s, "var d = app.activeDocument, p = d.pageItems;\ - var area = d.textFrames.areaText(p[0]); area.contents = 'Area';\ - var path = d.textFrames.pathText(p[1]); path.contents = 'Path';\ + var area = d.textFrames.areaText(p[1]); area.contents = 'Area';\ + var path = d.textFrames.pathText(p[0]); path.contents = 'Path';\ var pt = d.textFrames.add(); pt.contents = 'Point';\ var at = d.textFrames.pointText([30, 40]); at.contents = 'At';\ vc.log(d.textFrames.length); vc.log([area.kind, path.kind, pt.kind]);\ vc.log(pt.typename); vc.log(pt instanceof TextFrame && pt instanceof PageItem);\ - vc.log(d.textFrames[3].contents); vc.log(d.textFrames[9] === undefined);\ + vc.log(d.textFrames[0].contents); vc.log(d.textFrames[9] === undefined);\ vc.log(at.orientation); vc.log(d.textFrames.parent.typename);", ); assert_eq!(out[0], json!(4)); @@ -297,6 +297,49 @@ fn bad_text_paint_is_refused_without_a_change() { assert_eq!(paints(&s, id), runs); } +#[test] +fn hidden_or_locked_type_is_not_edited() { + let (mut s, id) = doc_with("abc"); + let (runs, text) = (paints(&s, id), plain(&s, id)); + for hide in ["t.locked = true;", "t.hidden = true;"] { + for edit in [ + "r.characters[1].fillColor = red;", + "r.size = 30;", + "r.contents = 'xyz';", + "r.characters.add('!');", + "r.justification = Justification.CENTER;", + ] { + let e = failure( + &mut s, + &format!("var t = app.activeDocument.textFrames[0], r = t.textRange, red = new RGBColor(); red.red = 255; {hide} {edit}"), + ); + assert!(e.contains("Cannot edit TextFrame"), "{hide} {edit}: {e}"); + } + } + assert_eq!((paints(&s, id), plain(&s, id)), (runs, text)); +} + +#[test] +fn text_added_after_a_range_ending_inside_a_character_goes_after_that_character() { + let (mut s, id) = doc_with("abc"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0]; t.contents = '\\uD83D\\uDE00X'; var r = t.textRange; r.length = 1;\ + var x = t.characters.add('!', r); vc.log([x.contents, r.contents]);", + ); + assert_eq!(plain(&s, id), "\u{1F600}!X"); + assert_eq!(out, vec![json!(["!", "\u{1F600}"])]); + // An empty range there sits after the character too, and styling it changes nothing. + let runs = paints(&s, id); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0]; var r = t.textRange; r.length = 1;\ + var e = t.characters.add('', r), red = new RGBColor(); red.red = 255; e.fillColor = red; vc.log(e.length);", + ); + assert_eq!(out, vec![json!(0)]); + assert_eq!(paints(&s, id), runs); +} + #[test] fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() { let (mut s, id) = doc_with("abc"); @@ -504,7 +547,7 @@ fn text_fonts_list_and_assign_fonts_by_name() { &format!( "var f = app.textFonts, m = '';\ try {{ f.getByName('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ - try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ + m = ''; try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[{pos}];\ vc.log([k.family, k.style]); r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\ vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);" @@ -564,16 +607,16 @@ fn collections_of_text_add_words_characters_and_paragraphs() { let (mut s, id) = doc_with("ab"); s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap(); let before = undo_steps(&s); - let out = log(&mut s, "var n = app.activeDocument.textFrames[1].words.add(''); vc.log([n.length, n.start]);"); + let out = log(&mut s, "var n = app.activeDocument.textFrames[0].words.add(''); vc.log([n.length, n.start]);"); assert_eq!(out, vec![json!([0, 5])]); for (call, want) in [ ("t.words.add(null)", "contents must be a string or a number"), ("t.words.add('x', t.words[0], 'after')", "insertionLocation must be"), ("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"), - ("t.words.add('x', app.activeDocument.textFrames[0])", "same text frame"), + ("t.words.add('x', app.activeDocument.textFrames[1])", "same text frame"), ("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"), ] { - let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[1]; {call};")); + let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {call};")); assert!(e.contains(want), "{call}: {e}"); } assert_eq!(undo_steps(&s), before); @@ -658,7 +701,7 @@ fn type_made_with_a_large_id_is_the_new_type() { fn text_members_refuse_objects_of_other_classes() { let (mut s, _) = doc_with("abc"); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[1]);"); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[0]);"); assert!(e.contains("this is not a TextFrame"), "{e}"); let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextRange.prototype, 'contents').get.call(app.activeDocument.textFrames[0]);"); assert!(e.contains("this is not a TextRange"), "{e}"); diff --git a/docs/mcp.md b/docs/mcp.md index a72b4cac53..793c599a3a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2838,7 +2838,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot 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 placed item's `file`, are not defined yet and read as `undefined`. - `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type - objects in paint order, those inside groups included, with `length`, `[i]`, `index(key)`, `getByName(name)` and + objects topmost first, as `pageItems` lists them, those inside groups included, with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation` From af7bf8bc69d021a531c89cdfefec77402ad12e89 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:36:32 -0800 Subject: [PATCH 03/22] Scripts: textFrames.removeAll() refuses type on a locked artboard - textFrames.removeAll() deleted a text frame on a locked artboard, although its editable property reads false. It now throws "cannot delete objects on a locked artboard" with the ids before anything is deleted, as pathItems.removeAll() and remove() do. - add(contents, relativeObject) with a text range of a removed frame threw a type error. It now throws "Stale text range"; only an argument of another class gets the type error. - The hidden or locked edit test starts each case from a fresh frame, and checks run sizes and justification after each refused edit. The add test also checks the text of the frame the script edits. --- crates/engine/src/script/dom/text.rs | 23 ++++++++++----- crates/engine/src/tests/script_text.rs | 41 +++++++++++++++++++++++--- 2 files changed, 53 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 4a25a8300f..0d993057ce 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -48,9 +48,9 @@ use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref}; use super::{ - Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, colors, command, doc_of, doc_ref, edit_item, editable, - float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, text, - typename_of, whole, with_doc, + Answer, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, boolean, class, colors, command, doc_of, doc_ref, + edit_item, editable, float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, + property, text, typename_of, whole, with_doc, }; use crate::{DocState, Document, NodeId, NodeKind}; @@ -744,8 +744,10 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { let rel = arg(a, 2); let target = if handle_of(rel, "TextFrame").is_some() { whole_span(h, item_of(h, rel)?)?.1 + } else if handle_of(rel, "TextRange").is_some() { + span_of(h, rel, &["TextRange"])? } else { - span_of(h, rel, &["TextRange"]).map_err(|_| HostError::Type("relativeObject must be a TextRange or a TextFrame".into()))? + return Err(HostError::Type("relativeObject must be a TextRange or a TextFrame".into())); }; if target.item.doc.uid != r.item.doc.uid || target.item.id != r.item.id { return Err(HostError::Error("relativeObject must be text of the same text frame".into())); @@ -1381,19 +1383,26 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { in_path(h, a, true, &[2, 3, 5, 6]) } -/// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first. +/// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a +/// locked artboard, stops it first. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let doc = frames_doc(h, a)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = frame_ids(h, st); let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); - (ids, refused) + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + (ids, refused, on_locked) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index dcecba422f..eef6b274e3 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -299,8 +299,10 @@ fn bad_text_paint_is_refused_without_a_change() { #[test] fn hidden_or_locked_type_is_not_edited() { - let (mut s, id) = doc_with("abc"); - let (runs, text) = (paints(&s, id), plain(&s, id)); + let state = |s: &Session, id: NodeId| match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (paints(s, id), plain(s, id), sizes(s, id), t.para_at(0).justify), + _ => panic!("not text"), + }; for hide in ["t.locked = true;", "t.hidden = true;"] { for edit in [ "r.characters[1].fillColor = red;", @@ -309,14 +311,17 @@ fn hidden_or_locked_type_is_not_edited() { "r.characters.add('!');", "r.justification = Justification.CENTER;", ] { + // Each case starts from a fresh frame, so the hidden cases test a frame that is only hidden. + let (mut s, id) = doc_with("abc"); + let before = state(&s, id); let e = failure( &mut s, &format!("var t = app.activeDocument.textFrames[0], r = t.textRange, red = new RGBColor(); red.red = 255; {hide} {edit}"), ); assert!(e.contains("Cannot edit TextFrame"), "{hide} {edit}: {e}"); + assert_eq!(state(&s, id), before, "{hide} {edit}"); } } - assert_eq!((paints(&s, id), plain(&s, id)), (runs, text)); } #[test] @@ -605,7 +610,7 @@ fn collections_of_text_add_words_characters_and_paragraphs() { } // Empty contents add nothing; bad arguments throw before anything changes. let (mut s, id) = doc_with("ab"); - s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap(); + let other = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap()["id"].as_u64().unwrap()); let before = undo_steps(&s); let out = log(&mut s, "var n = app.activeDocument.textFrames[0].words.add(''); vc.log([n.length, n.start]);"); assert_eq!(out, vec![json!([0, 5])]); @@ -620,7 +625,35 @@ fn collections_of_text_add_words_characters_and_paragraphs() { assert!(e.contains(want), "{call}: {e}"); } assert_eq!(undo_steps(&s), before); + assert_eq!(plain(&s, other), "other"); assert_eq!(plain(&s, id), "ab"); + // A range of a frame that was removed is stale, not of the wrong class. + let e = failure(&mut s, "var f = app.activeDocument.textFrames, b = f[0], a = f[1], r = b.textRange; b.remove(); a.characters.add('x', r);"); + assert!(e.contains("Stale text range"), "{e}"); + assert_eq!(plain(&s, id), "ab"); +} + +/// Type on a locked artboard stays: `removeAll()` throws and deletes nothing, as +/// `pathItems.removeAll()` does. +#[test] +fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { + let (mut s, id) = doc_with("ab"); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&id.0.to_string()), "{e}"); + assert_eq!(plain(&s, id), "ab"); + assert_eq!(undo_steps(&s), steps); + lock(&mut s, false); + log(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.textFrames.length);"), vec![json!(0)]); } #[test] From 2f786096a50b28bffd73acf07ff87e5a0c7ad583 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:54:54 -0800 Subject: [PATCH 04/22] Scripts: path and type edits refuse objects on a locked artboard - A point edit (anchor, leftDirection, rightDirection, setEntirePath) and a paint, stroke or transform change of a path on a locked artboard changed it, although its editable property reads false. They now throw "Cannot edit PathItem : it is on a locked artboard" with nothing changed. - A text edit, createOutline() or a point/area conversion of type on a locked artboard, and areaText() or pathText() given a hidden or locked path, now throw "Cannot edit" with nothing changed. - A point assigned more than 4,000,000 pt from the origin was queued without a check and written by a later call. It now throws a range error when it is assigned, and the path keeps its points. --- crates/engine/src/script/dom/paths.rs | 46 ++++++++++++++----- crates/engine/src/script/dom/text.rs | 23 ++++++++-- crates/engine/src/tests/script_dom_paths.rs | 49 +++++++++++++++++++++ crates/engine/src/tests/script_text.rs | 27 ++++++++++++ docs/mcp.md | 11 +++-- 5 files changed, 138 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index ea57a3f49b..bb3759d62e 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -15,7 +15,9 @@ //! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside //! groups and compound paths included. //! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden -//! or locked layer or group, throws `Cannot edit` with nothing changed. +//! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing +//! changed. A point assigned more than `MAX_COORD` from the origin throws a range error when it +//! is assigned. //! - A path in a compound path or compound shape reads that owner's paint, which the paint //! commands change in its place, and a gradient that `filled = true` gives it is placed on that //! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and @@ -106,6 +108,27 @@ fn cannot_edit(id: NodeId) -> HostError { HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0)) } +/// The `Cannot edit` error for the path `id` of `st` when it, or a layer or group it is in, is +/// hidden or locked, or it is on a locked artboard. +fn protected(h: &super::Host, st: &DocState, id: NodeId) -> Option { + if !editable(&st.doc, id) { + Some(cannot_edit(id)) + } else if super::on_locked_artboard(h, st, id) { + Some(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0))) + } else { + None + } +} + +/// `p`, a point the script assigned, which must be within [`crate::MAX_COORD`] of the origin. +fn in_canvas(p: Point, what: &str) -> std::result::Result { + if p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD { + Ok(p) + } else { + Err(HostError::Range(format!("{what} is outside the canvas"))) + } +} + /// The path `d` names, which must still be in its document. fn path_of(h: &super::Host, d: &Data) -> std::result::Result { let item = item_of(h, d)?; @@ -179,7 +202,7 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) /// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with /// the path's other point changes until [`flush`] writes them. The first change of a path writes /// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or -/// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object +/// locked or is on a locked artboard, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object /// that is, is written at once, so that its points read as the grid snaps them. fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() @@ -190,14 +213,15 @@ fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) flush(h)?; let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; let r = f(&mut subs); - let (same, ok, aligned) = read_path(h, item, |st, _, pd| { + let (same, refused, aligned) = read_path(h, item, |st, _, pd| { let d = &st.doc; let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned))); - (pd.subpaths == subs, editable(d, item.id), aligned) + let same = pd.subpaths == subs; + (same, if same { None } else { protected(h, st, item.id) }, aligned) })?; if !same { - if !ok { - return Err(cannot_edit(item.id)); + if let Some(e) = refused { + return Err(e); } *h.dom.pending.borrow_mut() = Some((item, subs)); if aligned { @@ -253,9 +277,8 @@ fn drawing_normally(h: &super::Host, f: impl FnOnce() -> T) -> T { /// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put /// back afterwards, so the edit changes only the path. fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result { - let ok = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)); - if !ok { - return Err(cannot_edit(item.id)); + if let Some(e) = with_doc(h, item.doc, |_, st| protected(h, st, item.id)) { + return Err(e); } if let Some(o) = params.as_object_mut() { o.entry("ids").or_insert_with(|| json!([item.id.0])); @@ -676,7 +699,8 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer { let f = with_doc(h, item.doc, |_, st| frame(st))?; let closed = read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))?; let c = h.dom.coords.get(); - let anchors: Vec = script.iter().map(|p| Anchor::corner(f.to_document(c, *p))).collect(); + let anchors: Vec = + script.iter().map(|p| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::>()?; let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; write_path(h, item, subs)?; cut_points(h, item); @@ -1351,7 +1375,7 @@ fn assigned_point(h: &super::Host, a: &[Data], what: &str) -> std::result::Resul let p = point(arg(a, 1), what)?; let (item, _) = this_point(h, a)?; let fr = with_doc(h, item.doc, |_, st| frame(st))?; - Ok(fr.to_document(h.dom.coords.get(), p)) + in_canvas(fr.to_document(h.dom.coords.get(), p), what) } fn pt_anchor(h: &super::Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 0d993057ce..b051fcbb43 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -302,14 +302,26 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u } /// Runs command `id` with `params` on the text frame of `item`. Throws `Cannot edit`, with nothing -/// changed, when the frame or a layer or group it is in is hidden or locked. +/// changed, when the frame or a layer or group it is in is hidden or locked, or the frame is on a +/// locked artboard. fn edit_text(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { - if !with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)) { - return Err(HostError::Error(format!("Cannot edit TextFrame {}: it, or a layer or group it is in, is hidden or locked", item.id.0))); - } + refuse_protected(h, item, "TextFrame")?; edit_item(h, item, id, params) } +/// Throws `Cannot edit` for the `class` object of `item` when it or a layer or group it is in is +/// hidden or locked, or it is on a locked artboard. +fn refuse_protected(h: &Host, item: Item, class: &str) -> std::result::Result<(), HostError> { + let (ok, on_locked) = with_doc(h, item.doc, |_, st| (editable(&st.doc, item.id), super::on_locked_artboard(h, st, item.id))); + if !ok { + return Err(HostError::Error(format!("Cannot edit {class} {}: it, or a layer or group it is in, is hidden or locked", item.id.0))); + } + if on_locked { + return Err(HostError::Error(format!("Cannot edit {class} {}: it is on a locked artboard", item.id.0))); + } + Ok(()) +} + /// Records an edit the model made to the frame: `removed` units at `at` replaced by `inserted`. /// When the text is not what that edit gives, every earlier range goes stale. fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> { @@ -548,6 +560,7 @@ fn new_ref(h: &Host, doc: Doc, id: Option) -> Answer { /// `null` when the type has nothing to outline and the command removed it. fn frame_outline(h: &Host, a: &[Data]) -> Answer { let item = this_frame(h, a)?; + refuse_protected(h, item, "TextFrame")?; let (_, r) = on_doc(h, item.doc.uid, true, |h| { command(h, "select.set", &json!({"ids": [item.id.0]}))?; super::command_value(h, "type.createOutlines", &json!({})) @@ -569,6 +582,7 @@ fn convert(h: &Host, a: &[Data], to_area: bool) -> Answer { Some(false) => return Err(HostError::Error(format!("the text frame is not {} type", if to_area { "point" } else { "area" }))), Some(true) => {} } + refuse_protected(h, item, "TextFrame")?; let id = if to_area { "type.convertToAreaType" } else { "type.convertToPointType" }; let (_, r) = on_doc(h, item.doc.uid, true, |h| super::command_value(h, id, &json!({"ids": [item.id.0]})))?; new_ref(h, item.doc, result_id(&r).or(Some(item.id))) @@ -1365,6 +1379,7 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) { return Err(HostError::Error("TextFrames: threading and path positions are not available yet".into())); } + refuse_protected(h, path, "PathItem")?; let orientation = if on_path { 4 } else { 2 }; let vertical = vertical_of(arg(a, orientation))?; let mode = if on_path { "onPath" } else { "area" }; diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 06c4670e93..591f0f1b05 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -854,6 +854,55 @@ fn locked_paths_and_wrong_objects_are_refused() { assert!(e.contains("not a PathPoint"), "{e}"); } +/// A point edit of a path on a locked artboard throws `Cannot edit` and changes nothing. +#[test] +fn point_edits_of_a_path_on_a_locked_artboard_are_refused() { + let (mut s, _, _) = doc(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let before = art(&s); + let steps = undo_steps(&s); + for source in [ + "app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 1];", + "app.activeDocument.pathItems[0].pathPoints[0].leftDirection = [1, 1];", + "app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1, 1]]);", + ] { + let e = failure(&mut s, source); + assert!(e.contains("Cannot edit PathItem") && e.contains("locked artboard"), "{source}: {e}"); + } + assert_eq!(art(&s), before); + assert_eq!(undo_steps(&s), steps); +} + +/// A point placed beyond the canvas throws when it is assigned, and the path keeps its points, so a +/// later member call does not lose an assignment that returned. +#[test] +fn a_point_beyond_the_canvas_throws_when_it_is_assigned() { + let (mut s, a, _) = doc(); + let before = node(&s, a).path_data().unwrap().subpaths.clone(); + let far = crate::MAX_COORD * 1.5; + for source in [ + format!("app.activeDocument.pathItems[0].pathPoints[0].anchor = [{far}, 0];"), + format!("app.activeDocument.pathItems[0].pathPoints[0].rightDirection = [0, {far}];"), + format!("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [{far}, 1]]);"), + ] { + let e = failure(&mut s, &source); + assert!(e.contains("outside the canvas"), "{source}: {e}"); + } + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0], q = p.pathPoints[1];\ + q.anchor = [45, 285];\ + try {{ p.pathPoints[0].anchor = [{far}, 0]; }} catch (e) {{ vc.log('threw'); }}\ + vc.log(q.anchor); vc.log(p.closed);" + ), + ); + assert_eq!(out, vec![json!("threw"), json!([45, 285]), json!(true)]); + let after = node(&s, a).path_data().unwrap().subpaths.clone(); + assert_eq!(after[0].anchors[0], before[0].anchors[0], "the point assigned beyond the canvas stays"); + assert_ne!(after[0].anchors[1], before[0].anchors[1], "the earlier assignment is written"); +} + #[test] fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index eef6b274e3..62e4d28a92 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -633,6 +633,33 @@ fn collections_of_text_add_words_characters_and_paragraphs() { assert_eq!(plain(&s, id), "ab"); } +/// Type on a locked artboard, and a hidden or locked path given to `areaText` or `pathText`, are +/// not changed. +#[test] +fn protected_type_and_paths_are_not_converted_or_edited() { + let (mut s, id) = doc_with("abc"); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + for edit in ["t.contents = 'xyz';", "t.textRange.size = 30;", "t.createOutline();", "t.convertPointObjectToAreaObject();"] { + let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {edit}")); + assert!(e.contains("Cannot edit TextFrame") && e.contains("locked artboard"), "{edit}: {e}"); + } + assert_eq!(plain(&s, id), "abc"); + assert_eq!(undo_steps(&s), steps); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 200}, {"x": 300, "y": 220}], "closed": false})).unwrap(); + for (hide, call) in [("p.locked = true;", "areaText(p)"), ("p.hidden = true;", "pathText(p)")] { + let e = failure(&mut s, &format!("var d = app.activeDocument, p = d.pathItems[0]; {hide} d.textFrames.{call};")); + assert!(e.contains("Cannot edit PathItem"), "{call}: {e}"); + assert_eq!(log(&mut s, "var d = app.activeDocument; vc.log([d.pathItems.length, d.textFrames.length]);"), vec![json!([1, 0])]); + } +} + /// Type on a locked artboard stays: `removeAll()` throws and deletes nothing, as /// `pathItems.removeAll()` does. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 7edcb0be3e..726081df2c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2901,7 +2901,10 @@ other files through `$`: with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation` value; a `startTValue`, `endTValue`, `baseFrame` or `postFix` that is given throws an error that says it is not - available yet. A `TextFrame` + available yet. `removeAll()` throws and deletes nothing when any type object is hidden or locked, is in a hidden or + locked layer or group, or is on a locked artboard (`cannot delete objects on a locked artboard`). A text edit, + `createOutline()` or a conversion of such a type object, and `areaText` or `pathText` given such a path, throw + `Cannot edit` with nothing changed. A `TextFrame` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`, `AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`, `createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to @@ -3033,8 +3036,10 @@ other files through `$`: `resize(100, 100)`, checks its arguments and runs no command, on a path with no points too. The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and `changeStrokePattern` given as different values throw an error, and `changeFillGradients` false and `ellipse` with `inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path - that is hidden or locked, or that is in a hidden or locked layer or group, throws `Cannot edit` with nothing - changed. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or + that is hidden or locked, that is in a hidden or locked layer or group, or that is on a locked artboard, throws + `Cannot edit` with nothing changed. A point given to `setEntirePath` or assigned to `anchor`, `leftDirection` or + `rightDirection` more than 4,000,000 pt from the origin throws a range error when it is given, and the path keeps + its points. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new art, the active Fill or Stroke proxy and Recent Colors as they were. `transform`, `polarity`, the gradient stops and the document's default paint are not available yet. From f1cb106d0293397c9f9a53bc39cc3e9eed289473 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 06:08:29 -0800 Subject: [PATCH 05/22] Docs: point limits name the x or y coordinate A script point is refused when its x or y is past MAX_COORD, not when its distance from the origin is. The module comment, the helper doc comment and docs/mcp.md now say so. --- crates/engine/src/script/dom/paths.rs | 6 +++--- docs/mcp.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index bb3759d62e..a9f36c1b4d 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -16,8 +16,8 @@ //! groups and compound paths included. //! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden //! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing -//! changed. A point assigned more than `MAX_COORD` from the origin throws a range error when it -//! is assigned. +//! changed. A point assigned whose x or y is more than `MAX_COORD` from the origin throws a +//! range error when it is assigned. //! - A path in a compound path or compound shape reads that owner's paint, which the paint //! commands change in its place, and a gradient that `filled = true` gives it is placed on that //! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and @@ -120,7 +120,7 @@ fn protected(h: &super::Host, st: &DocState, id: NodeId) -> Option { } } -/// `p`, a point the script assigned, which must be within [`crate::MAX_COORD`] of the origin. +/// `p`, a point the script assigned, whose x and y must each be within [`crate::MAX_COORD`] of the origin. fn in_canvas(p: Point, what: &str) -> std::result::Result { if p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD { Ok(p) diff --git a/docs/mcp.md b/docs/mcp.md index 726081df2c..dbb5934740 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3038,7 +3038,7 @@ other files through `$`: `inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path that is hidden or locked, that is in a hidden or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing changed. A point given to `setEntirePath` or assigned to `anchor`, `leftDirection` or - `rightDirection` more than 4,000,000 pt from the origin throws a range error when it is given, and the path keeps + `rightDirection` whose x or y is more than 4,000,000 pt from the origin throws a range error when it is given, and the path keeps its points. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new art, the active Fill or Stroke proxy and Recent Colors as they were. `transform`, `polarity`, the gradient stops and From bb80534f3ea8b90512ff98f07e15442e778d9e93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 21:37:42 -0800 Subject: [PATCH 06/22] Scripts: path edits honor locked guides, keep selections and stay atomic PathItem handles carry the document's revert count, as main's page item handles now do, so points and new paths resolve again. resize() scales and changes the stroke weight in one step; paint writes that the command skips throw; Lock Guides refuses edits and removeAll on guide paths; removing a point remaps the selected anchors and segments; new paths go on the active layer while a group is isolated; translate's reflected parameters include changePositions; point tracking revisits only the paths an edit changed. StoryRange lists its fillColor, strokeColor and strokeWeight rows. --- crates/engine/src/script/dom/paths.rs | 177 +++++++++++++---- crates/engine/src/tests/script_dom_paths.rs | 184 ++++++++++++++++++ crates/engine/src/tests/script_text.rs | 4 +- .../tests/it/script_host_vs_scriptcheck.rs | 4 +- 4 files changed, 323 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 1f308db41e..808567d3b6 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -115,6 +115,8 @@ fn protected(h: &super::Host, st: &DocState, id: NodeId) -> Option { Some(cannot_edit(id)) } else if super::on_locked_artboard(h, st, id) { Some(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0))) + } else if h.session.borrow().menu.guides_locked && st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })) { + Some(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0))) } else { None } @@ -158,9 +160,10 @@ fn read_path(h: &super::Host, item: Item, f: impl FnOnce(&DocState, &crate::d }) } +/// A `PathItem` handle for `item`, in the form `item_of` reads (with the document's revert count). fn path_ref(h: &super::Host, item: Item) -> Data { - let [high, low] = id_parts(item.id); - host_ref("PathItem", &[float(h.run), float(item.doc.uid), high, low]) + let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)); + host_ref("PathItem", &handle) } /// How many points a path with the subpaths `subs` has. @@ -264,9 +267,15 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) /// Runs `f` with the drawing mode set to normal, so that the paths it makes go on top of the active /// layer, then puts the drawing mode back. -fn drawing_normally(h: &super::Host, f: impl FnOnce() -> T) -> T { +fn drawing_normally(h: &super::Host, parent: Option, f: impl FnOnce() -> T) -> T { let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal); + let isolation = h.session.borrow_mut().active_mut().map(|st| (st.uid, std::mem::replace(&mut st.isolation, parent))); let r = f(); + if let Some((uid, isolation)) = isolation + && let Some(st) = h.session.borrow_mut().document_mut(uid) + { + st.isolation = isolation; + } h.session.borrow_mut().draw_mode = kept; r } @@ -283,7 +292,13 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r if let Some(o) = params.as_object_mut() { o.entry("ids").or_insert_with(|| json!([item.id.0])); } - keeping_paint(h, || edit_item(h, item, id, ¶ms)) + let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?; + if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") + && matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == "objects" && *v == Data::Number(0.0))) + { + return Err(HostError::Error(format!("Cannot edit PathItem {}: {id} did not change the path", item.id.0))); + } + Ok(result) } /// Runs `f`, then puts back the paint for new art, the active Fill or Stroke proxy, the last color @@ -378,11 +393,16 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = path_items(h, st); + if h.session.borrow().menu.guides_locked + && let Some(id) = ids.iter().find(|id| st.doc.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. }))) + { + return Err(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0))); + } let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); let locks = st.doc.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - (ids, refused, on_locked) - }); + Ok((ids, refused, on_locked)) + })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}"))); @@ -407,7 +427,8 @@ fn made_id(r: &(Data, Value)) -> std::result::Result { /// and reverses the new path's direction when `reversed`. → the new path. fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { let made = on_doc(h, doc.uid, true, |h| { - let id = made_id(&drawing_normally(h, || super::command_value(h, id, params))?)?; + let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); + let id = made_id(&drawing_normally(h, parent, || super::command_value(h, id, params))?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -566,7 +587,8 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; - let id = made_id(&drawing_normally(h, || super::command_value(h, "path.create", &json!({"d": ""})))?)?; + let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); + let id = made_id(&drawing_normally(h, parent, || super::command_value(h, "path.create", &json!({"d": ""})))?)?; if unpainted { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } @@ -1137,19 +1159,22 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { if new_width.is_some_and(|w| w > MAX_STROKE_WIDTH) { return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); } - if (sx != 100.0 || sy != 100.0) - && let (Some(r), _) = item_rect(h, item, false)? - { - let origin = about(h, item, place, r)?; - params["origin"] = json!([origin.x, origin.y]); - edit_path(h, item, "object.scale", params)?; - } - if let Some(w) = new_width - && (w - width).abs() > 1e-9 - { - edit_path(h, item, "stroke.set", json!({"weight": w}))?; - } - Ok(Data::Undefined) + // The scale and the stroke weight change together, or neither does. + super::atomically(h, |h| { + if (sx != 100.0 || sy != 100.0) + && let (Some(r), _) = item_rect(h, item, false)? + { + let origin = about(h, item, place, r)?; + params["origin"] = json!([origin.x, origin.y]); + edit_path(h, item, "object.scale", params)?; + } + if let Some(w) = new_width + && (w - width).abs() > 1e-9 + { + edit_path(h, item, "stroke.set", json!({"weight": w}))?; + } + Ok(Data::Undefined) + }) } // ---- PathPoints ---- @@ -1216,7 +1241,10 @@ fn node_arc(d: &crate::Document, id: NodeId) -> Option<&Arc> { fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { let node = { let s = h.session.borrow(); - s.documents().iter().find(|d| d.uid == key.0).and_then(|st| node_arc(&st.doc, NodeId(key.1)).cloned()) + s.documents().iter().find(|d| d.uid == key.0).and_then(|st| { + h.dom.point_docs.borrow_mut().entry(key.0).or_insert_with(|| st.doc.clone()); + node_arc(&st.doc, NodeId(key.1)).cloned() + }) }; // A path that is gone makes its points stale, so that an undo that brings it back leaves them // stale. @@ -1242,31 +1270,39 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { /// at is skipped, as are its paths. pub(super) fn see_all_points(h: &super::Host) { let keys: Vec<(u64, u64)> = { - let seen = h.dom.point_nodes.borrow(); - if seen.is_empty() { - return; - } let s = h.session.borrow(); let mut docs = h.dom.point_docs.borrow_mut(); - // The documents that changed since the last look, kept as they are now. - let mut changed = std::collections::HashSet::new(); - for (uid, _) in seen.keys() { - if changed.contains(uid) { - continue; + let seen = h.dom.point_nodes.borrow(); + let mut keys = Vec::new(); + docs.retain(|uid, before| { + let after = s.documents().iter().find(|d| d.uid == *uid).map(|st| &st.doc); + if after.is_some_and(|after| Arc::ptr_eq(before, after)) { + return true; } - match s.documents().iter().find(|d| d.uid == *uid) { - Some(st) if docs.get(uid).is_some_and(|d| Arc::ptr_eq(d, &st.doc)) => {} - Some(st) => { - docs.insert(*uid, st.doc.clone()); - changed.insert(*uid); + let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) { + Some(item) => node_arc(before, item.id).into_iter().collect(), + None => before.layers.iter().collect(), + }; + while let Some(node) = todo.pop() { + if after.and_then(|d| node_arc(d, node.id)).is_some_and(|n| Arc::ptr_eq(node, n)) { + continue; } - None => { - docs.remove(uid); - changed.insert(*uid); + let key = (*uid, node.id.0); + if seen.contains_key(&key) { + keys.push(key); + } + if let Some(children) = node.children() { + todo.extend(children); } } - } - seen.keys().copied().filter(|(uid, _)| changed.contains(uid)).collect() + if let Some(after) = after { + *before = after.clone(); + true + } else { + false + } + }); + keys }; let editing = h.dom.editing.get(); for (uid, id) in keys { @@ -1549,16 +1585,71 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { /// `remove()`: deletes the point; a subpath left with no points goes too. fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { let (item, i) = this_point(h, a)?; - edit_points(h, item, |subs| { + let mut selection = with_doc(h, item.doc, |_, st| st.selection.clone()); + // The endpoints of the path's selected segments, before the point goes. + let old_ends: std::collections::BTreeSet<(usize, usize)> = match selection.segments.get(&item.id) { + Some(segments) => read_points(h, item, |subs| { + segments + .iter() + .filter_map(|&(sub, at)| subs.get(sub).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(sub, at), (sub, (at + 1) % sp.anchors.len())])) + .flatten() + .collect() + })?, + None => std::collections::BTreeSet::new(), + }; + let removed = edit_points(h, item, |subs| { if let Some((s, j)) = locate(subs, i) && let Some(sp) = subs.get_mut(s) { + let (n, closed) = (sp.anchors.len(), sp.closed); sp.anchors.remove(j); if sp.anchors.is_empty() { subs.remove(s); } + Some((s, j, n, closed)) + } else { + None } })?; + if let Some((s, j, n, closed)) = removed { + let remap = |(sub, at): (usize, usize)| { + if sub == s && (n == 1 || at == j) { None } else { Some((sub - usize::from(sub > s && n == 1), at - usize::from(sub == s && at > j))) } + }; + // Anchors held only as a selected segment's endpoints come back from the kept segments below. + if let Some(anchors) = selection.anchors.get_mut(&item.id) { + *anchors = anchors.iter().copied().filter(|a| !old_ends.contains(a)).filter_map(remap).collect(); + } + if let Some(segments) = selection.segments.get_mut(&item.id) { + *segments = segments + .iter() + .copied() + .filter(|&(sub, at)| sub != s || (at != j && (j == 0 || at != j - 1) && (!closed || j != 0 || at != n - 1))) + .filter_map(remap) + .collect(); + let ends: Vec<_> = read_points(h, item, |subs| { + segments + .iter() + .filter_map(|&(sub, at)| { + subs.get(sub).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(sub, at), (sub, (at + 1) % sp.anchors.len())]) + }) + .flatten() + .collect() + })?; + // Directly selected anchors stay selected; the kept segments' endpoints are added. + selection.anchors.entry(item.id).or_default().extend(ends); + } + if let Some((id, at)) = selection.key_anchor + && id == item.id + { + selection.key_anchor = remap(at).map(|at| (id, at)); + } + if selection.contains(item.id) && (selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || read_points(h, item, point_count)? == 0) { + selection.remove(item.id); + } + if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) { + st.selection = selection; + } + } cut_points(h, item); Ok(Data::Undefined) } @@ -1570,7 +1661,7 @@ pub(super) fn path_item_members(l: &Link) -> Vec { let changes = [("changePositions", "boolean"), ("changeFillPatterns", "boolean"), ("changeFillGradients", "boolean"), ("changeStrokePattern", "boolean")]; let mut translate = vec![("deltaX", "number"), ("deltaY", "number")]; - translate.extend(changes.iter().skip(1)); + translate.extend(changes); let mut rotate = vec![("angle", "number")]; rotate.extend(changes); rotate.push(("rotateAbout", "Transformation")); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 591f0f1b05..b4da0d6850 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -299,6 +299,190 @@ fn path_point_wrapper_goes_stale_after_remove() { ); } +#[test] +fn removing_a_point_remaps_selection_and_clears_deleted_geometry() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.pathPoints[1].selected = PathPointSelection.ANCHORPOINT;\ + var anchor = p.pathPoints[1].anchor; p.pathPoints[0].remove();\ + vc.log(p.selectedPathPoints.length); vc.log(p.selectedPathPoints[0].anchor.join() == anchor.join());\ + vc.log(p.pathPoints[0].selected);", + ); + assert_eq!(out, vec![json!(1), json!(true), json!("PathPointSelection.ANCHORPOINT")]); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 0)])); + assert!(s.active().unwrap().selection.contains(b)); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert!(!s.active().unwrap().selection.contains(a)); + assert!(s.active().unwrap().selection.contains(b)); + + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "set"})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert!(!s.active().unwrap().selection.contains(a)); + assert!(!s.active().unwrap().selection.segments.contains_key(&a)); + + let (mut s, a, _) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 2]], "mode": "set"})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert_eq!(s.active().unwrap().selection.segments.get(&a).unwrap().iter().copied().collect::>(), vec![(0, 1)]); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); +} + +#[test] +fn removing_a_subpaths_last_point_remaps_other_subpaths_and_the_key_anchor() { + let (mut s, a, _) = doc(); + s.execute( + "path.setAnchors", + &json!({"id": a.0, "subpaths": [ + {"anchors": [{"x": 0, "y": 0}]}, + {"anchors": [{"x": 10, "y": 10}, {"x": 20, "y": 20}, {"x": 30, "y": 30}]} + ]}), + ) + .unwrap(); + s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 0], [1, 1], [1, 2]]}], "mode": "set"})).unwrap(); + s.execute("select.key", &json!({"id": a.0, "anchor": [1, 2]})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); + assert_eq!(s.active().unwrap().selection.key_anchor, Some((a, (0, 2)))); +} + +#[test] +fn locked_guides_refuse_path_edits_and_bulk_removal() { + let (mut s, a, _) = doc(); + log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + s.set_guides_locked(true); + let (before, steps) = (art(&s), undo_steps(&s)); + for edit in [ + "p.pathPoints[0].anchor = [0, 0]", + "p.pathPoints[0].remove()", + "p.pathPoints.removeAll()", + "p.setEntirePath([[0, 0], [1, 1]])", + "p.closed = false", + "p.translate(1, 0)", + "p.filled = false", + "p.strokeWidth = 12", + "app.activeDocument.pathItems.removeAll()", + ] { + let out = + log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; try {{ {edit}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}")); + assert_eq!(out.first(), Some(&json!("Error")), "{edit}: {out:?}"); + assert!(out[1].as_str().unwrap().contains("guides are locked"), "{edit}: {out:?}"); + assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{edit}"); + } + assert!(is_guide(&s, a)); + s.set_guides_locked(false); + log(&mut s, "app.activeDocument.pathItems[0].translate(1, 0);"); + assert_ne!(art(&s), before); +} + +#[test] +fn document_path_creators_use_the_active_layer_during_isolation() { + for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] { + let (mut s, a, b) = doc(); + let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.isolate", &json!({"id": group.0})).unwrap(); + let layer = s.active().unwrap().active_layer.unwrap(); + let before = node(&s, group); + let selection = s.active().unwrap().selection.clone(); + let steps = undo_steps(&s); + log(&mut s, &format!("app.activeDocument.pathItems.{create};")); + let st = s.active().unwrap(); + let made = st.doc.node(layer).unwrap().children().unwrap().last().unwrap(); + assert!(matches!(made.kind, NodeKind::Path { .. }), "{create}"); + assert_eq!(st.doc.parent_of(made.id), Some(layer), "{create}"); + assert_eq!(node(&s, group), before, "{create}"); + assert_eq!(st.isolation, Some(group), "{create}"); + assert_eq!(st.selection, selection, "{create}"); + assert_eq!(undo_steps(&s), steps + 1, "{create}"); + } +} + +#[test] +fn paint_writes_refuse_generated_graph_design_paths() { + for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] { + for unpainted in [false, true] { + let (mut s, a, _) = doc(); + if unpainted { + s.execute("paint.setFill", &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a.0], "none": true})).unwrap(); + } + s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap(); + let graph = NodeId( + s.execute( + "graph.create", + &json!({ + "type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4" + }), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap(); + let graph_node = node(&s, graph); + let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); + let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap(); + let mut paths = Vec::new(); + design.walk(&mut |n| { + if matches!(n.kind, NodeKind::Path { .. }) { + paths.push(n.id); + } + }); + let path = paths[0]; + s.execute("object.setProps", &json!({"ids": [path.0], "name": "generated"})).unwrap(); + let (before, steps) = (art(&s), undo_steps(&s)); + for edit in [ + "p.fillColor = c", + "p.strokeColor = c", + "p.filled = !p.filled", + "p.stroked = !p.stroked", + "p.strokeWidth = 12", + "p.strokeCap = StrokeCap.ROUNDENDCAP", + "p.strokeJoin = StrokeJoin.BEVELENDJOIN", + "p.strokeMiterLimit = 22", + "p.strokeDashes = [3, 4]", + ] { + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems.getByName('generated'), c = new RGBColor(); c.red = 123;\ + try {{ {edit}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}" + ), + ); + assert_eq!(out.first(), Some(&json!("Error")), "{kind} {unpainted} {edit}: {out:?}"); + assert!(out[1].as_str().unwrap().contains("did not change the path"), "{kind} {edit}: {out:?}"); + assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{kind} {edit}"); + } + } + } +} + +#[test] +fn editing_many_observed_paths_keeps_own_handles_and_invalidates_external_changes() { + let (mut s, a, b) = doc(); + for i in 0..100 { + rect(&mut s, f64::from(i), 10.0, 2.0, 2.0); + } + let out = log( + &mut s, + &format!( + "var ps = app.activeDocument.pathItems, paths = [], points = [], expected = [];\ + for (var i = 0; i < ps.length; i++) {{ paths.push(ps[i]); points.push(ps[i].pathPoints[0]); }}\ + for (var i = 0; i < paths.length; i++) {{ paths[i].translate(2, 0); expected.push(points[i].anchor.join()); }}\ + var valid = true; for (var i = 0; i < points.length; i++) valid = valid && points[i].anchor.join() == expected[i]; vc.log(valid);\ + vc.run('object.move', {{ids: [{a}], dx: 1, dy: 0}});\ + try {{ points[100].anchor; }} catch (e) {{ vc.log(e.message); }}\ + paths[0].translate(1, 0); vc.log(points[101].anchor.join() == expected[101]);\ + vc.run('object.move', {{ids: [{b}], dx: 1, dy: 0}}); vc.run('edit.undo');\ + try {{ points[101].anchor; }} catch (e) {{ vc.log(e.message); }}", + a = a.0, + b = b.0 + ), + ); + assert_eq!(out, vec![json!(true), json!("Stale path point"), json!(true), json!("Stale path point")]); +} + #[test] fn points_read_before_a_removal_or_replacement_go_stale() { let (mut s, _, _) = doc(); diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 0decf96eaf..29b676a377 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -360,7 +360,9 @@ fn text_added_after_a_range_ending_inside_a_character_goes_after_that_character( var x = t.characters.add('!', r); vc.log([x.contents, r.contents]);", ); assert_eq!(plain(&s, id), "\u{1F600}!X"); - assert_eq!(out, vec![json!(["!", "\u{1F600}"])]); + // Setting `length` to 1 moves the end out to the end of the emoji, and text added at a range's + // end joins the range. + assert_eq!(out, vec![json!(["!", "\u{1F600}!"])]); // An empty range there sits after the character too, and styling it changes nothing. let runs = paints(&s, id); let out = log( diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 1b74138da6..2a8b017f06 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -251,12 +251,12 @@ const INSIDE: &[(&str, &str)] = &[ "StoryRange.prototype.", "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes \ characterAttributes= characterOffset characterOffset= characterStyles characterStyles= characters constructor \ - contents contents= deSelect deSelect= duplicate duplicate= end end= getLocalCharOverridesJSON \ + contents contents= deSelect deSelect= duplicate duplicate= end end= fillColor fillColor= getLocalCharOverridesJSON \ getLocalCharOverridesJSON= getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength \ getTextRunLength= horizontalScale horizontalScale= insertionPoints insertionPoints= kerning kerning= leading leading= \ length length= lines lines= move move= paragraphAttributes paragraphAttributes= paragraphStyles paragraphStyles= \ paragraphs parent remove rotation rotation= select select= size size= start start= story strikeThrough \ - strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \ + strikeThrough= strokeColor strokeColor= strokeWeight strokeWeight= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \ underline underline= verticalScale verticalScale= words", ), ("StoryCharacters.", "prototype"), From e9010cd36384e0b643b1fd3e6ca230dac9e85636 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 22:03:07 -0800 Subject: [PATCH 07/22] Scripts: point handles go stale after a revert; flush keeps only live selections PathPoints and PathPoint handles carry the document's revert count. Writing point edits drops selected anchors and segments that no longer exist, in the same step as the edit. Overprint writes that the command skips throw, and changeFillGradients true with changePositions false throws until it is available. --- crates/engine/src/script/dom/paths.rs | 65 +++++++---- crates/engine/src/tests/script_dom_paths.rs | 113 ++++++++++++++++++++ 2 files changed, 159 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 808567d3b6..0a5aeacf31 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -54,7 +54,8 @@ //! are locked; assigning the value the path has runs no command. //! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and //! `changeStrokePattern` given as different values throw an error; gradients move with the art, -//! so `changeFillGradients` false throws an error that says it is not available yet. +//! so `changeFillGradients` false throws an error that says it is not available yet, as does +//! `changeFillGradients` true with `changePositions` false. use std::rc::Rc; use std::sync::Arc; @@ -70,8 +71,8 @@ use vectorcraft_tools::params::gradient_params; use super::{ Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, - edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, - on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, typename_of, whole, with_doc, + edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, item_rect, later, method, named, num, number, on_doc, pair, + point, point_get, point_method, point_property, property, returns, this_doc, typed, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -142,9 +143,12 @@ fn this_path(h: &super::Host, a: &[Data]) -> std::result::Result std::result::Result { +/// The path of the run `run`, document `uid`, id parts `high` and `low` and revert count `reverts`, as a handle gives them. +fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64, reverts: f64) -> std::result::Result { let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if with_doc(h, doc, |_, st| Some(st.reverts) != whole(reverts)) { + return Err(HostError::Error(STALE_ITEM.into())); + } let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; path_of(h, &path_ref(h, Item { doc, id })) } @@ -255,7 +259,27 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { } let subpaths: Vec = subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::>(), "closed": sp.closed})).collect(); - edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?; + super::atomically(h, |h| { + if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) { + let selection = &mut st.selection; + if let Some(anchors) = selection.anchors.get_mut(&item.id) { + anchors.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.anchors.len())); + } + if let Some(segments) = selection.segments.get_mut(&item.id) { + segments.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.segment_count())); + if segments.is_empty() { + selection.segments.remove(&item.id); + } + } + if selection.key_anchor.is_some_and(|(id, (s, i))| id == item.id && !subs.get(s).is_some_and(|sp| i < sp.anchors.len())) { + selection.key_anchor = None; + } + if selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || point_count(&subs) == 0 { + selection.remove(item.id); + } + } + edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths})) + })?; Ok(()) } @@ -293,8 +317,9 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r o.entry("ids").or_insert_with(|| json!([item.id.0])); } let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?; - if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") - && matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == "objects" && *v == Data::Number(0.0))) + let count = if id == "object.setOverprint" { "changed" } else { "objects" }; + if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set" | "object.setOverprint") + && matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == count && *v == Data::Number(0.0))) { return Err(HostError::Error(format!("Cannot edit PathItem {}: {id} did not change the path", item.id.0))); } @@ -603,8 +628,8 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { fn path_points(h: &super::Host, a: &[Data]) -> Answer { let item = this_path(h, a)?; - let [high, low] = id_parts(item.id); - Ok(host_ref("PathPoints", &[float(h.run), float(item.doc.uid), high, low])) + let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)); + Ok(host_ref("PathPoints", &handle)) } fn path_closed(h: &super::Host, a: &[Data]) -> Answer { @@ -1091,6 +1116,9 @@ fn transform_options(a: &[Data], i: usize, params: &mut Value) -> std::result::R if flags[2] == Some(false) { return Err(HostError::Error(format!("{} false is not available yet: gradients move with the art", names[2]))); } + if flags[0] == Some(false) && flags[2] == Some(true) { + return Err(HostError::Error(format!("{} true with {} false is not available yet", names[2], names[0]))); + } if let (Some(f), Some(s)) = (flags[1], flags[3]) && f != s { @@ -1181,8 +1209,8 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result { let Some(handle) = handle_of(arg(a, 0), "PathPoints") else { return Err(HostError::Type("this is not a PathPoints".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) }; - path_at(h, *run, *uid, *high, *low) + let [run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) }; + path_at(h, *run, *uid, *high, *low, *reverts) } fn points_length(h: &super::Host, a: &[Data]) -> Answer { @@ -1196,8 +1224,9 @@ fn points_parent(h: &super::Host, a: &[Data]) -> Answer { } fn point_ref(h: &super::Host, item: Item, i: usize) -> Data { - let [high, low] = id_parts(item.id); - host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), float(point_cuts(h, item))]) + let mut handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)).to_vec(); + handle.extend([float(i as u64), float(point_cuts(h, item))]); + host_ref("PathPoint", &handle) } /// How many times the points read of `item` have gone stale, after [`see_points`] notes a change @@ -1368,8 +1397,8 @@ fn points_remove_all(h: &super::Host, a: &[Data]) -> Answer { /// point of the path removed or replaced since `this` was read. pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize), HostError> { let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) }; - let [run, uid, high, low, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; - let item = path_at(h, *run, *uid, *high, *low)?; + let [run, uid, high, low, reverts, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; + let item = path_at(h, *run, *uid, *high, *low, *reverts)?; if whole(*cuts) != Some(point_cuts(h, item)) { return Err(HostError::Error(STALE_POINT.into())); } @@ -1576,9 +1605,7 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { out })?; h.charge_call(picked.len() as u64)?; - let [high, low] = id_parts(item.id); - let cuts = float(point_cuts(h, item)); - let points = picked.into_iter().map(|i| host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), cuts])).collect(); + let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect(); Ok(Data::Array(points)) } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index b4da0d6850..b08ed50e9a 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -329,6 +329,56 @@ fn removing_a_point_remaps_selection_and_clears_deleted_geometry() { assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); } +#[test] +fn opening_a_path_drops_deleted_segments_and_keeps_valid_selection() { + for flush in ["", "try { p.name; vc.log('flushed'); } catch (e) { vc.log(e.message); }"] { + for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] { + let (mut s, a, b) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + let anchors = selected_anchors(&s, a); + let steps = undo_steps(&s); + let out = log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; p.closed = false; {flush}")); + assert_eq!(out, if flush.is_empty() { vec![] } else { vec![json!("flushed")] }); + assert!(!node(&s, a).path_data().unwrap().subpaths[0].closed); + let selection = &s.active().unwrap().selection; + assert!(selection.contains(b)); + assert_eq!(selected_anchors(&s, a), anchors); + let kept: Vec<_> = selection.segments.get(&a).into_iter().flatten().copied().collect(); + assert_eq!(kept, if segments.as_array().unwrap().len() == 1 { vec![] } else { vec![(0, 1)] }); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(node(&s, a).path_data().unwrap().subpaths[0].closed); + } + } +} + +#[test] +fn path_point_handles_are_stale_after_revert_even_when_geometry_is_unchanged() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-path-points-revert"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for operation in ["pp.length", "pp.parent", "pp[0].anchor = [1, 2]", "pp.add()", "q.anchor", "q.anchor = [1, 2]", "picked.anchor = [1, 2]"] { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let before = node(&s, a); + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0], pp = p.pathPoints, q = pp[0], picked = p.selectedPathPoints[0];\ + p.name = 'changed'; vc.run('file.revert');\ + try {{ {operation}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}\ + var fresh = app.activeDocument.pathItems[0]; vc.log(fresh.pathPoints.length);\ + fresh.pathPoints[0].anchor = [11, 279]; vc.log(fresh.pathPoints[0].anchor);" + ), + ); + assert_eq!(out, vec![json!("Stale page item"), json!(4), json!([11, 279])], "{operation}"); + assert_ne!(node(&s, a).path_data(), before.path_data()); + s.execute("file.revert", &json!({})).unwrap(); + } +} + #[test] fn removing_a_subpaths_last_point_remaps_other_subpaths_and_the_key_anchor() { let (mut s, a, _) = doc(); @@ -458,6 +508,46 @@ fn paint_writes_refuse_generated_graph_design_paths() { } } +#[test] +fn overprint_writes_refuse_generated_graph_design_paths() { + for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] { + let (mut s, a, _) = doc(); + s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a.0], "color": "#000000"})).unwrap(); + s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap(); + let graph = NodeId( + s.execute("graph.create", &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4"})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap(); + let graph_node = node(&s, graph); + let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); + let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap(); + let mut paths = Vec::new(); + design.walk(&mut |n| { + if matches!(n.kind, NodeKind::Path { .. }) { + paths.push(n.id); + } + }); + s.execute("object.setProps", &json!({"ids": [paths[0].0], "name": "generated"})).unwrap(); + let before = (art(&s), undo_steps(&s)); + for property in ["fillOverprint", "strokeOverprint"] { + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems.getByName('generated'), before = p.{property};\ + try {{ p.{property} = !before; }} catch (e) {{ vc.log(e.message); }} vc.log(p.{property} == before);" + ), + ); + assert!(out[0].as_str().unwrap().contains("object.setOverprint did not change the path"), "{kind} {property}: {out:?}"); + assert_eq!(out.get(1), Some(&json!(true)), "{kind} {property}"); + assert_eq!((art(&s), undo_steps(&s)), before, "{kind} {property}"); + } + } +} + #[test] fn editing_many_observed_paths_keeps_own_handles_and_invalidates_external_changes() { let (mut s, a, b) = doc(); @@ -1087,6 +1177,29 @@ fn a_point_beyond_the_canvas_throws_when_it_is_assigned() { assert_ne!(after[0].anchors[1], before[0].anchors[1], "the earlier assignment is written"); } +#[test] +fn transforms_refuse_moving_gradients_without_the_path() { + for transform in + ["translate(5, 10, false, false, true, false)", "rotate(30, false, false, true, false)", "resize(150, 125, false, false, true, false)"] + { + let (mut s, a, b) = doc(); + s.execute( + "paint.setFill", + &json!({"ids": [a.0], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}), + ) + .unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let before = (art(&s), s.active().unwrap().selection.clone(), undo_steps(&s)); + let out = log(&mut s, &format!("try {{ app.activeDocument.pathItems[0].{transform}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}")); + assert_eq!(out.first(), Some(&json!("Error")), "{transform}: {out:?}"); + assert!( + out[1].as_str().unwrap().contains("changeFillGradients true with changePositions false is not available yet"), + "{transform}: {out:?}" + ); + assert_eq!((art(&s), s.active().unwrap().selection.clone(), undo_steps(&s)), before, "{transform}"); + } +} + #[test] fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() { let mut s = Session::new(); From 743e38ebf6549eeff373721e337f4dca3ecfb027 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 00:08:13 -0800 Subject: [PATCH 08/22] Scripts: path creation and paint edits replay as run; mixed picks keep their anchors Scripted shapes record the layer they were drawn on, so replay does not draw them behind other art or inside an isolated group. Paint edits on objects keep the new-art defaults on replay, and a solid new-art color copied to a path keeps its color model. An anchor picked next to a selected segment stays selected and is listed by selectedPathPoints. closed set on an empty path applies to its first points. Text fillColor and strokeColor reflect as Color. Saved file.new steps keep the old row rounding. --- crates/engine/src/cmd.rs | 6 ++ crates/engine/src/cmd/create.rs | 29 +++++- crates/engine/src/cmd/newdoc.rs | 9 +- crates/engine/src/cmd/paint.rs | 18 +++- crates/engine/src/cmd/select.rs | 9 +- crates/engine/src/cmd/stroke.rs | 2 +- crates/engine/src/script/dom/paths.rs | 61 +++++------ crates/engine/src/script/dom/text.rs | 1 + crates/engine/src/tests/script_dom.rs | 16 +++ crates/engine/src/tests/script_dom_paths.rs | 108 ++++++++++++++++++++ crates/engine/src/tests/script_text.rs | 11 ++ docs/mcp.md | 24 +++-- 12 files changed, 245 insertions(+), 49 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 8a4e6ebe6f..4f8a211d51 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -441,6 +441,12 @@ pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&' /// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in /// ([`plugin::run_command`]), which needs the command's id. pub(crate) fn run_spec(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result { + if matches!(spec.id, "shape.rectangle" | "shape.ellipse" | "shape.polygon" | "shape.star" | "path.create") { + return create::on_layer(s, p, spec.id, |s| (spec.run)(s, p)); + } + if matches!(spec.id, "paint.setFill" | "paint.setStroke" | "stroke.set") { + return paint::object_only(s, p, spec.id, |s| (spec.run)(s, p)); + } if plugin::is_command_id(spec.id) { plugin::run_command(s, spec.id, p) } else { (spec.run)(s, p) } } diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 16ceda7d38..31b9950296 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -12,6 +12,25 @@ use super::{ }; use crate::EngineError; +pub(crate) fn on_layer(s: &mut Session, p: &Value, cmd: &str, run: impl FnOnce(&mut Session) -> Result) -> Result { + if p.get("onLayer").is_none() { + return run(s); + } + let parent = object_param(p, "onLayer", cmd)?; + let d = &s.doc()?.doc; + if let Some(id) = parent + && !d.node(id).is_some_and(|n| n.is_layer() && d.is_editable(id)) + { + return Err(bad(cmd, "onLayer must name an editable layer")); + } + let mode = std::mem::replace(&mut s.draw_mode, crate::DrawMode::Normal); + let isolation = std::mem::replace(&mut s.doc_mut()?.isolation, parent); + let result = run(s); + s.doc_mut()?.isolation = isolation; + s.draw_mode = mode; + result +} + pub fn specs() -> Vec { vec![ cmd!( @@ -19,7 +38,7 @@ pub fn specs() -> Vec { "Rectangle", [], None, - "{x, y, width, height, radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}", + "{x, y, width, height, onLayer?: layer id|null (draw normally on this layer), radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}", has_doc, rectangle ), @@ -28,7 +47,7 @@ pub fn specs() -> Vec { "Ellipse", [], None, - "{x, y, width, height, rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}", + "{x, y, width, height, onLayer?: layer id|null (draw normally on this layer), rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}", has_doc, ellipse ), @@ -37,7 +56,7 @@ pub fn specs() -> Vec { "Polygon", [], None, - "{cx, cy, radius, sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}", + "{cx, cy, radius, onLayer?: layer id|null (draw normally on this layer), sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}", has_doc, polygon ), @@ -46,7 +65,7 @@ pub fn specs() -> Vec { "Star", [], None, - "{cx, cy, radius1, radius2, points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", + "{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", has_doc, star ), @@ -137,7 +156,7 @@ pub fn specs() -> Vec { "Create Path", [], None, - "{anchors: [{x, y, in?: [x,y], out?: [x,y]}], closed?: bool, d?: SVG path data} → {id}", + "{anchors: [{x, y, in?: [x,y], out?: [x,y]}], onLayer?: layer id|null (draw normally on this layer), closed?: bool, d?: SVG path data} → {id}", has_doc, path_create ), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index db0495ac97..0416c5b406 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -870,7 +870,14 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { // A preset keeps its name in Recent unless its size changed (turning it doesn't count). let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units); let size = str_param(p, "preset").map(|_| sorted(&base)); - let mut settings = base.with_params(p, C)?; + let mut params = p.clone(); + if s.replaying() + && let Some(rows) = params.pointer_mut("/artboardLayout/rows") + && let Some(value) = rows.as_f64().filter(|r| r.is_finite() && *r >= 1.0) + { + *rows = json!(value.round().min(MAX_ARTBOARDS as f64) as u32); + } + let mut settings = base.with_params(¶ms, C)?; if size != Some(sorted(&settings)) { settings.name = "Custom".into(); } diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index c722e2a58b..726aada285 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed), or with an opacity alone how many took the opacity}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, objectOnly?: bool (requires ids or id; keeps new-art paint, the active proxy and remembered colors), defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed), or with an opacity alone how many took the opacity}", has_doc, |s, p| set_paint(s, p, true) ), @@ -948,6 +948,22 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) apply_paint_opacity(s, p, Some(paint), None, fill) } +pub(crate) fn object_only(s: &mut Session, p: &Value, cmd: &str, run: impl FnOnce(&mut Session) -> Result) -> Result { + if !switch_or(p, "objectOnly", false, cmd)? { + return run(s); + } + if (!names(p, "ids") && !names(p, "id")) || asks_defaults_only(p) { + return Err(bad(cmd, "objectOnly needs ids or id and cannot be combined with defaultsOnly")); + } + let kept = (s.paint.clone(), s.fill_active, s.last_solid, s.last_gradient.clone(), s.recent_colors.clone()); + let result = run(s); + (s.paint, s.fill_active, s.last_solid, s.last_gradient, s.recent_colors) = kept; + if result.is_ok() { + s.note_defaults_only(); + } + result +} + /// [`apply_paint`] with `paint` optional, which also sets the `opacity` (0..1) of the fill (or /// stroke) item each target takes it on, in the same undo step: the picked gradient mesh points' /// own opacity for a fill (with no paint or a solid color), nothing on a target without that item. diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 931504dedb..0e937376bd 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -1034,8 +1034,7 @@ fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BT } let mut members = Members::of(sel); for (id, refs) in items { - // A segment pick's endpoints aren't selected anchors: start from none of them. - let segment_pick = sel.segments.remove(&id).is_some(); + let endpoints = sel.segments.remove(&id).and_then(|segments| segment_endpoints(d, id, &segments, "select.anchorsMany").ok()); let all: BTreeSet = d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default(); // Anything but a path is selected, toggled or deselected as a whole. @@ -1049,8 +1048,10 @@ fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BT } // From the anchors selected now (all of them for a path selected as a whole). let now = match sel.partial(id) { - _ if segment_pick => BTreeSet::new(), - Some(a) => a.clone(), + Some(a) => match &endpoints { + Some(endpoints) => a.difference(endpoints).copied().collect(), + None => a.clone(), + }, None if members.contains(id) => all.clone(), None => BTreeSet::new(), }; diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index e1d64b2112..4ee4f01c10 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, objectOnly?: bool (requires ids or id; keeps new-art paint, the active proxy and remembered colors), defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 0a5aeacf31..8c8e758c7b 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -289,19 +289,11 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n) } -/// Runs `f` with the drawing mode set to normal, so that the paths it makes go on top of the active -/// layer, then puts the drawing mode back. -fn drawing_normally(h: &super::Host, parent: Option, f: impl FnOnce() -> T) -> T { - let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal); - let isolation = h.session.borrow_mut().active_mut().map(|st| (st.uid, std::mem::replace(&mut st.isolation, parent))); - let r = f(); - if let Some((uid, isolation)) = isolation - && let Some(st) = h.session.borrow_mut().document_mut(uid) - { - st.isolation = isolation; - } - h.session.borrow_mut().draw_mode = kept; - r +/// Runs a path creation command with its layer placement recorded. +fn drawing_normally(h: &super::Host, parent: Option, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> { + let mut params = params.clone(); + params["onLayer"] = json!(parent.map(|p| p.0)); + super::command_value(h, id, ¶ms) } /// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which @@ -315,6 +307,9 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r } if let Some(o) = params.as_object_mut() { o.entry("ids").or_insert_with(|| json!([item.id.0])); + if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") { + o.insert("objectOnly".into(), json!(true)); + } } let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?; let count = if id == "object.setOverprint" { "changed" } else { "objects" }; @@ -453,7 +448,7 @@ fn made_id(r: &(Data, Value)) -> std::result::Result { fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { let made = on_doc(h, doc.uid, true, |h| { let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); - let id = made_id(&drawing_normally(h, parent, || super::command_value(h, id, params))?)?; + let id = made_id(&drawing_normally(h, parent, id, params)?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -613,9 +608,9 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); - let id = made_id(&drawing_normally(h, parent, || super::command_value(h, "path.create", &json!({"d": ""})))?)?; + let id = made_id(&drawing_normally(h, parent, "path.create", &json!({"d": ""}))?)?; if unpainted { - keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; + command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0], "objectOnly": true}))?; } Ok(id) })?; @@ -640,7 +635,13 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer { fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { let closed = boolean(arg(a, 1), "closed")?; let item = this_path(h, a)?; - edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; + edit_points(h, item, |subs| { + if subs.is_empty() && closed { + subs.push(SubPath::new(Vec::new(), closed)); + } else { + subs.iter_mut().for_each(|sp| sp.closed = closed); + } + })?; Ok(Data::Undefined) } @@ -836,10 +837,10 @@ fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Resul Ok(match linked { true if *tint < 1.0 => json!({"swatch": name, "tint": f64::from(*tint) * 100.0}), true => json!({"swatch": name}), - false => json!({"color": colors::param(color)}), + false => json!({"color": colors::param(color), "keepModel": true}), }) } - Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color)})), + Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color), "keepModel": true})), Paint::Gradient(g) => { let mut g = g.clone(); if g.geom.is_some() || g.freeform.is_some() { @@ -1502,12 +1503,18 @@ fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[ if held { return true; } - if !sel.contains(id) || sel.segments.contains_key(&id) { + if !sel.contains(id) { return false; } match sel.partial(id) { None => true, - Some(picked) => locate(subs, i).is_some_and(|r| picked.contains(&r)), + Some(picked) => locate(subs, i).is_some_and(|(s, j)| { + picked.contains(&(s, j)) + && !sel + .segments + .get(&id) + .is_some_and(|segments| segments.iter().any(|&(sub, at)| sub == s && (at == j || (at + 1) % subs[s].anchors.len() == j))) + }), } } @@ -1592,17 +1599,11 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { let picked: Vec = read_path(h, item, |st, _, pd| { let sel = &st.selection; let held = held_selected(&st.doc, sel, item.id); - if !held && (!sel.contains(item.id) || sel.segments.contains_key(&item.id)) { + if !held && !sel.contains(item.id) { return Vec::new(); } - let mut out = Vec::new(); - let mut first = 0; - for (s, sp) in pd.subpaths.iter().enumerate() { - let n = sp.anchors.len(); - out.extend((0..n).filter(|j| held || sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j)); - first += n; - } - out + let total: usize = pd.subpaths.iter().map(|sp| sp.anchors.len()).sum(); + (0..total).filter(|&i| anchor_selected(sel, item.id, held, &pd.subpaths, i)).collect() })?; h.charge_call(picked.len() as u64)?; let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect(); diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index e96645da43..f5a8c840fe 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1617,6 +1617,7 @@ fn attr_type(attr: Attr) -> &'static str { match attr { Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean", Attr::TextFont => "TextFont", + Attr::FillColor | Attr::StrokeColor => "Color", _ => "number", } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4bebfb6ab9..7b44a3eb04 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1024,6 +1024,22 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { } } +#[test] +fn file_new_replays_legacy_fractional_and_large_rows() { + for (rows, rounded) in [(3.6, 4), (1001.2, 1000)] { + let params = json!({"width": 100, "height": 100, "artboards": 5, "artboardLayout": {"layout": "gridByColumn", "rows": rows}}); + let mut s = Session::new(); + assert!(s.execute("file.new", ¶ms).unwrap_err().to_string().contains("rows must be a whole number")); + s.replay("file.new", ¶ms).unwrap(); + let mut expected = Session::new(); + let mut params = params; + params["artboardLayout"]["rows"] = json!(rounded); + expected.execute("file.new", ¶ms).unwrap(); + let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|b| b.rect).collect::>(); + assert_eq!(boards(&s), boards(&expected)); + } +} + #[test] fn a_listed_preset_keeps_more_rows_than_artboards() { use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index b08ed50e9a..c1ec77f4e1 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -49,6 +49,114 @@ fn node(s: &Session, id: NodeId) -> crate::doc::Node { s.active().unwrap().doc.node(id).unwrap().clone() } +#[test] +fn path_creation_replays_on_top_of_the_active_layer() { + for mode in ["behind", "inside", "isolation"] { + for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] { + let setup = || { + let (mut s, a, b) = doc(); + if mode == "isolation" { + let group = s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].clone(); + s.execute("object.isolate", &json!({"id": group})).unwrap(); + } else { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.drawMode", &json!({"mode": mode})).unwrap(); + } + s + }; + let mut s = setup(); + let start = s.journal.len(); + log(&mut s, &format!("app.activeDocument.pathItems.{create};")); + let mut replay = setup(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s), "{mode}: {create}"); + assert_eq!(replay.draw_mode, s.draw_mode); + assert_eq!(replay.active().unwrap().isolation, s.active().unwrap().isolation); + } + } +} + +#[test] +fn path_paint_edits_replay_without_changing_new_art() { + let (mut s, a, _) = doc(); + let start = s.journal.len(); + log( + &mut s, + "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; c.green = 10; c.blue = 30;\ + p.fillColor = c; p.strokeColor = c; p.strokeWidth = 7;\ + app.activeDocument.pathItems.rectangle(100, 200, 20, 30);", + ); + let (mut replay, _, _) = doc(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(node(&replay, a).appearance, node(&s, a).appearance); + assert_eq!(art(&replay), art(&s)); + assert_eq!(replay.paint, s.paint); + assert_eq!(replay.fill_active, s.fill_active); + assert_eq!(replay.recent_colors, s.recent_colors); +} + +#[test] +fn mixed_anchor_and_segment_picks_keep_independent_anchors() { + for selected in ["ANCHORPOINT", "NOSELECTION"] { + let (mut s, a, _) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 3]]})).unwrap(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0]; vc.log(p.pathPoints[0].selected);\ + vc.log(p.pathPoints[1].selected); vc.log(p.selectedPathPoints.length);\ + p.pathPoints[{}].selected = PathPointSelection.{selected}; vc.log(p.selectedPathPoints.length);", + if selected == "ANCHORPOINT" { 1 } else { 3 } + ), + ); + assert_eq!(out[..3], [json!("PathPointSelection.ANCHORPOINT"), json!("PathPointSelection.NOSELECTION"), json!(2)]); + assert_eq!(out[3], json!(if selected == "ANCHORPOINT" { 3 } else { 1 })); + assert!(!s.active().unwrap().selection.segments.contains_key(&a)); + assert_eq!(selected_anchors(&s, a), Some(if selected == "ANCHORPOINT" { vec![(0, 0), (0, 1), (0, 3)] } else { vec![(0, 0)] })); + } +} + +#[test] +fn an_empty_path_keeps_closed_before_points_are_added() { + for add in ["p.pathPoints.add(); p.pathPoints.add();", "p.setEntirePath([[0, 0], [10, 0], [10, 10]]);"] { + let (mut s, _, _) = doc(); + let start = s.journal.len(); + let out = log( + &mut s, + &format!("var p = app.activeDocument.pathItems.add(); p.closed = true; vc.log(p.closed); vc.run('select.none'); {add} vc.log(p.closed);"), + ); + assert_eq!(out, [json!(true), json!(true)]); + let (mut replay, _, _) = doc(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s)); + } +} + +#[test] +fn enabling_path_paint_preserves_the_new_art_color_model() { + for fill in [true, false] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; + s.execute(cmd, &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute(cmd, &json!({"color": "#12ab34", "keepModel": true})).unwrap(); + let new_art = s.new_art(); + let want = if fill { new_art.fill_paint() } else { new_art.stroke_paint() }; + log(&mut s, if fill { "app.activeDocument.pathItems[0].filled = true;" } else { "app.activeDocument.pathItems[0].stroked = true;" }); + let n = node(&s, a); + assert_eq!(if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() }, want); + } +} + /// Each number of `v` rounded to 3 decimals, in place. fn rounded(v: &Value) -> Value { match v { diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 29b676a377..a18184d7ce 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -46,6 +46,17 @@ fn sizes(s: &Session, id: NodeId) -> Vec<(String, f64)> { } } +#[test] +fn character_color_attributes_reflect_as_color() { + let (mut s, _) = doc_with("color"); + let out = log( + &mut s, + "var a = app.activeDocument.textFrames[0].textRange.characterAttributes;\ + vc.log(a.reflect.find('fillColor').dataType); vc.log(a.reflect.find('strokeColor').dataType);", + ); + assert_eq!(out, [json!("Color"), json!("Color")]); +} + #[test] fn text_frames_add_point_area_and_path_type() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index 6070ae384a..1ff018d34e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3124,7 +3124,8 @@ through `$`: `verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough`, `textFont`, `fillColor` and `strokeColor` (color objects, as a path takes them; a `NoColor` takes the paint away) and `strokeWeight` (0 to 1000 pt) (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/), set with - `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are + `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Reflection reports + `fillColor` and `strokeColor` as `Color`. Paragraph attributes are `justification` (a `Justification` value, set with `text.setStyle`; the Auto alignment new type has reads as `LEFT`, or `RIGHT` in a right-to-left paragraph, and setting a value replaces it), `firstLineIndent`, `leftIndent`, `rightIndent`, `spaceBefore` and `spaceAfter` (-1296 to 1296 pt, set with `text.setFormat`). `app.textFonts` @@ -3175,7 +3176,9 @@ through `$`: radius = 50, innerRadius = 20, points = 5, reversed?)`, which run `shape.rectangle`, `path.create`, `shape.ellipse`, `shape.polygon` and `shape.star` (and `path.reverse` for `reversed`) and paint the new path as new art is painted. `add()` and the shape creators put the new path on top of the active layer whatever the drawing - mode, which stays as it was. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item + mode, which stays as it was. These creation commands take `onLayer: layerId` to draw normally on that layer and + record this placement for replay. A null `onLayer` draws normally on the active layer. + A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`, `guides`, `clipping`, `selectedPathPoints`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to @@ -3183,8 +3186,11 @@ through `$`: (counterclockwise for a positive angle) and `resize(scaleX, scaleY, ..., changeLineWidths?, scaleAbout?)`. The geometry changes through `path.setAnchors`, the fill and stroke through `paint.setFill` and `paint.setStroke`, the stroke options through `stroke.set`, the fill rule through `path.setFillRule`, overprint through - `object.setOverprint` and the transforms through `object.move`, `object.rotate` and `object.scale`. Changes to the - points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one + `object.setOverprint` and the transforms through `object.move`, `object.rotate` and `object.scale`. + Script path paint and stroke edits pass `objectOnly: true` with explicit `ids` to keep new-art paint, the active proxy + and remembered colors during execution and replay. `paint.setFill`, `paint.setStroke` and `stroke.set` accept + this option with `ids` or `id`; it cannot be combined with `defaultsOnly: true`. + Changes to the points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one `path.setAnchors` before the script uses any other member or command, or the points of another path, and when the script ends; a path aligned to the pixel grid, or in an object that is, is written at each change, so its points read as the grid snaps them. @@ -3204,7 +3210,8 @@ through `$`: the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues` and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`. VectorCraft's own rules: a point's index counts across the path's subpaths; `closed` is true when every subpath is - closed, and assigning it opens or closes them all; `setEntirePath` takes at most 100,000 points and gives corner + closed, and assigning it opens or closes them all. An empty path keeps an assigned closure state for its first + subpath. `setEntirePath` takes at most 100,000 points and gives corner points with no handles, keeping the path closed when it was; moving `anchor` leaves its handles where they are, and `pointType` changes only the type; `PathPoints.add()` adds a corner point at the last point, or at `[0, 0]`; a point whose index is past the end of its path throws `Stale path point`, and so does a point read before the script removed @@ -3212,7 +3219,8 @@ through `$`: than the object model changed the path's points (a command run with `vc.run`, such as `path.setAnchors`, `object.move` or `edit.undo`); points stay valid through the object model's other changes to the path or to an object that holds it, such as `translate()`. Every point of a path selected as a whole is a selected anchor point, - and the endpoints of selected segments are not; a path in a selected group or compound path is selected as a whole. + and the endpoints of selected segments are not. Independently selected anchors remain selected alongside segment + picks. A path in a selected group or compound path is selected as a whole. Direction handles are not selected on their own, so assigning `LEFTDIRECTION`, `RIGHTDIRECTION` or `LEFTRIGHTPOINT` to `selected` throws an error that says it is not available yet, and so does assigning `NOSELECTION` to a point of a path in a selected group or compound path. Selecting a point of a path with selected segments replaces that path's @@ -3228,7 +3236,7 @@ through `$`: was. Reading `fillColor` or `strokeColor` gives a new object each time, a `GradientColor`, `SpotColor` or `PatternColor` among them (a color linked to a global or spot swatch reads as a `SpotColor` with its `tint`); assigning one of those throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new art gets (a color, gradient or pattern), or black when new art has none, and `stroked = true` does the same with the - stroke; a new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint + stroke. A copied solid new-art color keeps its color model. A new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint it shows, and a new-art pattern with a placement of its own, or one missing from the document, throws an error. `fillOverprint` and `strokeOverprint` read and change the top fill or stroke only. Sizes and radii are finite and not negative, `sides` is a whole number from 3 to 1000, `points` one from 2 to 1000, @@ -10492,6 +10500,8 @@ the rows give the current number of artboards, and New Document drops the rows w `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's value outside that range is read as the nearer end), `previewMode` and `alignNewObjectsToPixelGrid` (see [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)). +Replaying a saved `file.new` command rounds legacy fractional row counts and caps them at 1000. New calls still +require whole row counts from 1 to 1000. `file.newPresets {category?}` lists the categories and presets (Recent: the last sizes used; Saved: the user's presets, kept in the preferences by `file.newPresets.save` and removed by `file.newPresets.delete`). A listed preset can be passed straight back to `file.new`. Print presets and sizes without `units` start in `unitsGeneral`; screen presets From c822678ed7dc5695ab2d02106f1dd20a5314672d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 00:37:09 -0800 Subject: [PATCH 09/22] Scripts: point removal journals its selection, and point reads flush closures Removing a point records the shifted anchor selection as select commands, so replay moves the same points. Reading a point's selection writes waiting closure changes first when they drop a selected segment. selectedPathPoints walks the subpaths once. pathItems[name] looks up a numeric name that is not an index, as pageItems does. --- crates/engine/src/script/dom/paths.rs | 98 +++++++++++++++++++-- crates/engine/src/tests/script_dom_paths.rs | 61 +++++++++++++ 2 files changed, 150 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 8c8e758c7b..a828db6b00 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -178,6 +178,8 @@ fn point_count(subs: &[SubPath]) -> usize { /// The subpath and the place in it of point `i`, among the subpaths `subs`. fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> { for (s, sp) in subs.iter().enumerate() { + #[cfg(test)] + tests::LOCATE_STEPS.with(|steps| steps.set(steps.get() + 1)); if i < sp.anchors.len() { return Some((s, i)); } @@ -380,17 +382,26 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer { }; } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; - let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; + let Some(i) = super::position(*n) else { + return match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) { + Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), + r => r, + }; + }; Ok(with_doc(h, doc, |_, st| path_items(h, st).get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) } fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + items_named(h, doc, name) +} + +fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer { with_doc(h, doc, |_, st| { let ids = path_items(h, st); h.charge_call(ids.len() as u64)?; - let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name)); id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) }) } @@ -398,6 +409,7 @@ fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { fn items_index(h: &super::Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => items_by_name(h, a), + Data::Number(n) if super::position(*n).is_none() => Err(HostError::Error(NOT_FOUND.into())), Data::Number(_) => match items_at(h, a)? { Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), d => Ok(d), @@ -1526,12 +1538,19 @@ fn same_layout(a: &[SubPath], b: &[SubPath]) -> bool { /// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point /// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. The point changes waiting in -/// [`super::State`] are written first only when they add or remove points of this path, since -/// the selection names anchors by their place in the document's path. +/// [`super::State`] are written first when they add or remove points of this path or invalidate +/// selected segments. fn pt_selected(h: &super::Host, a: &[Data]) -> Answer { let (item, i) = this_point(h, a)?; let moved = match &*h.dom.pending.borrow() { - Some((waiting, subs)) if same_path(*waiting, item) => !read_path(h, item, |_, _, pd| same_layout(subs, &pd.subpaths))?, + Some((waiting, subs)) if same_path(*waiting, item) => read_path(h, item, |st, _, pd| { + !same_layout(subs, &pd.subpaths) + || st + .selection + .segments + .get(&item.id) + .is_some_and(|segments| segments.iter().any(|&(s, i)| !subs.get(s).is_some_and(|sp| i < sp.segment_count()))) + })?, _ => false, }; if moved { @@ -1602,8 +1621,25 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { if !held && !sel.contains(item.id) { return Vec::new(); } - let total: usize = pd.subpaths.iter().map(|sp| sp.anchors.len()).sum(); - (0..total).filter(|&i| anchor_selected(sel, item.id, held, &pd.subpaths, i)).collect() + let segments = sel.segments.get(&item.id); + let ends: std::collections::BTreeSet<_> = segments + .into_iter() + .flatten() + .filter_map(|&(s, i)| pd.subpaths.get(s).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(s, i), (s, (i + 1) % sp.anchors.len())])) + .flatten() + .collect(); + let partial = sel.partial(item.id).filter(|_| !held); + let mut picked = Vec::new(); + let mut offset = 0; + for (s, sp) in pd.subpaths.iter().enumerate() { + for j in 0..sp.anchors.len() { + if partial.is_none_or(|a| a.contains(&(s, j)) && !ends.contains(&(s, j))) { + picked.push(offset + j); + } + } + offset += sp.anchors.len(); + } + picked })?; h.charge_call(picked.len() as u64)?; let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect(); @@ -1674,8 +1710,22 @@ fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { if selection.contains(item.id) && (selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || read_points(h, item, point_count)? == 0) { selection.remove(item.id); } - if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) { - st.selection = selection; + super::flush(h)?; + let (doc, changed, layer, rows) = + with_doc(h, item.doc, |_, st| (st.doc.clone(), st.selection != selection, st.active_layer, st.highlighted_rows())); + if changed { + on_doc(h, item.doc.uid, false, |h| { + super::restore_selection(h, &doc, &selection)?; + if let Some(anchors) = selection.anchors.get(&item.id) + && with_doc(h, item.doc, |_, st| st.selection.anchors.get(&item.id) != Some(anchors)) + { + command(h, "select.anchors", &json!({"id": item.id.0, "anchors": anchors, "mode": "add"}))?; + if let Some(segments) = selection.segments.get(&item.id).filter(|s| !s.is_empty()) { + command(h, "select.segments", &json!({"id": item.id.0, "segments": segments, "mode": "add"}))?; + } + } + super::restore_layer(h, item.doc.uid, layer, &rows) + })?; } } cut_points(h, item); @@ -1836,3 +1886,33 @@ pub(super) fn classes(l: &Link) -> Vec { ), ] } + +#[cfg(test)] +mod tests { + use std::cell::Cell; + + use serde_json::json; + + use crate::Session; + + thread_local! { + pub(super) static LOCATE_STEPS: Cell = const { Cell::new(0) }; + } + + #[test] + fn selected_points_do_not_rescan_subpaths() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + let subpaths = vec![json!({"anchors": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 10}, {"x": 0, "y": 10}], "closed": true}); 128]; + s.execute("path.setAnchors", &json!({"id": id, "subpaths": subpaths})).unwrap(); + s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 3], [127, 3]]})).unwrap(); + s.execute("select.segments", &json!({"id": id, "segments": [[0, 0], [127, 1]], "mode": "add"})).unwrap(); + LOCATE_STEPS.with(|steps| steps.set(0)); + let out = s + .execute("script.run", &json!({"source": "vc.log(app.activeDocument.pathItems[0].selectedPathPoints.length);", "name": "t.js"})) + .unwrap(); + assert_eq!(out["log"], json!([2])); + LOCATE_STEPS.with(|steps| assert!(steps.get() <= 512, "subpath visits: {}", steps.get())); + } +} diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index c1ec77f4e1..501d027f3b 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -221,6 +221,23 @@ fn path_items_read_with_a_name_give_the_named_path() { assert_eq!(out, vec![json!([true, "n", true, false, true]), json!(["Not found"])]); } +#[test] +fn path_items_read_non_index_numbers_as_names() { + for name in ["-1", "1.5", "4294967295"] { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": name})).unwrap(); + let out = log( + &mut s, + &format!( + "var d = app.activeDocument; vc.log(d.pathItems['{name}'].name);\ + vc.log(d.pathItems[{name}].name == d.pageItems[{name}].name);\ + vc.log(d.pathItems[-2] === undefined); vc.log(d.pathItems[1].name == '{name}');" + ), + ); + assert_eq!(out, vec![json!(name), json!(true), json!(true), json!(false)]); + } +} + /// Paths on a locked artboard stay, a path in a group included: `removeAll()` throws and deletes /// nothing, as `pageItems.removeAll()` and `remove()` do. #[test] @@ -437,6 +454,50 @@ fn removing_a_point_remaps_selection_and_clears_deleted_geometry() { assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); } +#[test] +fn removing_a_point_replays_selection_before_moving_anchors() { + for segments in [false, true] { + let setup = || { + let (mut s, a, _) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1], [0, 3]]})).unwrap(); + if segments { + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 2]], "mode": "add"})).unwrap(); + } else { + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap(); + } + s + }; + let mut s = setup(); + let start = s.journal.len(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + let a = s.active().unwrap().selection.objects[0]; + assert_eq!(selected_anchors(&s, a), Some(if segments { vec![(0, 0), (0, 1), (0, 2)] } else { vec![(0, 0), (0, 2)] })); + s.execute("path.moveAnchors", &json!({"dx": 7, "dy": 3})).unwrap(); + let mut replay = setup(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s), "segments: {segments}"); + assert_eq!(replay.active().unwrap().selection, s.active().unwrap().selection, "segments: {segments}"); + } +} + +#[test] +fn point_selection_reads_flush_removed_closing_segments() { + for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] { + let (mut s, a, _) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], first = p.pathPoints[0], last = p.pathPoints[3];\ + p.closed = false; vc.log(first.selected); vc.log(last.selected); p.name;\ + vc.log(first.selected); vc.log(last.selected); vc.log(p.pathPoints[1].selected);", + ); + assert_eq!(out[..4], vec![json!("PathPointSelection.ANCHORPOINT"); 4]); + assert_eq!(out[4], json!("PathPointSelection.NOSELECTION")); + } +} + #[test] fn opening_a_path_drops_deleted_segments_and_keeps_valid_selection() { for flush in ["", "try { p.name; vc.log('flushed'); } catch (e) { vc.log(e.message); }"] { From b893fce7016226b4cc3994775d8193a8193d7e64 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 23:08:04 -0800 Subject: [PATCH 10/22] Scripts: emptying a path keeps an unrelated selection, and point removal keeps the layer Writing a path's points removes it from the selection only when it, its anchors or its segments are selected, so emptying an unselected path keeps a targeted layer. Removing a point that changes the selection puts back the current layer and the highlighted Layers rows. The New Document test reads fractional rows as rounded, as file.new does. --- crates/engine/src/script/dom/paths.rs | 4 +++- crates/engine/src/tests/script_dom_paths.rs | 10 ++++++++++ crates/ui-egui/src/dialogs/new_document.rs | 4 +--- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index a37ed8b71b..7785dc25a8 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -357,7 +357,9 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { if selection.key_anchor.is_some_and(|(id, (s, i))| id == item.id && !subs.get(s).is_some_and(|sp| i < sp.anchors.len())) { selection.key_anchor = None; } - if selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || subs.iter().all(|sp| sp.anchors.is_empty()) { + if (selection.contains(item.id) || selection.anchors.contains_key(&item.id) || selection.segments.contains_key(&item.id)) + && (selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || subs.iter().all(|sp| sp.anchors.is_empty())) + { selection.remove(item.id); } } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 9efa282707..93f2aaadf9 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -518,6 +518,16 @@ fn removing_the_last_selected_point_of_a_path_keeps_the_current_layer() { assert_eq!(st.highlighted_rows(), rows); } +#[test] +fn emptying_an_unselected_path_keeps_the_targeted_layer() { + let (mut s, a, _) = doc(); + let layer = NodeId(s.execute("layer.new", &json!({"name": "Empty"})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + assert!(!s.active().unwrap().selection.contains(a)); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints.removeAll();"); + assert_eq!(s.active().unwrap().selection.target, Some(layer)); +} + #[test] fn point_selection_reads_flush_removed_closing_segments() { for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] { diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 8f18b7fb46..c20582141e 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -1293,9 +1293,7 @@ mod tests { let mut app = app(); open(&mut app); set(&app, "artboards", json!(5)).unwrap(); - // Rows that are not a whole number are refused, as `file.new` refuses them. - assert!(set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).is_err()); - set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4, "spacing": 10})).unwrap(); + set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).unwrap(); assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4)); create(&mut app); let st = app.session.active().unwrap(); From 39a0fd69236dc6ee77b91666d4ef4c819539e676 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 12:01:00 -0800 Subject: [PATCH 11/22] Scripts: objectOnly paint, empty closed paths and style applyTo keep their rules - An objectOnly paint during an open interaction also restores the paint waiting for the commit, so it no longer reaches Recent Colors. - setEntirePath([]) on a closed path keeps an empty closed subpath, so the path stays closed. - A character or paragraph style's applyTo throws Cannot edit, with nothing changed, on a hidden or locked text frame or one on a locked artboard, as other text edits do. --- crates/engine/src/cmd/paint.rs | 4 ++-- crates/engine/src/script/dom/paths.rs | 2 +- crates/engine/src/script/dom/text/styles.rs | 4 +++- crates/engine/src/tests/editcolors.rs | 15 +++++++++++++++ crates/engine/src/tests/script_dom_paths.rs | 2 +- crates/engine/src/tests/script_text.rs | 3 +++ docs/mcp.md | 3 ++- 7 files changed, 27 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 726aada285..26951ce41c 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -955,9 +955,9 @@ pub(crate) fn object_only(s: &mut Session, p: &Value, cmd: &str, run: impl FnOnc if (!names(p, "ids") && !names(p, "id")) || asks_defaults_only(p) { return Err(bad(cmd, "objectOnly needs ids or id and cannot be combined with defaultsOnly")); } - let kept = (s.paint.clone(), s.fill_active, s.last_solid, s.last_gradient.clone(), s.recent_colors.clone()); + let kept = (s.paint.clone(), s.fill_active, s.last_solid, s.last_gradient.clone(), s.recent_colors.clone(), s.pending_paint.clone()); let result = run(s); - (s.paint, s.fill_active, s.last_solid, s.last_gradient, s.recent_colors) = kept; + (s.paint, s.fill_active, s.last_solid, s.last_gradient, s.recent_colors, s.pending_paint) = kept; if result.is_ok() { s.note_defaults_only(); } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 7785dc25a8..5d2cfdd52f 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -857,7 +857,7 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer { let c = h.dom.coords.get(); let anchors: Vec = script.iter().map(|p| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::>()?; - let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; + let subs = if anchors.is_empty() && !closed { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; write_path(h, item, subs)?; cut_points(h, item); Ok(Data::Undefined) diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index e9121eee6b..45d1a428f3 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -342,7 +342,8 @@ fn target_span(h: &Host, d: &Data) -> std::result::Result { span_of(h, d, &TEXT) } -/// `applyTo(textItem, clearingOverrides?)`. +/// `applyTo(textItem, clearingOverrides?)`. Throws `Cannot edit`, with nothing changed, when the +/// text frame is protected as for any other text edit. fn style_apply_to(h: &Host, a: &[Data]) -> Answer { let style = this_style(h, a)?; let target = target_span(h, arg(a, 1))?; @@ -355,6 +356,7 @@ fn style_apply_to(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("the text is in another document than the style".into())); } let (index, s, e, _) = resolve(h, target)?; + super::refuse_protected(h, target.item, "TextFrame")?; h.charge_call(16 + (e - s) as u64)?; let (start, end) = if style.para { let (_, ba, bb) = para_range(&index, s, e); diff --git a/crates/engine/src/tests/editcolors.rs b/crates/engine/src/tests/editcolors.rs index a42f2c4ca7..1539ece240 100644 --- a/crates/engine/src/tests/editcolors.rs +++ b/crates/engine/src/tests/editcolors.rs @@ -70,6 +70,21 @@ fn balance_previews_and_commits_one_step() { assert_eq!(fill_of(&s, a).to_hex(), "#808080"); } +/// An `objectOnly` paint during an open interaction keeps the remembered colors: the paint it would +/// leave waiting for the commit is not added to Recent Colors when the interaction commits. +#[test] +fn object_only_paint_in_an_interaction_keeps_recent_colors() { + let mut s = session(); + let a = rect(&mut s, json!("#808080")); + s.recent_colors.clear(); + let recent = (s.recent_colors.clone(), s.last_solid); + s.begin_interaction("Adjust Colors").unwrap(); + s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000", "objectOnly": true})).unwrap(); + assert_eq!(fill_of(&s, a).to_hex(), "#ff0000"); + s.commit_interaction().unwrap(); + assert_eq!((s.recent_colors.clone(), s.last_solid), recent, "the recent colors are as they were"); +} + /// Saturate needs its intensity: a call without one, or with one that is not a number, is an error /// that changes nothing and records no undo step. A number outside −100..100 counts as its nearest end. #[test] diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 93f2aaadf9..c0beeeb0a4 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -124,7 +124,7 @@ fn mixed_anchor_and_segment_picks_keep_independent_anchors() { #[test] fn an_empty_path_keeps_closed_before_points_are_added() { - for add in ["p.pathPoints.add(); p.pathPoints.add();", "p.setEntirePath([[0, 0], [10, 0], [10, 10]]);"] { + for add in ["p.pathPoints.add(); p.pathPoints.add();", "p.setEntirePath([[0, 0], [10, 0], [10, 10]]);", "p.setEntirePath([]);"] { let (mut s, _, _) = doc(); let start = s.journal.len(); let out = log( diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index a18184d7ce..af5bc55ea0 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -348,6 +348,9 @@ fn hidden_or_locked_type_is_not_edited() { "r.contents = 'xyz';", "r.characters.add('!');", "r.justification = Justification.CENTER;", + "var b = app.activeDocument.characterStyles.add('Big'); b.characterAttributes.size = 30; b.applyTo(r);", + "var b = app.activeDocument.characterStyles.add('Big'); b.characterAttributes.size = 30; b.applyTo(t);", + "var c = app.activeDocument.paragraphStyles.add('C'); c.paragraphAttributes.justification = Justification.CENTER; c.applyTo(r);", ] { // Each case starts from a fresh frame, so the hidden cases test a frame that is only hidden. let (mut s, id) = doc_with("abc"); diff --git a/docs/mcp.md b/docs/mcp.md index 555e456e3b..49d76671f4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3292,7 +3292,8 @@ through `$`: style's old value. `applyTo` takes a text range, a text frame or its characters, words or paragraphs, in the style's document; a character style on an empty range inside text changes nothing, on empty text it styles the text typed or set later, and a paragraph style styles every paragraph the text touches. `clearingOverrides` left - out is false. A range lists each style once, in the order + out is false. `applyTo` on a frame that is hidden or locked, in a hidden or locked layer or group, or on a locked + artboard throws `Cannot edit` with nothing changed. A range lists each style once, in the order its text first uses it, the Normal style standing for text in no other style, and its lists cannot add or remove styles. The Normal styles cannot be renamed or removed. A style object keeps naming its style after a rename made through `name`; after the style is removed, renamed another way or its document closed or reverted, it throws From 483bf2363dfa63be319cac792e5b9ccf947cff10 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 13:25:11 -0800 Subject: [PATCH 12/22] Scripts: invertMatrix decides overflow from the exact quotient The determinant and the translation numerators are rounded before the division, so a value whose exact quotient is below the overflow midpoint could round to infinity and throw a RangeError, and one at or past it could come out finite. When the rounded quotient overflows or lies within eight steps of Number.MAX_VALUE, the exact quotient is now compared with the midpoint between Number.MAX_VALUE and 2^1024 from exact product parts. An infinite rounded quotient below it is replaced by the number the exact quotient rounds to. --- crates/engine/src/script/dom/matrix.rs | 101 +++++++++++++++++--- crates/engine/src/tests/script_dom_prefs.rs | 25 +++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 4 files changed, 119 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 467a5fc10e..e9fd55e70b 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -125,26 +125,29 @@ fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { // Each product is split into its rounded value and the part that rounding drops, both exact. // The five parts are added one at a time into a list of values that do not overlap, smallest // first, whose sum is exact (Shewchuk's expansion). - let product = |a: f64, b: f64| { - let (a, b) = (Wide::of(a), Wide::of(b)); - let (hi, e) = (a.m * b.m, a.e.saturating_add(b.e)); - [Wide::new(hi, e), Wide::new(a.m.mul_add(b.m, 0.0 - hi), e)] - }; let ([p, p_lost], [q, q_lost]) = (product(x, y), product(z, w)); let exact = [p, p_lost, q, q_lost, Wide::of(t)].into_iter().fold(Parts::EMPTY, grow); nearest(exact) } +/// `a·b` as its rounded value and the part that rounding drops, both exact. +fn product(a: f64, b: f64) -> [Wide; 2] { + let (a, b) = (Wide::of(a), Wide::of(b)); + let (hi, e) = (a.m * b.m, a.e.saturating_add(b.e)); + [Wide::new(hi, e), Wide::new(a.m.mul_add(b.m, 0.0 - hi), e)] +} + /// Values that do not overlap, smallest first, held without allocating. Each value added keeps at -/// most one more, so the five parts of a sum and the two of a comparison fit. +/// most one more, so the five parts of a sum, the two of a comparison and the sixteen of an +/// inverse's rounding test fit. #[derive(Clone, Copy)] struct Parts { - v: [Wide; 8], + v: [Wide; 16], n: usize, } impl Parts { - const EMPTY: Self = Self { v: [Wide { m: 0.0, e: 0 }; 8], n: 0 }; + const EMPTY: Self = Self { v: [Wide { m: 0.0, e: 0 }; 16], n: 0 }; fn as_slice(&self) -> &[Wide] { &self.v[..self.n] @@ -404,9 +407,85 @@ fn invert(_: &Host, a: &[Data]) -> Answer { // Each value is divided by the determinant before it is brought back into the range of a // number, and the translations are taken whole, so a finite inverse is not lost to an // intermediate value. Adding 0 turns -0 into 0. - let over = |w: Wide| w.div(det).value() + 0.0; - let plain = |v: f64| over(Wide::of(v)); - record([plain(d), plain(0.0 - b), plain(0.0 - c), plain(a), over(products_difference(c, f, d, e)), over(products_difference(b, e, a, f))]) + let exact_det = || difference_parts(a, d, b, c); + let zero = Wide::of(0.0); + let plain = |v: f64| quotient(Wide::of(v), || [Wide::of(v), zero, zero, zero], det, exact_det); + record([ + plain(d), + plain(0.0 - b), + plain(0.0 - c), + plain(a), + quotient(products_difference(c, f, d, e), || difference_parts(c, f, d, e), det, exact_det), + quotient(products_difference(b, e, a, f), || difference_parts(b, e, a, f), det, exact_det), + ]) +} + +/// `a·d − b·c` as four exact parts. +fn difference_parts(a: f64, d: f64, b: f64, c: f64) -> [Wide; 4] { + let neg = |w: Wide| Wide { m: 0.0 - w.m, e: w.e }; + let ([p, p_lost], [q, q_lost]) = (product(a, d), product(b, c)); + [p, p_lost, neg(q), neg(q_lost)] +} + +/// The quotient of `num` by `det`, from their rounded values `num` and `det` and their exact parts. +/// The result is the rounded quotient, which is within a few steps of the exact one, except where +/// that would decide overflow wrongly. When the rounded quotient overflows or lies within eight +/// steps of the largest number, the exact quotient is compared with 2^1024 − 2^970, the halfway +/// point between the largest number and 2^1024: at it or past it the result is infinite. Below it +/// a finite rounded quotient is kept, and an infinite one is replaced by the number the exact +/// quotient rounds to, found from the halfway points 2^1024 − j·2^970 (odd `j`) below, ties to the +/// even one. The exact parts are worked out only then. Adding 0 turns -0 into 0. +fn quotient(num: Wide, exact_num: impl Fn() -> [Wide; 4], det: Wide, exact_det: impl Fn() -> [Wide; 4]) -> f64 { + let v = num.div(det).value() + 0.0; + // 2^1024 − 9·2^971, eight steps below the largest number. + let near_top = f64::MAX - 8.0 * pow2(971); + if v.is_finite() && v.abs() < near_top { + return v; + } + let (exact_num, exact_det) = (exact_num(), exact_det()); + let sign = |parts: &[Wide]| match parts.iter().copied().fold(Parts::EMPTY, grow).as_slice().last() { + Some(w) if w.m < 0.0 => -1.0, + _ => 1.0, + }; + let (sn, sd) = (sign(&exact_num), sign(&exact_det)); + // The sign of |num| − (2^1024 − j·2^970)·|det|. Scaling by a power of 2 is exact, and each + // `j·m` is split into its rounded value and the part that rounding drops. + let past = |j: f64| { + let scaled = |w: Wide, s: f64, e: i32| Wide { m: w.m * s, e: w.e.saturating_add(e) }; + let times_j = |w: Wide| { + let hi = j * w.m * sd; + let lo = (j * sd).mul_add(w.m, 0.0 - hi); + [Wide::new(hi, w.e.saturating_add(970)), Wide::new(lo, w.e.saturating_add(970))] + }; + let sum = exact_num + .iter() + .map(|&w| scaled(w, sn, 0)) + .chain(exact_det.iter().map(|&w| scaled(w, 0.0 - sd, 1024))) + .chain(exact_det.iter().flat_map(|&w| times_j(w))) + .fold(Parts::EMPTY, grow); + match sum.as_slice().last() { + Some(w) if w.m > 0.0 => 1, + Some(w) if w.m < 0.0 => -1, + _ => 0, + } + }; + if past(1.0) >= 0 { + return f64::INFINITY; + } + if v.is_finite() { + return v; + } + let even = |x: f64| x.to_bits() & 1 == 0; + let mut top = f64::MAX; + for k in 1..16u8 { + let below = top.next_down(); + match past(f64::from(2 * k + 1)) { + 1 => return top * sn * sd, + 0 => return if even(top) { top } else { below } * sn * sd, + _ => top = below, + } + } + top * sn * sd } fn is_equal(_: &Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index c56542973e..5cb7acb4b2 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -466,6 +466,31 @@ fn a_turn_just_short_of_a_negative_quarter_turn_is_not_rounded_to_it() { assert_eq!(out, vec![json!(true), json!(-1), json!([0, -1, 1, 0]), json!([-1, 0, 0, -1]), json!([0, -1, 1, 0])]); } +#[test] +fn an_inverse_translation_next_to_the_overflow_midpoint_rounds_once() { + let mut s = Session::new(); + // The x-translation's numerator is MAX + 2^970, the overflow midpoint. With b = 2^-53 the + // determinant is 1 + 2^-53, so the exact quotient is MAX - 2^970 + about 2^917, which rounds + // to MAX, while the rounded determinant 1 gives infinity. With b = 0 the quotient is the + // midpoint itself, which rounds to infinity. With a = 1 + 2^-51 and the numerator + // 2^1024 + 3·2^971, the rounded quotient overflows while the exact one is MAX - 2^971 and a + // little more, which rounds to the number below MAX. With b = -2^-54 and ty = -2^969 the rounded + // quotient is MAX, while the exact one is past the overflow midpoint. + let out = log( + &mut s, + "function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var i = app.invertMatrix(mat([1, Math.pow(2, -53), -1, 1, -Number.MAX_VALUE, -Math.pow(2, 970)]));\ + vc.log(i.mValueTX === Number.MAX_VALUE);\ + try { app.invertMatrix(mat([1, 0, -1, 1, -Number.MAX_VALUE, -Math.pow(2, 970)])); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }\ + var j = app.invertMatrix(mat([1 + Math.pow(2, -51), Math.pow(2, -53), -1, 1, -Math.pow(2, 1023), -(Math.pow(2, 1023) + 3 * Math.pow(2, 971))]));\ + vc.log(j.mValueTX === Number.MAX_VALUE - Math.pow(2, 971));\ + try { app.invertMatrix(mat([1, -Math.pow(2, -54), -1, 1, -Number.MAX_VALUE, -Math.pow(2, 969)])); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }", + ); + assert_eq!(out, vec![json!(true), json!("RangeError"), json!(true), json!("RangeError")]); +} + #[test] fn inverse_singular_and_equal_matrices() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index a09de47c27..ae84f1361b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3153,7 +3153,9 @@ through `$`: `scaleY` is `scaleX`; quarter turns are exact; each value `concatenateMatrix` gives is its exact sum of products rounded once; a matrix whose determinant is 0 is singular, and `invertMatrix` of one throws; `isEqualMatrix` compares the six values exactly. A value that is not a finite number throws a `TypeError`, - and a result too large for a number throws a `RangeError`. + and a result too large for a number throws a `RangeError`. `invertMatrix` decides overflow from each value's exact + quotient: when its magnitude is below the halfway point between `Number.MAX_VALUE` and 2^1024 the value is a finite + number, and at that point or past it the call throws a `RangeError`. - `app.copy()`, `app.cut()` and `app.paste()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) run `edit.copy`, `edit.cut` and `edit.paste` on the active document inside the run's transaction. With nothing selected `copy` and `cut` do nothing, and with the clipboard empty `paste` does nothing; `paste` with no document open throws diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 407734ce80..fabc5554ee 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1112,7 +1112,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. + - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. From efdaa06fd260c32545364dac795d2f2e402cd3b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 21:10:26 -0800 Subject: [PATCH 13/22] Scripts: reflect reports matrix defaults; copy notes keep the recording limit - app.reflect now reports the defaults of the matrix functions' number arguments: 0 for deltaX, deltaY and angle, and 100 for scaleX, in the get and concatenate variants. scaleY has no fixed default, since a left-out vertical scale is the horizontal one; its description says so. - When a script's commands take a recording past its limit and the script also copied, the notes of the Copy's formats no longer replace the limit message in the status bar. The limit is named only once, so the message is kept while it shows. The same applies to a script run that automation takes to its end at once. --- crates/engine/src/script/dom/matrix.rs | 20 ++++++++++++- crates/engine/src/tests/script_dom_prefs.rs | 20 +++++++++++++ .../ui-egui/src/panels/actions/recording.rs | 2 ++ .../src/panels/actions/tests_limits.rs | 29 +++++++++++++++++++ crates/ui-egui/src/sysclip.rs | 11 ++++++- 5 files changed, 80 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index e9fd55e70b..0887168db8 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -19,7 +19,7 @@ //! - An argument that is not a finite number, or a matrix with a value that is not one, throws a //! `TypeError`; a result with a value too large for a number throws a `RangeError`. -use vectorcraft_js::{Data, HostError}; +use vectorcraft_js::{Data, HostError, MemberInfo}; use super::{Answer, Described, Host, Link, arg, method, named, num, returns, text}; @@ -54,6 +54,24 @@ pub(super) fn app_members(link: &Link) -> Vec { ("isEqualMatrix", method(l, is_equal), returns("boolean", &[("matrix", "Matrix"), ("secondMatrix", "Matrix")])), ("isSingularMatrix", method(l, is_singular), returns("boolean", &[("matrix", "Matrix")])), ]) + .into_iter() + .map(|(name, member, info)| (name, member, with_defaults(info))) + .collect() +} + +/// `info` with the defaults of its left-out number arguments, which `reflect` reports: 0 for a +/// translation and an angle, 100 for a horizontal scale. A left-out vertical scale is the +/// horizontal one, so it has no fixed default and its description says so. +fn with_defaults(mut info: MemberInfo) -> MemberInfo { + for a in &mut info.arguments { + match a.name.as_str() { + "deltaX" | "deltaY" | "angle" => a.default = Some(num(0.0)), + "scaleX" => a.default = Some(num(100.0)), + "scaleY" => a.description = Some("The vertical scale; when it is left out, the horizontal scale.".into()), + _ => {} + } + } + info } /// The record for `m`, or a `RangeError` when a value is not finite. diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index 5cb7acb4b2..624ff8a7f8 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -342,6 +342,26 @@ fn matrix_functions_give_new_records() { assert_eq!(r, vec![json!([c, sn, -sn, c])]); } +#[test] +fn reflect_reports_the_matrix_argument_defaults() { + let mut s = Session::new(); + let out = log( + &mut s, + "function d(f, a) { return String(app.reflect.find(f).arguments[a].defaultValue); }\ + vc.log([d('getScaleMatrix', 'scaleX'), d('concatenateScaleMatrix', 'scaleX'), d('getTranslationMatrix', 'deltaX'),\ + d('concatenateTranslationMatrix', 'deltaY'), d('getRotationMatrix', 'angle'), d('concatenateRotationMatrix', 'angle'),\ + d('getScaleMatrix', 'scaleY'), d('concatenateMatrix', 'matrix')]);\ + vc.log(app.reflect.find('getScaleMatrix').arguments.scaleY.description);", + ); + assert_eq!( + out, + vec![ + json!(["100", "100", "0", "0", "0", "0", "undefined", "undefined"]), + json!("The vertical scale; when it is left out, the horizontal scale."), + ] + ); +} + #[test] fn concatenation_applies_the_first_matrix_first() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/panels/actions/recording.rs b/crates/ui-egui/src/panels/actions/recording.rs index bf0d4440f8..13ce1bf3bf 100644 --- a/crates/ui-egui/src/panels/actions/recording.rs +++ b/crates/ui-egui/src/panels/actions/recording.rs @@ -172,6 +172,8 @@ pub(crate) fn after_journaled_edit(app: &mut VectorcraftApp) -> bool { Ok(()) => false, Err(e) => { app.status(e); + // The limit is named once: the notes of the edit's Copy or Cut do not replace it. + app.clipboard_publishing.keep_status(&app.ui); true } } diff --git a/crates/ui-egui/src/panels/actions/tests_limits.rs b/crates/ui-egui/src/panels/actions/tests_limits.rs index a4b22246fd..5ecd1c718b 100644 --- a/crates/ui-egui/src/panels/actions/tests_limits.rs +++ b/crates/ui-egui/src/panels/actions/tests_limits.rs @@ -295,6 +295,35 @@ fn script_run_checks_recording_step_limit_on_completion() { } } +/// A script that copies type in a family that is not installed, whose Copy's formats therefore +/// have notes, and whose commands take a recording past 10,000 steps: the status bar keeps naming +/// the limit once the formats are written. Without the recording the notes show. +#[test] +fn a_scripts_copy_notes_do_not_replace_the_recording_limit() { + let steps = "the action already has 10,000 steps"; + let copy = "var t = vc.run('text.create', {x: 5, y: 20, text: 'Ab', font: 'Nonexistent Sans Probe'});\ + vc.run('select.set', {ids: [t.id]}); app.copy();"; + for frames in [false, true] { + for recording in [true, false] { + let services = crate::tests::sysclip::fake_clipboard_services(); + let app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), services)); + let (mut app, _) = three_moves_in(app); + if recording { + recording_with(&mut app, files::MAX_ACTION_STEPS - 1); + } + app.ui.status.clear(); + run_script(&mut app, copy, frames); + let _ = app.written_clipboard_text(); + let what = format!("frames {frames}, recording {recording}"); + if recording { + assert_eq!(app.ui.status, steps, "{what}: the limit stays in the status bar"); + } else { + assert!(app.ui.status.starts_with("Copied with "), "{what}: {}", app.ui.status); + } + } + } +} + /// A script whose commands give the recording's set a file larger than 8 MiB keeps its edit, /// the status bar names the limit as the run ends, and Stop Playing/Recording keeps the steps /// that fit in a set that Load Actions… reads. One that fills the file exactly names no limit. diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index 9371e118fd..8c54822d2f 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -94,6 +94,9 @@ pub(crate) struct Publishing { /// The status bar's message the latest Copy or Cut with notes left, with /// [`crate::state::UiState::status_sets`] then. notes_status: Option<(String, u64)>, + /// A message that no Copy or Cut's notes replace while the status bar shows it (a recording's + /// limit, which is named once), with [`crate::state::UiState::status_sets`] then. + kept: Option<(String, u64)>, } impl Publishing { @@ -118,7 +121,13 @@ impl Publishing { /// Does `ui`'s status bar still show the message the latest Copy or Cut left, with nothing /// setting the status since? fn shows_status(&self, ui: &crate::state::UiState) -> bool { - ui.status == self.status.0 && ui.status_sets == self.status.1 + let kept = self.kept.as_ref().is_some_and(|(s, sets)| ui.status == *s && ui.status_sets == *sets); + !kept && ui.status == self.status.0 && ui.status_sets == self.status.1 + } + + /// `ui`'s status bar message stays while it shows: no Copy or Cut's notes replace it. + pub(crate) fn keep_status(&mut self, ui: &crate::state::UiState) { + self.kept = Some((ui.status.clone(), ui.status_sets)); } /// Is the latest Copy or Cut one whose formats could not be written to `cb`, with nothing From 61770864ecdf8c48c10c53549398178a8b1ef487 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 00:49:28 -0800 Subject: [PATCH 14/22] Scripts: an inverse below half the smallest number rounds once app.invertMatrix divided the rounded numerator by the determinant and rounded again, so an x-translation whose exact quotient is just past half the smallest number (numerator 2^-1021 + 2^-1075, determinant 2^54) came back as 0 instead of Number.MIN_VALUE. When the rounded quotient is below 2^-1023, the result is now found from the exact numerator and determinant: the multiple of the smallest number whose halfway points hold the exact quotient, ties to the even one. A quotient exactly at the halfway point still rounds to 0. --- crates/engine/src/script/dom/matrix.rs | 62 ++++++++++++++++++++- crates/engine/src/tests/script_dom_prefs.rs | 22 ++++++++ 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 0887168db8..bf5c325295 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -452,12 +452,19 @@ fn difference_parts(a: f64, d: f64, b: f64, c: f64) -> [Wide; 4] { /// point between the largest number and 2^1024: at it or past it the result is infinite. Below it /// a finite rounded quotient is kept, and an infinite one is replaced by the number the exact /// quotient rounds to, found from the halfway points 2^1024 − j·2^970 (odd `j`) below, ties to the -/// even one. The exact parts are worked out only then. Adding 0 turns -0 into 0. +/// even one. When the rounded quotient is below 2^-1023, where every number is a multiple of the +/// smallest number, the result is the multiple whose halfway points to its neighbors hold the exact +/// quotient, ties to the even one, so a quotient just past half the smallest number is not rounded +/// to 0. The exact parts are worked out only then. Adding 0 turns -0 into 0. fn quotient(num: Wide, exact_num: impl Fn() -> [Wide; 4], det: Wide, exact_det: impl Fn() -> [Wide; 4]) -> f64 { + if num.m == 0.0 { + return 0.0; + } let v = num.div(det).value() + 0.0; // 2^1024 − 9·2^971, eight steps below the largest number. let near_top = f64::MAX - 8.0 * pow2(971); - if v.is_finite() && v.abs() < near_top { + let tiny = f64::MIN_POSITIVE / 2.0; + if v.is_finite() && v.abs() < near_top && v.abs() >= tiny { return v; } let (exact_num, exact_det) = (exact_num(), exact_det()); @@ -466,6 +473,9 @@ fn quotient(num: Wide, exact_num: impl Fn() -> [Wide; 4], det: Wide, exact_det: _ => 1.0, }; let (sn, sd) = (sign(&exact_num), sign(&exact_det)); + if v.abs() < tiny { + return small_quotient(v, &exact_num, &exact_det, sn, sd); + } // The sign of |num| − (2^1024 − j·2^970)·|det|. Scaling by a power of 2 is exact, and each // `j·m` is split into its rounded value and the part that rounding drops. let past = |j: f64| { @@ -506,6 +516,54 @@ fn quotient(num: Wide, exact_num: impl Fn() -> [Wide; 4], det: Wide, exact_det: top * sn * sd } +/// The exact quotient of `exact_num` by `exact_det`, whose signs are `sn` and `sd`, rounded to a +/// multiple of the smallest number, ties to the even multiple, starting from the rounded quotient +/// `v`, which is below 2^-1023 and within a few steps of it. +fn small_quotient(v: f64, exact_num: &[Wide; 4], exact_det: &[Wide; 4], sn: f64, sd: f64) -> f64 { + let step = f64::from_bits(1); + // The sign of |num| − j·2^-1075·|det|, with each `j·m` split into its rounded value and the + // part that rounding drops. `j` is odd and below 2^53, so it is exact. + let past = |j: f64| { + let times_j = |w: Wide| { + let hi = j * w.m * sd; + let lo = (j * sd).mul_add(w.m, 0.0 - hi); + [Wide::new(0.0 - hi, w.e.saturating_sub(1075)), Wide::new(0.0 - lo, w.e.saturating_sub(1075))] + }; + let sum = exact_num.iter().map(|&w| Wide { m: w.m * sn, e: w.e }).chain(exact_det.iter().flat_map(|&w| times_j(w))).fold(Parts::EMPTY, grow); + match sum.as_slice().last() { + Some(w) if w.m > 0.0 => 1, + Some(w) if w.m < 0.0 => -1, + _ => 0, + } + }; + // `k` steps; dividing by the smallest number is exact. + let mut k = v.abs() / step; + let even = |k: f64| k % 2.0 == 0.0; + for _ in 0..8 { + match past(2.0 * k + 1.0) { + 1 => k += 1.0, + 0 => { + k = if even(k) { k } else { k + 1.0 }; + break; + } + _ => { + if k == 0.0 { + break; + } + match past(2.0 * k - 1.0) { + -1 => k -= 1.0, + 0 => { + k = if even(k) { k } else { k - 1.0 }; + break; + } + _ => break, + } + } + } + } + k * step * sn * sd + 0.0 +} + fn is_equal(_: &Host, a: &[Data]) -> Answer { Ok(Data::Bool(matrix(arg(a, 1), "matrix")? == matrix(arg(a, 2), "secondMatrix")?)) } diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index 624ff8a7f8..2f14af0357 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -511,6 +511,28 @@ fn an_inverse_translation_next_to_the_overflow_midpoint_rounds_once() { assert_eq!(out, vec![json!(true), json!("RangeError"), json!(true), json!("RangeError")]); } +#[test] +fn an_inverse_translation_next_to_half_the_smallest_number_rounds_once() { + let mut s = Session::new(); + // The x-translation's numerator is 2^-1021 + 2^-1075 and the determinant 2^54, so the exact + // quotient is 2^-1075 + 2^-1129, just past half the smallest number, which rounds to it. The + // rounded numerator 2^-1021 gives 2^-1075, which rounds to 0. With c = 0 the quotient is 2^-1075 + // itself, which rounds to 0. With both translations negated, the x-translation rounds to minus + // the smallest number. + let out = log( + &mut s, + "function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var t = Math.pow(2, -1021), big = Math.pow(2, 54), small = Math.pow(2, -54);\ + var i = app.invertMatrix(mat([big, 0, small, 1, -t, t]));\ + vc.log([i.mValueTX === Number.MIN_VALUE, i.mValueTY === -t]);\ + var j = app.invertMatrix(mat([big, 0, 0, 1, -t, t]));\ + vc.log([j.mValueTX, 1 / j.mValueTX > 0]);\ + var k = app.invertMatrix(mat([big, 0, small, 1, t, -t]));\ + vc.log([k.mValueTX === -Number.MIN_VALUE, k.mValueTY === t]);", + ); + assert_eq!(out, vec![json!([true, true]), json!([0, true]), json!([true, true])]); +} + #[test] fn inverse_singular_and_equal_matrices() { let mut s = Session::new(); From d23dd117baa6e63e801b1819b1fc03cf2ead0b21 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 05:12:30 -0800 Subject: [PATCH 15/22] Print: the job asks CUPS for the paper size chosen On macOS and Linux the print job carried no media option, so the queue printed on its default paper whatever Size the Print dialog showed. The dialog now sends the driver's keyword for the chosen Size, and file.print takes it as `paper`; the job passes it to CUPS as `media`. A `paper` that is not a single keyword is an error, and so is `paper` with file output, with directPdf or on Windows, where the spooler does not apply it. While the chosen printer's sizes are still loading, Print is refused and the dialog stays open. A queue with no PPD on this machine (a driverless or remote printer) listed no paper sizes. Its sizes now come from `lpoptions -p NAME -l`, and when its server has no PPD either, from the queue's IPP media-supported attribute on the scheduler CUPS uses. CUPS's B4 and B5 keywords are the JIS sizes, and ISOB4 and ISOB5 the ISO ones. Builds on the printer paper lookup in apps/vectorcraft/src/printing.rs (#10511). --- apps/vectorcraft/src/printing.rs | 106 ++++++++++++- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/print.rs | 34 +++- crates/ui-egui/src/dialogs/tests_print.rs | 184 ++++++++++++++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/print.rs | 128 ++++++++++++++- docs/mcp.md | 7 +- 7 files changed, 440 insertions(+), 23 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index e7f5db9a69..eca59e3ab6 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -22,6 +22,9 @@ impl PrintService for SystemPrint { fn shared_print(&self) -> Option { Some(std::sync::Arc::new(|job| system::print(job).map(|note| sent(job.title, job.printer, ¬e)))) } + fn applies_paper(&self) -> bool { + !cfg!(windows) + } fn turns_landscape(&self) -> bool { // macOS's `lp` doesn't turn a landscape page to the paper: it cuts it off on upright // paper. craft-print turns each sheet to its own orientation on Windows. @@ -113,14 +116,74 @@ mod system { const PPD_CAP: u64 = 16 << 20; let mut bytes = Vec::new(); let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); - if read.is_err() { - return Vec::new(); + let papers = if read.is_ok() { vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) } else { Vec::new() }; + if !papers.is_empty() { + return papers; } - vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) + // A driverless or remote queue has no PPD here: `lpoptions` asks the queue's server for its sizes. + let mut command = Command::new("lpoptions"); + command.args(["-p", printer, "-l"]); + let papers = paper_output(&mut command) + .map(|out| vectorcraft_ui_egui::print::lpoptions_papers(&String::from_utf8_lossy(&out))) + .unwrap_or_default(); + if !papers.is_empty() { + return papers; + } + // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. + let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(cups_server().as_deref(), printer) else { return papers }; + use std::io::Write as _; + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(0); + let test_path = + std::env::temp_dir().join(format!("vectorcraft-printer-papers-{}-{}.test", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let Ok(mut test) = std::fs::File::options().write(true).create_new(true).open(&test_path) else { return papers }; + let written = test.write_all( + b"{\n\ + VERSION 1.1\n\ + OPERATION Get-Printer-Attributes\n\ + GROUP operation-attributes-tag\n\ + ATTR charset attributes-charset utf-8\n\ + ATTR language attributes-natural-language en\n\ + ATTR uri printer-uri $uri\n\ + ATTR keyword requested-attributes media-supported\n\ + STATUS successful-ok\n\ + }\n", + ); + drop(test); + if written.is_err() { + let _ = std::fs::remove_file(&test_path); + return papers; + } + let mut command = Command::new("ipptool"); + command.args(["-T", "10", "-tv", &uri]).arg(&test_path); + let output = paper_output(&mut command); + let _ = std::fs::remove_file(&test_path); + output.map(|out| vectorcraft_ui_egui::print::ipp_papers(&String::from_utf8_lossy(&out))).unwrap_or_default() } } + /// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or + /// `/etc/cups/client.conf`; `None` for the local default. + #[cfg(not(windows))] + fn cups_server() -> Option { + if let Some(server) = std::env::var("CUPS_SERVER").ok().filter(|s| !s.trim().is_empty()) { + return Some(server.trim().to_string()); + } + let home = std::env::var_os("HOME").map(|h| std::path::Path::new(&h).join(".cups/client.conf")); + home.into_iter().chain([std::path::PathBuf::from("/etc/cups/client.conf")]).find_map(|path| { + use std::io::Read as _; + let mut text = String::new(); + std::fs::File::open(path).and_then(|f| f.take(1 << 16).read_to_string(&mut text)).ok()?; + text.lines().rev().find_map(|line| { + let line = line.trim(); + if line.starts_with('#') { + return None; + } + let (key, value) = line.split_once(char::is_whitespace)?; + (key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string()) + }) + }) + } /// Drain output while polling the child, and stop discovery after ten seconds. - #[cfg(windows)] fn paper_output(command: &mut Command) -> Option> { use std::io::Read as _; use std::process::Stdio; @@ -163,10 +226,14 @@ mod system { if job.direct_pdf { return super::direct_pdf::print(job); } - // Copies, layout, marks and colour management are already in the PDF. Preserve its - // physical sheet size and the queue's duplex default without printing copies twice. - let settings = craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() }; - craft::print::submit(job.pdf, &settings).map_err(|e| e.to_string()) + craft::print::submit(job.pdf, &settings(job)).map_err(|e| e.to_string()) + } + /// The spooler's settings for `job`. Copies, layout, marks and colour management are already in the PDF. Preserve + /// its physical sheet size and the queue's duplex default without printing copies twice. The driver's paper + /// keyword goes to CUPS as `media`, so the queue feeds the paper the job was laid out for. + pub(crate) fn settings(job: &PrintJob) -> craft::print::Job { + let options = job.paper.map(|paper| ("media".to_string(), paper.to_string())).into_iter().collect(); + craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), options, ..Default::default() } } #[cfg(windows)] pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command { @@ -310,3 +377,26 @@ mod turn_tests { ); } } + +#[cfg(test)] +mod job_settings_tests { + use super::system::settings; + use vectorcraft_ui_egui::print::PrintJob; + + fn job(paper: Option<&str>) -> PrintJob<'_> { + PrintJob { printer: Some("Card"), title: "Badge", pdf: b"%PDF", paper, direct_pdf: false } + } + + #[test] + fn the_chosen_paper_goes_to_cups_as_media() { + let args = craft::print::lp_args(&settings(&job(Some("CR80")))); + assert!(args.windows(2).any(|w| w == ["-o", "media=CR80"]), "{args:?}"); + assert!(args.windows(2).any(|w| w == ["-d", "Card"]), "{args:?}"); + } + + #[test] + fn without_a_paper_the_queue_keeps_its_own() { + let args = craft::print::lp_args(&settings(&job(None))); + assert!(!args.iter().any(|a| a.starts_with("media=")), "{args:?}"); + } +} diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 8dfdfd28e3..a02bf08641 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1991,7 +1991,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.print", "Print…", "Cmd+P", - "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way", + "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way", ), ( "print.printers", diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 6546b2ff5b..b2b51e69cc 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -209,6 +209,17 @@ fn printer_paper<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a P papers.iter().find(|p| p.key == key) } +/// The driver's keyword for the paper the Size row names, for the job to ask the queue for: the printer's own paper +/// (`printer:CR80`), or the driver's paper of the size of one of the dialog's own papers (`letter` on a driver that lists +/// `Letter`). `None` when the driver lists no such paper, or names it with characters a keyword can't hold. +fn driver_paper_key<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a str> { + let paper = printer_paper(fields, papers).or_else(|| { + let own = Media::from_name(fields.text("media")?).filter(|m| *m != Media::Custom)?; + papers.iter().find(|p| own_media_of(p) == Some(own)) + })?; + crate::print::is_paper_keyword(&paper.key).then_some(paper.key.as_str()) +} + /// Whether two papers have the same Width and Height, to within half a point. fn same_size(a: &Paper, b: &Paper) -> bool { (a.width - b.width).abs() <= 0.5 && (a.height - b.height).abs() <= 0.5 @@ -490,15 +501,16 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, // The paper chosen from the previous list, read before the list is replaced. let chosen = on(dialogs, |p| printer_paper(p.fields(), &open.papers.1).cloned()).flatten(); if printer_changed || open.papers_pending { + let (papers, pending) = papers_of(app, open.mode, &d.printer, printer_changed); // The held answer still names a paper from the previous list. if let Some(answer) = &mut d.ok && let Some(paper) = printer_paper(&answer.fields, &open.papers.1) + && (pending || !printer_paper(&answer.fields, &papers).is_some_and(|new| same_size(paper, new))) { answer.fields.set("width", paper.width); answer.fields.set("height", paper.height); answer.fields.set("media", Media::Custom.id()); } - let (papers, pending) = papers_of(app, open.mode, &d.printer, printer_changed); // While the new printer's lookup runs, the Size list keeps the sizes before it, so the paper chosen keeps its // name and size until the driver answers. papers_changed = !pending; @@ -638,7 +650,7 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, } if let Some(answer) = d.ok { let result = accept(app, open, &answer, &d.name); - on(dialogs, |p| p.answer_ok(result.map_err(Into::into))); + on(dialogs, |p| p.answer_ok(result.map_err(|e| crate::i18n::message(crate::i18n::current(), &e).into()))); } true } @@ -703,17 +715,23 @@ fn accept(app: &mut VectorcraftApp, open: &Open, answer: &PrintAnswer, name: &st if open.mode == PrintMode::PresetEditor { return save_preset(app, open, name, settings); } + let (printer, to_file) = match &answer.settings.destination { + Destination::Printer(name) if name != PDF_FILE => (name.as_str(), false), + _ => ("", true), + }; + let direct_pdf = answer.fields.bool("directPdf").unwrap_or(false); + let applies_paper = !to_file && !direct_pdf && app.services.print.as_ref().is_some_and(|s| s.applies_paper()); + if matches!(answer.finish, PrintFinish::Print) && applies_paper && (open.papers_pending || open.papers.0 != printer) { + return Err("The printer's paper sizes are still loading; try Print again in a moment.".into()); + } // Laid out first, so a bad range or overlap is refused before anything is kept. app.session.execute("print.preview", &json!({ "settings": settings })).map_err(|e| e.to_string())?; app.run("print.setup", json!({ "settings": settings }))?; match answer.finish { PrintFinish::Print => { - let (printer, to_file) = match &answer.settings.destination { - Destination::Printer(name) if name != PDF_FILE => (name.as_str(), false), - _ => ("", true), - }; - let direct_pdf = answer.fields.bool("directPdf").unwrap_or(false); - crate::print::run(app, &json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf })).map(|_| ()) + let paper = if applies_paper { driver_paper_key(&answer.fields, &open.papers.1) } else { None }; + let job = json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf, "paper": paper }); + crate::print::run(app, &job).map(|_| ()) } // Done only keeps the settings. _ => Ok(()), diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index d2ebf74122..fb122e1c67 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -650,6 +650,190 @@ fn windows_paper_sizes_are_read_in_hundredths_of_an_inch() { assert_eq!((got[3].0, got[3].1), ("256", "256"), "no name: the number"); } +#[test] +fn a_queue_without_a_ppd_lists_the_paper_sizes_lpoptions_reports() { + let out = "ColorModel/Color Mode: Gray *RGB\n\ + PageSize/Media Size: *Letter A4 Legal na_index-4x6_4x6in iso_a5_148x210mm B5 ISOB4 Custom.WIDTHxHEIGHT Unknown Letter\r\n\ + media/Media: om_cr80_54x85.6mm tiny_1x1mm\n\ + InputSlot/Source: *Auto Tray1\n"; + let papers = crate::print::lpoptions_papers(out); + let got: Vec<(&str, i64, i64)> = papers.iter().map(|p| (p.key.as_str(), p.width.round() as i64, p.height.round() as i64)).collect(); + // The custom size, the keyword of unknown size, the repeated Letter and a size below 72 pt are left out. + assert_eq!( + got, + [ + ("Letter", 612, 792), + ("A4", 595, 842), + ("Legal", 612, 1008), + ("na_index-4x6_4x6in", 288, 432), + ("iso_a5_148x210mm", 420, 595), + // CUPS names the JIS B sizes B4 and B5, and the ISO ones ISOB4 and ISOB5. + ("B5", 516, 729), + ("ISOB4", 709, 1001), + ("om_cr80_54x85.6mm", 153, 243) + ] + ); + assert!(crate::print::lpoptions_papers("PageSize: \nbroken\nInputSlot: *A4\n").is_empty()); +} + +#[test] +fn a_queue_without_any_ppd_lists_the_media_its_ipp_attributes_report() { + let out = "\"get-printer-attributes.test\":\n\ + \x20 media-default (keyword) = na_letter_8.5x11in\n\ + \x20 media-supported (1setOf keyword) = na_letter_8.5x11in,iso_a4_210x297mm,custom_min_1x1in,oe_photo-l_3.5x5in,na_letter_8.5x11in\r\n\ + \x20 media-ready (1setOf keyword) = iso_a5_148x210mm\n"; + let papers = crate::print::ipp_papers(out); + let got: Vec<(&str, i64, i64)> = papers.iter().map(|p| (p.key.as_str(), p.width.round() as i64, p.height.round() as i64)).collect(); + // Only media-supported counts; the custom range and the repeated Letter are left out. + assert_eq!(got, [("na_letter_8.5x11in", 612, 792), ("iso_a4_210x297mm", 595, 842), ("oe_photo-l_3.5x5in", 252, 360)]); + assert!(crate::print::ipp_papers("media-supported (1setOf keyword) = \n").is_empty()); +} + +#[test] +fn the_ipp_lookup_asks_the_scheduler_cups_uses_for_the_queue() { + use crate::print::ipp_queue_uri; + assert_eq!(ipp_queue_uri(None, "Office+Color").as_deref(), Some("ipp://localhost/printers/Office%2BColor")); + assert_eq!(ipp_queue_uri(Some(" "), "Lab").as_deref(), Some("ipp://localhost/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("print.example.com:631/version=1.1"), "Lab").as_deref(), Some("ipp://print.example.com:631/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("/run/cups/cups.sock"), "Lab"), None, "a domain socket has no URI"); + assert_eq!(ipp_queue_uri(None, ""), None); +} + +/// What the paper-keyword service was asked to print on: each job's paper. +type SentPapers = Rc>>>; + +/// One printer, Card, whose driver lists US Letter and a CR80 card, and which keeps each job's paper keyword. +struct KeywordPrint(SentPapers, bool); + +impl PrintService for KeywordPrint { + fn applies_paper(&self) -> bool { + self.1 + } + + fn printers(&mut self) -> Vec { + vec![Printer::new("Card").is_default(true), Printer::new("Slow")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + self.0.borrow_mut().push(job.paper.map(str::to_string)); + Ok("Sent".into()) + } + + fn papers(&mut self, printer: &str, _fresh: bool) -> Papers { + if printer == "Slow" { + return Papers::Pending; + } + let paper = |key: &str, label: &str, width, height| crate::print::Paper { key: key.into(), label: label.into(), width, height }; + Papers::Ready(vec![paper("Letter", "US Letter", 612.0, 792.0), paper("CR80", "CR80 Card", 153.0, 243.0)]) + } +} + +#[test] +fn the_job_asks_the_queue_for_the_driver_paper_chosen() { + let sent = SentPapers::default(); + let services = Services { print: Some(Box::new(KeywordPrint(sent.clone(), true))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + for (media, keyword) in [("printer:CR80", Some("CR80")), ("letter", Some("Letter")), ("custom", None)] { + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "media", json!(media)); + pump(&mut app); + confirm(&mut app); + assert!(!is_open(&app)); + assert_eq!(sent.borrow().last().cloned().flatten().as_deref(), keyword, "{media}"); + } + assert_eq!(sent.borrow().len(), 3); + // Printing to Slow is refused while its paper sizes are still loading. + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "media", json!("letter")); + set(&mut app, "printer", json!("Slow")); + pump(&mut app); + confirm(&mut app); + assert!(is_open(&app)); + assert_eq!(sent.borrow().len(), 3); + call(&mut app, "ui.dialog.cancel", json!({})); + // Without the dialog, the keyword is given as `paper`, and anything else is refused before printing. + app.run("file.print", json!({"printer": "Card", "paper": "iso_a4_210x297mm"})).unwrap(); + assert_eq!(sent.borrow().last().cloned().flatten().as_deref(), Some("iso_a4_210x297mm")); + for bad in [json!("US Letter"), json!(""), json!("a=b"), json!("Letter,Tray1"), json!("Let'ter"), json!("Let\\ter"), json!(4)] { + assert!(app.run("file.print", json!({"printer": "Card", "paper": bad})).is_err(), "{bad}"); + } + assert!(app.run("file.print", json!({"toFile": true, "paper": "Letter"})).is_err()); + assert_eq!(sent.borrow().len(), 4, "no refused job was sent"); +} + +#[test] +fn a_job_without_a_paper_keyword_prints_while_the_paper_lookup_is_pending() { + let sent = SentPapers::default(); + let services = Services { print: Some(Box::new(KeywordPrint(sent.clone(), false))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("Slow")); + pump(&mut app); + confirm(&mut app); + assert!(!is_open(&app)); + assert_eq!(*sent.borrow(), [None]); +} + +struct PendingKeywordPrint(Rc>, SentPapers); + +impl PrintService for PendingKeywordPrint { + fn printers(&mut self) -> Vec { + PendingTwin(self.0.clone()).printers() + } + + fn print(&mut self, job: &PrintJob) -> Result { + KeywordPrint(self.1.clone(), true).print(job) + } + + fn applies_paper(&self) -> bool { + true + } + + fn papers(&mut self, printer: &str, fresh: bool) -> Papers { + PendingTwin(self.0.clone()).papers(printer, fresh) + } +} + +#[test] +fn a_held_print_keeps_the_paper_keyword_when_the_lookup_finishes() { + let ready = Rc::new(Cell::new(false)); + let sent = SentPapers::default(); + let services = Services { print: Some(Box::new(PendingKeywordPrint(ready.clone(), sent.clone()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "media", json!("printer:CR80")); + pump(&mut app); + set(&mut app, "printer", json!("Twin")); + pump(&mut app); + let ctx = ctx(&app); + let (id, _) = top(&app).expect("the print dialog is open"); + let _ = app.dialogs().expect("a window host").with(|host| host.confirm_by_id(&ctx, id)); + ready.set(true); + pump(&mut app); + pump(&mut app); + assert!(!is_open(&app)); + assert_eq!(*sent.borrow(), [Some("CR80".to_string())]); +} + +#[test] +fn an_explicit_paper_is_refused_when_the_print_path_cannot_apply_it() { + let (mut app, jobs) = app(); + assert!(app.run("file.print", json!({"paper": "Letter"})).is_err()); + assert!(jobs.borrow().is_empty()); + + let sent = SentPapers::default(); + app.services.print = Some(Box::new(KeywordPrint(sent.clone(), true))); + assert!(app.run("file.print", json!({"paper": "Letter", "directPdf": true})).is_err()); + assert!(sent.borrow().is_empty()); +} + /// A print queue that puts each page on the paper as it is, as `lp` does. struct UprightQueue(Jobs); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 3e4a834cb8..98f4bc3b3e 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1992,7 +1992,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.print", "Print…", "Cmd+P", - "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way", + "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way", ), ( "print.printers", diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 0451cb5b5c..919b834d18 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -13,6 +13,7 @@ use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio; use vectorcraft_engine::script::printing::{PreparedPrint, Printers}; +use vectorcraft_pdf::Media; use crate::{VectorcraftApp, io}; @@ -25,6 +26,9 @@ pub struct PrintJob<'a> { /// The job's name in the print queue. pub title: &'a str, pub pdf: &'a [u8], + /// The printer driver's keyword for the paper the job prints on (`Letter`, `CR80`, `iso_a4_210x297mm`), sent to + /// CUPS as the job's `media`; `None` leaves the paper to the queue. + pub paper: Option<&'a str>, /// Send the PDF to the printer's own PDF interpreter over its RAW TCP port instead of /// spooling it through the platform driver (Windows). pub direct_pdf: bool, @@ -39,6 +43,10 @@ pub trait PrintService { fn printers(&mut self) -> Vec; /// Send `job` to its printer → what happened, for the status bar. fn print(&mut self, job: &PrintJob) -> Result; + /// Whether the service applies the job's paper keyword when printing through the driver. + fn applies_paper(&self) -> bool { + false + } /// Desktop services can submit on the existing background worker; browser services stay /// on the UI thread to invoke their print dialog. fn shared_print(&self) -> Option { @@ -156,6 +164,99 @@ pub fn windows_papers(out: &str) -> Vec { papers } +/// The paper sizes of a queue that has no local PPD, from `lpoptions -p NAME -l` (`PageSize/Media Size: *Letter A4 +/// na_legal_8.5x14in`), which asks the queue's server: each choice of its `PageSize` or `media` line, sized by a PWG +/// self-describing name (`iso_a4_210x297mm`, `na_letter_8.5x11in`) or by one of the dialog's own paper names. Custom +/// sizes (`Custom.WxH`), keywords of unknown size and the limits of [`ppd_papers`] are left out. +pub fn lpoptions_papers(out: &str) -> Vec { + let mut papers: Vec = Vec::new(); + for line in out.lines() { + let Some((head, choices)) = line.trim_end_matches('\r').split_once(':') else { continue }; + let key = head.split('/').next().unwrap_or_default().trim(); + if !key.eq_ignore_ascii_case("PageSize") && !key.eq_ignore_ascii_case("media") { + continue; + } + for choice in choices.split_whitespace().map(|c| c.trim_start_matches('*')) { + if !is_paper_keyword(choice) || choice.get(..7).is_some_and(|p| p.eq_ignore_ascii_case("custom.")) { + continue; + } + let size = pwg_size(choice).or_else(|| cups_b_size(choice)).or_else(|| Media::from_name(choice).and_then(Media::size)); + if let Some((width, height)) = size { + push_paper(&mut papers, Paper { key: choice.into(), label: choice.into(), width, height }); + } + } + } + papers +} + +/// The IPP URI of the queue `printer` on the CUPS scheduler `server` (`CUPS_SERVER` or a `ServerName`: `host`, +/// `host:port`, `host:port/version=1.1`; `None` or empty for this machine's). `None` for a domain-socket server (a path), +/// which `ipptool` can't reach by URI. The queue name is percent-encoded. +pub fn ipp_queue_uri(server: Option<&str>, printer: &str) -> Option { + let server = server.map(str::trim).filter(|s| !s.is_empty()).unwrap_or("localhost"); + if server.starts_with('/') || printer.is_empty() { + return None; + } + let host = server.split('/').next().unwrap_or_default(); + if host.is_empty() || host.contains(['@', '?', '#', ' ']) { + return None; + } + let mut name = String::new(); + for b in printer.bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { + name.push(char::from(b)); + } else { + name.push_str(&format!("%{b:02X}")); + } + } + Some(format!("ipp://{host}/printers/{name}")) +} + +/// The size in points of a CUPS PPD keyword for a B size: `B4` and `B5` are the JIS sizes, `ISOB4` and `ISOB5` the ISO +/// ones. +fn cups_b_size(keyword: &str) -> Option<(f64, f64)> { + let mm = match keyword.to_ascii_uppercase().as_str() { + "B4" => (257.0, 364.0), + "B5" => (182.0, 257.0), + "ISOB4" => (250.0, 353.0), + "ISOB5" => (176.0, 250.0), + _ => return None, + }; + Some((mm.0 * 72.0 / 25.4, mm.1 * 72.0 / 25.4)) +} + +/// The paper sizes of a queue that serves no PPD at all, from the `media-supported` line of `ipptool -tv URI +/// get-printer-attributes.test` (`media-supported (1setOf keyword) = na_letter_8.5x11in,iso_a4_210x297mm`): each PWG +/// self-describing name, sized by its name. Custom ranges (`custom_min_…`, `custom_max_…`) and the limits of +/// [`ppd_papers`] are left out. +pub fn ipp_papers(out: &str) -> Vec { + let mut papers: Vec = Vec::new(); + for line in out.lines() { + let Some((head, values)) = line.trim_end_matches('\r').split_once('=') else { continue }; + if head.split_whitespace().next() != Some("media-supported") { + continue; + } + for name in values.split(',').map(str::trim) { + if !is_paper_keyword(name) || name.get(..7).is_some_and(|p| p.eq_ignore_ascii_case("custom_")) { + continue; + } + if let Some((width, height)) = pwg_size(name) { + push_paper(&mut papers, Paper { key: name.into(), label: name.into(), width, height }); + } + } + } + papers +} + +/// The size in points a PWG 5101.1 self-describing media name ends with (`_8.5x11in`, `_210x297mm`). +fn pwg_size(name: &str) -> Option<(f64, f64)> { + let dims = name.rsplit('_').next()?; + let (dims, scale) = if let Some(d) = dims.strip_suffix("mm") { (d, 72.0 / 25.4) } else { (dims.strip_suffix("in")?, 72.0) }; + let (w, h) = dims.split_once('x')?; + let (w, h) = (w.parse::().ok()?, h.parse::().ok()?); + (w.is_finite() && h.is_finite()).then_some((w * scale, h * scale)) +} + /// `print.printers`: the system's printers, and what the print service offers. pub fn printers(app: &mut VectorcraftApp) -> Value { let (printers, setup) = app.services.print.as_mut().map(|s| (s.printers(), s.has_setup())).unwrap_or_default(); @@ -219,7 +320,7 @@ pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec) -> Result, jobs: &[PreparedPrint]) -> Result, String> { let mut notes = Vec::new(); for (sent, job) in jobs.iter().enumerate() { - match submit(&PrintJob { printer: Some(&job.printer), title: &job.title, pdf: &job.pdf, direct_pdf: false }) { + match submit(&PrintJob { printer: Some(&job.printer), title: &job.title, pdf: &job.pdf, paper: None, direct_pdf: false }) { Ok(note) => notes.push(note), Err(e) if sent == 0 => return Err(e), Err(e) => return Err(format!("{e} ({sent} of {} print jobs were sent)", jobs.len())), @@ -228,6 +329,21 @@ fn send_each(submit: &mut dyn FnMut(&PrintJob<'_>) -> Result, jo Ok(notes) } +/// `file.print`'s `paper`: the printer driver's keyword for the paper (absent or null: none). Anything but printable +/// ASCII without spaces, `,`, `/`, `:`, `=`, `"`, `'` or `\`, up to 64 characters, is an error. +fn paper_param(p: &Value) -> Result, String> { + match p.get("paper") { + None | Some(Value::Null) => Ok(None), + Some(Value::String(k)) if is_paper_keyword(k) => Ok(Some(k.clone())), + Some(v) => Err(format!("paper must be a printer driver's paper keyword, such as `Letter` or `CR80`, not {v}")), + } +} + +/// A driver's paper keyword: 1 to 64 printable ASCII characters other than space, `,`, `/`, `:`, `=`, `"`, `'` and `\`. +pub fn is_paper_keyword(k: &str) -> bool { + !k.is_empty() && k.len() <= 64 && k.bytes().all(|b| b.is_ascii_graphic() && !matches!(b, b',' | b'/' | b':' | b'=' | b'"' | b'\'' | b'\\')) +} + /// `file.print` with settings: print the active document with `settings` (over the document's, or /// over those of the print preset `preset` names) on `printer` (default: the system's default), or /// save the job as a PDF at `path` (else a picked file, the web downloads it) with `toFile`, a @@ -238,6 +354,11 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { let s = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string); let postscript = s("format").as_deref() == Some("postscript") || s("path").is_some_and(|path| fileio::extension(&path) == "ps"); let to_file = p.get("toFile").and_then(Value::as_bool).unwrap_or(false) || s("path").is_some() || postscript; + let paper = paper_param(p)?; + let direct_pdf = p.get("directPdf").and_then(Value::as_bool).unwrap_or(false); + if paper.is_some() && (to_file || direct_pdf || !app.services.print.as_ref().is_some_and(|s| s.applies_paper())) { + return Err("The print service cannot apply a paper keyword for this job.".into()); + } let mut q = json!({}); for k in ["preset", "settings", "format", "level", "flattenerPreset"] { if let Some(v) = p.get(k).filter(|v| !v.is_null()) { @@ -270,7 +391,6 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { let pdf = data.as_ref().and_then(Value::as_str).and_then(vectorcraft_format::base64_decode).ok_or("the print job has no data")?; let title = app.session.active().map(|d| d.title()).unwrap_or_default(); let printer = s("printer").filter(|n| !n.is_empty()); - let direct_pdf = p.get("directPdf").and_then(Value::as_bool).unwrap_or(false); let service = app.services.print.as_mut().ok_or("no print service")?; if let Some(submit) = service.shared_print() { let pending_printer = printer.clone(); @@ -280,7 +400,7 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { format!("Printing {title}"), None, move |_| { - submit(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, direct_pdf }) + submit(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, paper: paper.as_deref(), direct_pdf }) .map(|note| json!({ "note": note, "printer": printer })) }, move |app, result| { @@ -302,7 +422,7 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { } return Ok(v); } - let done = service.print(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, direct_pdf })?; + let done = service.print(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, paper: paper.as_deref(), direct_pdf })?; app.status(done); v["printer"] = json!(printer); v["printed"] = json!(true); diff --git a/docs/mcp.md b/docs/mcp.md index 27ec011196..669e8dff94 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13223,7 +13223,12 @@ sheet, tile, ink and copy); headless it answers `dataBase64`. With `maxPages`, t prints at most that many pages, copies counted; with more, `file.print` composes and writes nothing and answers `{pages, format}`. In the app, `file.print` with no params opens the Print dialog, and with params it prints through the system (`printer`: a name from `print.printers`, default the system's -default printer) or, with `toFile`, a `path` or no printing available, saves the PDF. +default printer) or, with `toFile`, a `path` or no printing available, saves the PDF. `paper` names the printer +driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the job asks the print queue for as its +`media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is +not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or +remote queue) lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes +of its IPP `media-supported` attribute. ```json {"name":"run_command","arguments":{"command":"print.setup","params":{"settings":{"media":"a4","scaling":"fit","marks":{"trim":true}}}}} From f5b9e1a04b6c4530b07da640ab7c7fcc74f3d933 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 07:39:49 -0800 Subject: [PATCH 16/22] Print: a client.conf comment no longer spoils the CUPS server name cups_server() took everything after ServerName, so a line such as "ServerName print.example.com # office" gave a value that ipp_queue_uri rejects, and IPP paper discovery was skipped. The value is now read as CUPS reads the file: the first unescaped # starts a comment, and \# stands for a literal #. On macOS, which does not read ServerName, only CUPS_SERVER is used. --- apps/vectorcraft/src/printing.rs | 48 ++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 9 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index eca59e3ab6..d23195588d 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -162,25 +162,37 @@ mod system { } } /// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or - /// `/etc/cups/client.conf`; `None` for the local default. + /// `/etc/cups/client.conf`; `None` for the local default. macOS does not read `ServerName` + /// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts. #[cfg(not(windows))] fn cups_server() -> Option { if let Some(server) = std::env::var("CUPS_SERVER").ok().filter(|s| !s.trim().is_empty()) { return Some(server.trim().to_string()); } + if cfg!(target_os = "macos") { + return None; + } let home = std::env::var_os("HOME").map(|h| std::path::Path::new(&h).join(".cups/client.conf")); home.into_iter().chain([std::path::PathBuf::from("/etc/cups/client.conf")]).find_map(|path| { use std::io::Read as _; let mut text = String::new(); std::fs::File::open(path).and_then(|f| f.take(1 << 16).read_to_string(&mut text)).ok()?; - text.lines().rev().find_map(|line| { - let line = line.trim(); - if line.starts_with('#') { - return None; - } - let (key, value) = line.split_once(char::is_whitespace)?; - (key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string()) - }) + client_conf_server_name(&text) + }) + } + /// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a + /// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is + /// dropped and the rest of the line is kept as written. + #[cfg(not(windows))] + pub(super) fn client_conf_server_name(text: &str) -> Option { + text.lines().rev().find_map(|line| { + let kept = match line.find('#') { + Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]), + Some(at) => line[..at].to_string(), + None => line.to_string(), + }; + let (key, value) = kept.trim().split_once(char::is_whitespace)?; + (key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string()) }) } /// Drain output while polling the child, and stop discovery after ten seconds. @@ -378,6 +390,24 @@ mod turn_tests { } } +#[cfg(all(test, not(windows)))] +mod client_conf_tests { + use super::system::client_conf_server_name; + + #[test] + fn server_name_drops_a_trailing_comment_and_keeps_an_escaped_hash() { + assert_eq!(client_conf_server_name("ServerName print.example.com\n").as_deref(), Some("print.example.com")); + assert_eq!(client_conf_server_name("ServerName print.example.com # office\n").as_deref(), Some("print.example.com")); + assert_eq!(client_conf_server_name("ServerName print.example.com#office\n").as_deref(), Some("print.example.com")); + assert_eq!(client_conf_server_name("ServerName /run/cups\\#1.sock\n").as_deref(), Some("/run/cups#1.sock")); + // After an escaped first `#`, a later `#` stays as written. + assert_eq!(client_conf_server_name("ServerName a\\#b#c\n").as_deref(), Some("a#b#c")); + // A later line that is only a comment, or a directive whose value is all comment, leaves the earlier one. + assert_eq!(client_conf_server_name("ServerName a.example\n# ServerName b.example\nServerName # none\n").as_deref(), Some("a.example")); + assert_eq!(client_conf_server_name("ServerName a.example\nServerName b.example\n").as_deref(), Some("b.example")); + } +} + #[cfg(test)] mod job_settings_tests { use super::system::settings; From 4ca2683571a441cf7d3973d30d4ba9ec578a70a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:22:43 -0800 Subject: [PATCH 17/22] Scripts: preference tests check the run result and the quiet level The merge test now requires the run to succeed instead of accepting any result, through the bounded pump helper. The confirm test sets UserInteractionLevel.DONTDISPLAYALERTS without a try/catch, so the run really asks for no dialogs before the confirm. --- crates/engine/src/tests/script_dom_prefs.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index 2f14af0357..bfdcd5a376 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -151,7 +151,7 @@ fn no_to_the_confirm_or_stop_leaves_the_warning_on() { #[test] fn the_confirm_cannot_be_skipped() { let mut s = Session::new(); - framed(&mut s, &format!("try {{ app.userInteractionLevel = 'DONTDISPLAYALERTS'; }} catch (e) {{}} {ASK_OFF}")); + framed(&mut s, &format!("app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS; {ASK_OFF}")); assert_eq!(s.script_dialog().map(|d| d.message), Some(WARNING_OFF_QUESTION.to_string())); assert!(s.script_answer(DialogAnswer::Confirm(false))); assert!(pump(&mut s).unwrap().is_ok()); @@ -305,7 +305,7 @@ fn a_run_merges_its_keys_with_keys_the_app_changed_meanwhile() { assert!(s.script_running()); s.prefs.script_preferences.insert("theirs".into(), ScriptPreference::Boolean(true)); s.prefs.script_preferences.insert("kept".into(), ScriptPreference::Integer(3)); - while s.script_pump().is_none() {} + pump(&mut s).unwrap().unwrap(); let keys: Vec<(&str, &ScriptPreference)> = s.prefs.script_preferences.iter().map(|(k, v)| (k.as_str(), v)).collect(); assert_eq!( keys, From f382526eb9a86a38c69c48d6a80ad92757048612 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 10:32:46 -0800 Subject: [PATCH 18/22] Print: the IPP paper lookup uses IPP_PORT for a server named without a port ipp_queue_uri built ipp://host/printers/name from CUPS_SERVER or the client.conf ServerName, so a server named without a port was always asked on 631, while CUPS clients use IPP_PORT for it. The app now reads IPP_PORT and passes it in; a port in the server name keeps precedence, and a bracketed IPv6 host counts as having a port only after its ]. With no server named, the lookup uses localhost on IPP_PORT only when none of the CUPS domain sockets exists, since CUPS otherwise talks to its socket. docs/mcp.md describes the lookup's server and port. --- apps/vectorcraft/src/printing.rs | 8 +++++- crates/ui-egui/src/dialogs/tests_print.rs | 33 +++++++++++++++++++---- crates/ui-egui/src/print.rs | 27 ++++++++++++++++--- docs/mcp.md | 4 ++- 4 files changed, 61 insertions(+), 11 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index d23195588d..5fa9535648 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -130,7 +130,13 @@ mod system { return papers; } // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. - let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(cups_server().as_deref(), printer) else { return papers }; + let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); + // With no server named, CUPS uses its domain socket when it exists, and `localhost` on `IPP_PORT` otherwise. + let server = cups_server().or_else(|| { + let sockets = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"]; + (!sockets.iter().any(|s| std::path::Path::new(s).exists())).then(|| "localhost".to_string()) + }); + let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers }; use std::io::Write as _; use std::sync::atomic::{AtomicU64, Ordering}; static NEXT: AtomicU64 = AtomicU64::new(0); diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index fb122e1c67..bb5bb040a5 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -692,11 +692,34 @@ fn a_queue_without_any_ppd_lists_the_media_its_ipp_attributes_report() { #[test] fn the_ipp_lookup_asks_the_scheduler_cups_uses_for_the_queue() { use crate::print::ipp_queue_uri; - assert_eq!(ipp_queue_uri(None, "Office+Color").as_deref(), Some("ipp://localhost/printers/Office%2BColor")); - assert_eq!(ipp_queue_uri(Some(" "), "Lab").as_deref(), Some("ipp://localhost/printers/Lab")); - assert_eq!(ipp_queue_uri(Some("print.example.com:631/version=1.1"), "Lab").as_deref(), Some("ipp://print.example.com:631/printers/Lab")); - assert_eq!(ipp_queue_uri(Some("/run/cups/cups.sock"), "Lab"), None, "a domain socket has no URI"); - assert_eq!(ipp_queue_uri(None, ""), None); + assert_eq!(ipp_queue_uri(None, None, "Office+Color").as_deref(), Some("ipp://localhost/printers/Office%2BColor")); + assert_eq!(ipp_queue_uri(Some(" "), None, "Lab").as_deref(), Some("ipp://localhost/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("print.example.com:631/version=1.1"), None, "Lab").as_deref(), Some("ipp://print.example.com:631/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("/run/cups/cups.sock"), None, "Lab"), None, "a domain socket has no URI"); + assert_eq!(ipp_queue_uri(None, None, ""), None); +} + +#[test] +fn the_ipp_lookup_uses_ipp_port_for_a_server_without_a_port() { + use crate::print::{ipp_port, ipp_queue_uri}; + assert_eq!(ipp_queue_uri(Some("print.example.com"), Some(8631), "Lab").as_deref(), Some("ipp://print.example.com:8631/printers/Lab")); + assert_eq!( + ipp_queue_uri(None, Some(8631), "Lab").as_deref(), + Some("ipp://localhost/printers/Lab"), + "with no server named, CUPS uses its domain socket, not IPP_PORT" + ); + assert_eq!( + ipp_queue_uri(Some("print.example.com:631"), Some(8631), "Lab").as_deref(), + Some("ipp://print.example.com:631/printers/Lab"), + "a port in the server name wins" + ); + assert_eq!(ipp_queue_uri(Some("[::1]"), Some(8631), "Lab").as_deref(), Some("ipp://[::1]:8631/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("[::1]:632"), Some(8631), "Lab").as_deref(), Some("ipp://[::1]:632/printers/Lab")); + assert_eq!(ipp_port(Some("8631")), Some(8631)); + for invalid in [None, Some(""), Some("0"), Some("70000"), Some("ipp")] { + assert_eq!(ipp_port(invalid), None, "{invalid:?}"); + } + assert_eq!(ipp_queue_uri(Some("print.example.com"), ipp_port(Some("x")), "Lab").as_deref(), Some("ipp://print.example.com/printers/Lab")); } /// What the paper-keyword service was asked to print on: each job's paper. diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 919b834d18..1f1cf1981f 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -191,9 +191,14 @@ pub fn lpoptions_papers(out: &str) -> Vec { /// The IPP URI of the queue `printer` on the CUPS scheduler `server` (`CUPS_SERVER` or a `ServerName`: `host`, /// `host:port`, `host:port/version=1.1`; `None` or empty for this machine's). `None` for a domain-socket server (a path), -/// which `ipptool` can't reach by URI. The queue name is percent-encoded. -pub fn ipp_queue_uri(server: Option<&str>, printer: &str) -> Option { - let server = server.map(str::trim).filter(|s| !s.is_empty()).unwrap_or("localhost"); +/// which `ipptool` can't reach by URI. A server named without a port of its own gets `port` (from [`ipp_port`]) when +/// there is one; a bracketed IPv6 host (`[::1]`) has a port only after its `]`. With no server named, the URI is +/// `localhost` on the IPP default port, for a CUPS that reaches its own scheduler through its domain socket; a caller +/// whose CUPS has no socket names `localhost` to get `port`. The queue name is percent-encoded. +pub fn ipp_queue_uri(server: Option<&str>, port: Option, printer: &str) -> Option { + let named = server.map(str::trim).filter(|s| !s.is_empty()); + let port = if named.is_some() { port } else { None }; + let server = named.unwrap_or("localhost"); if server.starts_with('/') || printer.is_empty() { return None; } @@ -209,7 +214,21 @@ pub fn ipp_queue_uri(server: Option<&str>, printer: &str) -> Option { name.push_str(&format!("%{b:02X}")); } } - Some(format!("ipp://{host}/printers/{name}")) + let has_port = match host.strip_prefix('[') { + Some(rest) => rest.split_once(']').is_some_and(|(_, after)| after.starts_with(':')), + None => host.contains(':'), + }; + let port = match port { + Some(port) if !has_port => format!(":{port}"), + _ => String::new(), + }; + Some(format!("ipp://{host}{port}/printers/{name}")) +} + +/// The port CUPS clients use for a server named without one, from the value of `IPP_PORT`: `None` when it is unset, +/// empty or not a port number from 1 to 65535. +pub fn ipp_port(value: Option<&str>) -> Option { + value.and_then(|v| v.trim().parse::().ok()).filter(|p| *p != 0) } /// The size in points of a CUPS PPD keyword for a B size: `B4` and `B5` are the JIS sizes, `ISOB4` and `ISOB5` the ISO diff --git a/docs/mcp.md b/docs/mcp.md index 669e8dff94..8d0d9c3dff 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13228,7 +13228,9 @@ driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the `media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or remote queue) lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes -of its IPP `media-supported` attribute. +of its IPP `media-supported` attribute. That lookup asks the server named by `CUPS_SERVER` or, on Linux, +`client.conf`'s `ServerName`; a server named without a port, or `localhost` when no server is named and CUPS has no domain socket, is +asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. ```json {"name":"run_command","arguments":{"command":"print.setup","params":{"settings":{"media":"a4","scaling":"fit","marks":{"trim":true}}}}} From af28b5380cd8666872de165e6b2f261e9da2248c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 12:51:04 -0800 Subject: [PATCH 19/22] Print: a remote CUPS scheduler supplies its own paper sizes When CUPS_SERVER or client.conf's ServerName names a remote scheduler, the Print dialog no longer reads a same-named PPD under /etc/cups/ppd. The job goes to the remote queue, so the sizes now come from that server through lpoptions and IPP. A domain socket, localhost, 127.0.0.1 and ::1, with an optional port and /version= suffix, still count as local and keep the PPD lookup. --- apps/vectorcraft/src/printing.rs | 67 ++++++++++++++++++++++++++++---- docs/mcp.md | 3 +- 2 files changed, 61 insertions(+), 9 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index f81ca95306..7bfb550876 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -169,12 +169,17 @@ mod system { if printer.contains(['/', '\\']) || printer.starts_with('.') { return Vec::new(); } - const PPD_CAP: u64 = 16 << 20; - let mut bytes = Vec::new(); - let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); - let papers = if read.is_ok() { vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) } else { Vec::new() }; - if !papers.is_empty() { - return papers; + let named = cups_server(); + // A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue, + // so its sizes come from the server. + if scheduler_is_local(named.as_deref()) { + const PPD_CAP: u64 = 16 << 20; + let mut bytes = Vec::new(); + let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); + let papers = if read.is_ok() { vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) } else { Vec::new() }; + if !papers.is_empty() { + return papers; + } } // A driverless or remote queue has no PPD here: `lpoptions` asks the queue's server for its sizes. let mut command = Command::new("lpoptions"); @@ -188,7 +193,7 @@ mod system { // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); // With no server named, CUPS uses its domain socket when it exists, and `localhost` on `IPP_PORT` otherwise. - let server = cups_server().or_else(|| { + let server = named.or_else(|| { let sockets = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"]; (!sockets.iter().any(|s| std::path::Path::new(s).exists())).then(|| "localhost".to_string()) }); @@ -242,6 +247,25 @@ mod system { client_conf_server_name(&text) }) } + /// Whether a scheduler named by `cups_server` runs on this machine: none named, a domain socket path, + /// or `localhost`, `127.0.0.1` or `::1`, each with an optional `:port` and `/version=` suffix. + #[cfg(not(windows))] + pub(super) fn scheduler_is_local(server: Option<&str>) -> bool { + let Some(server) = server.map(str::trim) else { return true }; + if server.starts_with('/') { + return true; + } + // A network name may end in `/version=1.1`. + let server = server.split_once('/').map_or(server, |(server, _)| server); + let host = if let Some(rest) = server.strip_prefix('[') { + rest.split_once(']').map_or(rest, |(host, _)| host) + } else if server.matches(':').count() == 1 { + server.split_once(':').map_or(server, |(host, _)| host) + } else { + server + }; + host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1" + } /// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a /// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is /// dropped and the rest of the line is kept as written. @@ -557,7 +581,34 @@ mod turn_tests { #[cfg(all(test, not(windows)))] mod client_conf_tests { - use super::system::client_conf_server_name; + use super::system::{client_conf_server_name, scheduler_is_local}; + + #[test] + fn only_a_scheduler_on_this_machine_counts_as_local() { + for local in [ + None, + Some("/run/cups/cups.sock"), + Some("localhost"), + Some("LocalHost:631"), + Some("127.0.0.1:8631"), + Some("::1"), + Some("[::1]:631"), + Some("localhost/version=1.1"), + ] { + assert!(scheduler_is_local(local), "{local:?}"); + } + for remote in [ + "print.example.com", + "print.example.com:631", + "192.0.2.7", + "[2001:db8::1]:631", + "2001:db8::1", + "localhost.example.com", + "print.example.com:631/version=1.1", + ] { + assert!(!scheduler_is_local(Some(remote)), "{remote}"); + } + } #[test] fn server_name_drops_a_trailing_comment_and_keeps_an_escaped_hash() { diff --git a/docs/mcp.md b/docs/mcp.md index bf0f467ea4..fb72b22769 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13252,7 +13252,8 @@ default printer) or, with `toFile`, a `path` or no printing available, saves the driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the job asks the print queue for as its `media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or -remote queue) lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes +remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than a domain socket, +`localhost`, `127.0.0.1` or `::1`, lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes of its IPP `media-supported` attribute. That lookup asks the server named by `CUPS_SERVER` or, on Linux, `client.conf`'s `ServerName`; a server named without a port, or `localhost` when no server is named and CUPS has no domain socket, is asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. From 15d11beb8369075c7331edcf2f2b912559d862cf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 15:48:30 -0800 Subject: [PATCH 20/22] Print: a second scheduler on a loopback port supplies its own paper sizes A `CUPS_SERVER` or `ServerName` of `localhost`, `127.0.0.1` or `::1` counts as this machine's scheduler only with no port or port 631. On another port (a second CUPS instance) the dialog no longer reads `/etc/cups/ppd`, whose queues belong to the default scheduler, and asks `lpoptions` and IPP instead. When the named server is one of CUPS's own domain sockets and neither the PPD nor `lpoptions` lists sizes, the IPP lookup asks `localhost` on the IPP default port, as it already does when no server is named. `ipptool` rejects a URI whose host is a socket path (`httpSeparateURI` in CUPS's `cups/http-support.c`), so another socket path is not asked. --- apps/vectorcraft/src/printing.rs | 61 +++++++++++++++++++++++++------- docs/mcp.md | 5 +-- 2 files changed, 51 insertions(+), 15 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index f77d74610c..4eb39067a0 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -199,11 +199,7 @@ mod system { } // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); - // With no server named, CUPS uses its domain socket when it exists, and `localhost` on `IPP_PORT` otherwise. - let server = named.or_else(|| { - let sockets = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"]; - (!sockets.iter().any(|s| std::path::Path::new(s).exists())).then(|| "localhost".to_string()) - }); + let server = ipp_server(named, |s| std::path::Path::new(s).exists()); let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers }; use std::io::Write as _; use std::sync::atomic::{AtomicU64, Ordering}; @@ -235,6 +231,24 @@ mod system { output.map(|out| vectorcraft_ui_egui::print::ipp_papers(&String::from_utf8_lossy(&out))).unwrap_or_default() } } + /// CUPS's own domain sockets, where the local scheduler listens next to `localhost:631`. + #[cfg(not(windows))] + const CUPS_SOCKETS: [&str; 3] = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"]; + /// The server for the IPP lookup, given the one `cups_server` names and whether a path exists. With no server + /// named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost` on the IPP default + /// port), and `localhost` on `IPP_PORT` otherwise. A named domain socket that is one of CUPS's own is the same local + /// scheduler; any other socket path stays as named, so the lookup is skipped rather than asking a scheduler the job + /// does not go to. + /// + /// [`ipp_queue_uri`]: vectorcraft_ui_egui::print::ipp_queue_uri + #[cfg(not(windows))] + pub(super) fn ipp_server(named: Option, exists: impl Fn(&str) -> bool) -> Option { + match named { + Some(server) if CUPS_SOCKETS.contains(&server.trim()) => None, + Some(server) => Some(server), + None => (!CUPS_SOCKETS.iter().any(|s| exists(s))).then(|| "localhost".to_string()), + } + } /// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or /// `/etc/cups/client.conf`; `None` for the local default. macOS does not read `ServerName` /// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts. @@ -255,7 +269,8 @@ mod system { }) } /// Whether a scheduler named by `cups_server` runs on this machine: none named, a domain socket path, - /// or `localhost`, `127.0.0.1` or `::1`, each with an optional `:port` and `/version=` suffix. + /// or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. A loopback + /// name on another port is a second scheduler, whose queues the local PPD folder does not describe. #[cfg(not(windows))] pub(super) fn scheduler_is_local(server: Option<&str>) -> bool { let Some(server) = server.map(str::trim) else { return true }; @@ -264,14 +279,15 @@ mod system { } // A network name may end in `/version=1.1`. let server = server.split_once('/').map_or(server, |(server, _)| server); - let host = if let Some(rest) = server.strip_prefix('[') { - rest.split_once(']').map_or(rest, |(host, _)| host) + let (host, port) = if let Some(rest) = server.strip_prefix('[') { + rest.split_once(']').map_or((rest, None), |(host, after)| (host, after.strip_prefix(':'))) } else if server.matches(':').count() == 1 { - server.split_once(':').map_or(server, |(host, _)| host) + server.split_once(':').map_or((server, None), |(host, port)| (host, Some(port))) } else { - server + (server, None) }; - host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1" + let loopback = host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1"; + loopback && port.is_none_or(|port| port.trim() == "631") } /// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a /// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is @@ -588,7 +604,19 @@ mod turn_tests { #[cfg(all(test, not(windows)))] mod client_conf_tests { - use super::system::{client_conf_server_name, scheduler_is_local}; + use super::system::{client_conf_server_name, ipp_server, scheduler_is_local}; + + #[test] + fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() { + let none = |_: &str| false; + let socket = |s: &str| s == "/run/cups/cups.sock"; + assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none), None, "CUPS's socket is asked as localhost:631"); + assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none), None); + assert_eq!(ipp_server(Some("/tmp/other.sock".into()), socket).as_deref(), Some("/tmp/other.sock"), "another socket is not asked"); + assert_eq!(ipp_server(Some("localhost:8631".into()), socket).as_deref(), Some("localhost:8631")); + assert_eq!(ipp_server(None, socket), None); + assert_eq!(ipp_server(None, none).as_deref(), Some("localhost")); + } #[test] fn only_a_scheduler_on_this_machine_counts_as_local() { @@ -597,10 +625,13 @@ mod client_conf_tests { Some("/run/cups/cups.sock"), Some("localhost"), Some("LocalHost:631"), - Some("127.0.0.1:8631"), + Some("localhost:631"), + Some("127.0.0.1:631"), Some("::1"), Some("[::1]:631"), + Some("[::1]"), Some("localhost/version=1.1"), + Some("localhost:631/version=1.1"), ] { assert!(scheduler_is_local(local), "{local:?}"); } @@ -612,6 +643,10 @@ mod client_conf_tests { "2001:db8::1", "localhost.example.com", "print.example.com:631/version=1.1", + "localhost:8631", + "127.0.0.1:8631", + "[::1]:8631", + "localhost:8631/version=1.1", ] { assert!(!scheduler_is_local(Some(remote)), "{remote}"); } diff --git a/docs/mcp.md b/docs/mcp.md index 8a0b9f86ee..250806a975 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13344,10 +13344,11 @@ driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the `media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than a domain socket, -`localhost`, `127.0.0.1` or `::1`, lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes +`localhost`, `127.0.0.1` or `::1` (each with no port or port 631), lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes of its IPP `media-supported` attribute. That lookup asks the server named by `CUPS_SERVER` or, on Linux, `client.conf`'s `ServerName`; a server named without a port, or `localhost` when no server is named and CUPS has no domain socket, is -asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. +asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. CUPS's own domain socket named as the +server is asked as `localhost` on port 631; another socket path is not asked. In the desktop Print dialog, installed printers appear once the background lookup has returned and the dialog has applied the list. `ui.dialog.set` accepts a named `printer` once it appears in that list. PDF File is available at once. The dialog shows and announces printer discovery. Physical Print is disabled until the list is applied; PDF File and Done remain available. From dc94ae977c4f425e5a5da1900d4d0cd1a621993e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 16:10:05 -0800 Subject: [PATCH 21/22] Docs: matrix records passed in need only the six mValue fields The matrix functions read only mValueA to mValueTY from a record passed in. The typename "Matrix" is on the records they give back. --- crates/engine/src/script/dom/matrix.rs | 7 ++++--- docs/mcp.md | 3 ++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index aeccf78c95..4de0a9efe4 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -1,9 +1,10 @@ //! The matrix functions of `app`, as the help pages //! and //! describe them. A matrix is a plain -//! record with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and `mValueTY` and the -//! `typename` `"Matrix"`; each function other than `isEqualMatrix` and `isSingularMatrix` gives a -//! new record, those two give a boolean, and none changes the records passed to it. +//! record with the finite numbers `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and +//! `mValueTY`; a record passed in needs only those six, and each record a function gives also has +//! the `typename` `"Matrix"`. Each function other than `isEqualMatrix` and `isSingularMatrix` gives +//! a new record, those two give a boolean, and none changes the records passed to it. //! //! The record maps a point `(x, y)` to `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix //! does (ISO 32000-1, 8.3.4), in script coordinates with Y up. diff --git a/docs/mcp.md b/docs/mcp.md index 3f6d406c90..2a2578895e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3278,7 +3278,8 @@ through `$`: `concatenateTranslationMatrix(matrix, deltaX?, deltaY?)`, `concatenateScaleMatrix(matrix, scaleX?, scaleY?)`, `concatenateRotationMatrix(matrix, angle?)`, `invertMatrix(matrix)`, `isEqualMatrix(matrix, secondMatrix)` and `isSingularMatrix(matrix)` work on `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/): plain - objects with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX`, `mValueTY` and `typename` `"Matrix"`. Each + objects with the finite numbers `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and `mValueTY`. A record + passed in needs only those six fields; each record a function gives also has `typename` `"Matrix"`. Each function other than `isEqualMatrix` and `isSingularMatrix` gives a new record; those two give `true` or `false`. No function changes the records passed to it. A record maps `(x, y)` to `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix does (ISO 32000-1, 8.3.4), with Y up. VectorCraft's own From b51d13d2a4d72cf233227e8bcf9dc050fa75c2cf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 17:28:48 -0800 Subject: [PATCH 22/22] New document: a replayed rows count over 1000 is kept to 1000 A file.new step replayed from a journal or the Actions panel rounded artboardLayout.rows and then refused a result over 1000, so a step with rows 1000.5 or 5000 stopped the playback. The rows count now follows the columns rule: it is rounded, must be 1 or more, and is kept to at most 1000. Recent stores the kept count. docs/mcp.md says the same. --- crates/engine/src/cmd/newdoc.rs | 2 +- crates/engine/src/tests/newdoc.rs | 7 ++++++- crates/engine/src/tests/script_dom.rs | 4 ++-- docs/mcp.md | 2 +- 4 files changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 79ce3f97fa..3dc7f579d8 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -395,7 +395,7 @@ impl DocSettings { } "rows" => { self.rows = if replaying { - v.as_f64().map(f64::round).filter(|n| (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32) + v.as_f64().map(f64::round).filter(|n| *n >= 1.0).map(|n| n.min(f64::from(MAX_ARTBOARDS)) as u32) } else { count(v) } diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 200792d5fe..a320b09b18 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -219,6 +219,8 @@ fn replayed_counts_keep_their_rounding_and_range_rules() { ("rows", 2.4, 2), ("rows", 0.6, 1), ("rows", 1000.4, 1000), + ("rows", 1000.6, 1000), + ("rows", 5000.0, 1000), ] { let mut p = json!({"width": 10, "height": 10, "artboards": 4, "artboardLayout": {"layout": "gridByColumn", "spacing": 0}}); @@ -236,8 +238,11 @@ fn replayed_counts_keep_their_rounding_and_range_rules() { p["artboardLayout"][key] = json!(expected); } assert_eq!(boards(&s), boards(&new_doc(p))); + if key == "rows" { + assert_eq!(presets(&mut s, "Recent")[0]["artboardLayout"]["rows"], json!(expected), "{value}"); + } } - for layout in [json!({"columns": 0.6}), json!({"rows": 0.4}), json!({"rows": 1000.6})] { + for layout in [json!({"columns": 0.6}), json!({"rows": 0.4})] { let mut p = json!({"artboardLayout": layout}); p["artboardLayout"]["layout"] = json!("gridByColumn"); let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ca827eb2ab..e4d2f62350 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1306,10 +1306,10 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { #[test] fn file_new_replays_legacy_fractional_and_large_rows() { - for (rows, rounded) in [(3.6, 4), (1000.4, 1000)] { + for (rows, rounded) in [(3.6, 4), (1000.4, 1000), (1000.5, 1000), (5000.0, 1000)] { let params = json!({"width": 100, "height": 100, "artboards": 5, "artboardLayout": {"layout": "gridByColumn", "rows": rows}}); let mut s = Session::new(); - // A direct call refuses a fraction; a replay rounds it to a count from 1 to 1000. + // A direct call refuses a fraction or a count over 1000; a replay rounds it and keeps it to at most 1000. let direct = Session::new().execute("file.new", ¶ms); assert!(direct.is_err(), "{rows}: {direct:?}"); s.replay("file.new", ¶ms).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 5a0fb08062..14fd04a184 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -636,7 +636,7 @@ left out or null; `appearance.setActiveItem` reads a null `index` as clearing th whole number from 1 to 1000, such as `2.4`, `0` or `1001`, and opens no document. A null `artboards` keeps the default or the preset's count; a null `columns` or `rows` is an error. A `file.new` step replayed from a journal or played from the Actions panel keeps the earlier rules: `artboards` is rounded and kept within 1 to 1000, a `columns` of -1 or more is rounded and kept to at most 1000, and a `rows` is rounded and must then be from 1 to 1000. +1 or more is rounded and kept to at most 1000, and a `rows` is rounded, must then be 1 or more, and is kept to at most 1000. A command that leaves out an object selected inside a selected group also leaves it out when `ids` list it together with a group that holds it. Every command that takes `ids` (or `slices`, for the slice commands) refuses a list with an entry that is not a non-negative integer, or a value