From 1b429b586e35da80f83c6e861b800de25a245921 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:31:30 -0800 Subject: [PATCH 01/72] Scripts: Document.print prints to a file with PrintOptions and its option classes Document.print(options) writes the file jobOptions.file names, checked as saveAs checks its file: PostScript when the name ends with .ps or postScriptLevel is assigned, a print-ready PDF otherwise. Only the properties a script assigns are sent to file.print over the document's saved print settings, which stay as they are, and no undo step is added. Without a file it throws, since printing to a printer is not available to scripts yet. - new PrintOptions() and its nine option classes read as their help pages' defaults until assigned, and a PrintOptions holds its option objects by reference. Each value is checked when it is assigned. - Preset, profile and paper names must name an existing preset, an RGB or CMYK profile or a known paper; an empty name or one holding a path separator or control character throws. An artboardRange naming a missing artboard throws before anything is written. - Options and values that are not mapped throw an error that says they are not available yet. printerName and PPDName take only "". - app.printPresetsList lists the print presets, app.PPDFileList is empty, and the print enumerations are published. - Each warning file.print gives goes to the Script Console. - vc.run still cannot run file.print or print.*. - A hosted File given to or returned by a member stays a File. Help pages: https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and the option class pages beside it. --- crates/engine/src/lib.rs | 4 + crates/engine/src/script/dom.rs | 8 +- crates/engine/src/script/dom/print.rs | 974 ++++++++++++++++++++++ crates/engine/src/script/dom/save_open.rs | 8 +- crates/engine/src/session/documents.rs | 1 + crates/engine/src/session/execute.rs | 2 +- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_print.rs | 406 +++++++++ crates/js/src/file_classes.rs | 12 +- crates/js/src/host.rs | 6 + docs/mcp.md | 41 + docs/target-app-parity.md | 1 + 12 files changed, 1455 insertions(+), 9 deletions(-) create mode 100644 crates/engine/src/script/dom/print.rs create mode 100644 crates/engine/src/tests/script_print.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..0a29bb2cc7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -311,6 +311,10 @@ pub struct Session { pub(crate) script_high_water: std::collections::HashMap, /// While a slice of a script runs in this session. pub(crate) script_in_run: bool, + /// The one command a member of the script object model runs past + /// [`script::refused_to_scripts`] while it is set: `file.print` for `Document.print`, after the + /// member checked its options and its file. + pub(crate) script_unfenced: Option<&'static str>, /// Write recovery copies of the unsaved documents before a run, and don't start without them. pub script_copy_first: bool, /// While the active tool's actions run: their commands aren't "a command from outside the diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 5e16f2a121..278ed1eb1b 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,7 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod print; mod save_open; /// The error for a member read or called with no document open. @@ -96,6 +97,8 @@ pub(super) struct State { saving: Cell, /// `app.userInteractionLevel` ([`save_open`]). save_options: save_open::State, + /// The print option objects ([`print`]). + printing: print::State, } impl State { @@ -1711,7 +1714,7 @@ const ENUMS: &[(&str, &[&str])] = &[ /// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { - for (name, members) in ENUMS.iter().chain(save_open::ENUMS) { + for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS) { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } @@ -1726,6 +1729,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ]); application.push(later(l, "Application", "beep")); application.extend(save_open::application_members(l)); + application.extend(print::application_members(l)); let preset = { let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { @@ -1771,6 +1775,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .map(|m| later(l, "Document", m)), ); document.extend(save_open::document_members(l)); + document.extend(print::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", @@ -1836,6 +1841,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), classes.push(class("PageItem", None, page_item, None)); classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); classes.extend(save_open::classes(l)); + classes.extend(print::classes(l)); classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) } diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs new file mode 100644 index 0000000000..c2acec376e --- /dev/null +++ b/crates/engine/src/script/dom/print.rs @@ -0,0 +1,974 @@ +//! Printing in the script object model: `Document.print`, `PrintOptions` and its option classes, +//! `app.printPresetsList`, `app.printerList` and `app.PPDFileList`, as the help pages +//! , +//! , +//! , +//! , +//! , +//! , +//! , +//! , +//! , +//! and +//! describe. +//! +//! An option object is an object of a host class whose properties the run keeps. A `PrintOptions` +//! holds its option objects by reference, so a change made to one after it was assigned is read +//! when `print` is called. Every value is checked when it is assigned; `print` maps the whole tree +//! into `file.print`'s settings before anything is written. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `print` writes a file: `jobOptions.file` names it, a `File` the script may write +//! ([`super::super::files`]). PostScript is written when the name ends with `.ps` or +//! `postScriptOptions.postScriptLevel` is set, a print-ready PDF otherwise. Printing to a printer +//! from a script is not available yet, so `print` without a file throws an error. +//! - Only the properties a script assigned apply; the others keep the document's print settings +//! (`print.setup`), which `print` leaves as they are. A property that was not assigned reads as +//! the default its help page gives. +//! - A property the help pages list that is not mapped accepts the default its help page gives +//! and throws an error that says it is not available yet at any other value. +//! - `fitToPage` set to true wins over the scale factors and the tiling mode. +//! - With `printAllArtboards` set to false, `artboardRange` picks the artboards; without a range +//! every artboard prints. +//! - With one of `horizontalScale` and `verticalScale` assigned, the other keeps the saved value. +//! - `print` throws, before anything is written, when an assigned `artboardRange` names an artboard +//! the document does not have, also with `printAllArtboards` true; when `printPreset` or +//! `flattenerPreset` is not the name of a preset (any case); when `colorManagementOptions.name` is +//! not the name of an RGB or CMYK color profile (any case); and when `paperOptions.name` is not +//! the id or label of a paper `file.print` knows, or names a paper other than `custom` while +//! `width` or `height` is assigned above 0. An assigned name that is empty or only spaces, +//! or that holds `/`, `\` or a control character, throws too. Each checked name goes to +//! `file.print` without the spaces around it. `printerName` and `PPDName` take only the empty +//! string. +//! - A run makes at most [`MAX_OPTION_OBJECTS`] option objects. +//! - `app.printerList` is not available yet, and `app.PPDFileList` is empty: VectorCraft prints +//! without PPD files. + +use std::cell::RefCell; +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_color::cms; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, host_ref, host_ref_parts}; + +use super::save_open::{exactly, file_path, plain, refused}; +use super::{ + Answer, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, arg, command, current, float, get, given, later, method, named, num, on_doc, text, this_doc, + whole, with_doc, +}; +use crate::cmd::flatten::FlattenOptions; + +/// The most option objects one run makes. +pub const MAX_OPTION_OBJECTS: usize = 256; +/// The largest scale factor `file.print` takes, in percent. +pub const MAX_PRINT_SCALE: f64 = 1000.0; +/// The error of `print` without `jobOptions.file`. +pub const NO_PRINTER: &str = "Printing to a printer is not available to scripts yet: set jobOptions.file to print to a file"; +/// The error for an option object from an earlier run. +pub const STALE_OPTIONS: &str = "Stale print options"; + +/// The option objects of the run: each one's class, as an index into [`CLASSES`], and the +/// properties the script assigned. +#[derive(Default)] +pub(in crate::script) struct State { + objects: RefCell>, +} + +struct Options { + class: usize, + set: Vec<(&'static str, Data)>, +} + +const PRINT_COLOR_PROFILE: &[&str] = &["CUSTOMPROFILE", "PRINTERPROFILE", "OLDSTYLEPROFILE", "SOURCEPROFILE"]; +const PRINT_COLOR_INTENT: &[&str] = &["ABSOLUTECOLORIMETRIC", "PERCEPTUALINTENT", "RELATIVECOLORIMETRIC", "SATURATIONINTENT"]; +const PRINT_COLOR_SEPARATION_MODE: &[&str] = &["COMPOSITE", "HOSTBASEDSEPARATION", "INRIPSEPARATION"]; +const PRINT_ORIENTATION: &[&str] = &["AUTOROTATE", "LANDSCAPE", "PORTRAIT", "REVERSELANDSCAPE", "REVERSEPORTRAIT"]; +const PRINT_POSITION: &[&str] = &[ + "TRANSLATEBOTTOM", + "TRANSLATEBOTTOMLEFT", + "TRANSLATEBOTTOMRIGHT", + "TRANSLATECENTER", + "TRANSLATELEFT", + "TRANSLATERIGHT", + "TRANSLATETOP", + "TRANSLATETOPLEFT", + "TRANSLATETOPRIGHT", +]; +const PRINT_TILING: &[&str] = &["TILEFULLPAGES", "TILESINGLEFULLPAGE", "TILEIMAGEABLEAREAS"]; +const PRINT_ARTWORK_DESIGNATION: &[&str] = &["ALLLAYERS", "VISIBLELAYERS", "VISIBLEPRINTABLELAYERS"]; +const PRINTING_BOUNDS: &[&str] = &["ARTBOARDBOUNDS", "ARTWORKBOUNDS"]; +const PRINT_FONT_DOWNLOAD_MODE: &[&str] = &["DOWNLOADNONE", "DOWNLOADCOMPLETE", "DOWNLOADSUBSET"]; +const FONT_SUBSTITUTION_POLICY: &[&str] = &["SUBSTITUTEDEVICE", "SUBSTITUTEOBLIQUE", "SUBSTITUTETINT"]; +const PAGE_MARKS_TYPES: &[&str] = &["Japanese", "Roman"]; +const PDF_OVERPRINT: &[&str] = &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"]; +const POSTSCRIPT_IMAGE_COMPRESSION: &[&str] = &["IMAGECOMPRESSIONNONE", "JPEG", "RLE"]; +const POSTSCRIPT_LEVEL: &[&str] = &["PSLEVEL1", "PSLEVEL2", "PSLEVEL3"]; + +/// The enumerations these members use, as `dom`'s are made. `PDFOverprint` comes from +/// [`super::save_open::ENUMS`]. +pub(super) const ENUMS: &[(&str, &[&str])] = &[ + ("PrintColorProfile", PRINT_COLOR_PROFILE), + ("PrintColorIntent", PRINT_COLOR_INTENT), + ("PrintColorSeparationMode", PRINT_COLOR_SEPARATION_MODE), + ("PrintOrientation", PRINT_ORIENTATION), + ("PrintPosition", PRINT_POSITION), + ("PrintTiling", PRINT_TILING), + ("PrintArtworkDesignation", PRINT_ARTWORK_DESIGNATION), + ("PrintingBounds", PRINTING_BOUNDS), + ("PrintFontDownloadMode", PRINT_FONT_DOWNLOAD_MODE), + ("FontSubstitutionPolicy", FONT_SUBSTITUTION_POLICY), + ("PageMarksTypes", PAGE_MARKS_TYPES), + ("PostScriptImageCompressionType", POSTSCRIPT_IMAGE_COMPRESSION), + ("PrinterPostScriptLevelEnum", POSTSCRIPT_LEVEL), +]; + +/// What a property takes. +#[derive(Clone, Copy)] +enum Kind { + Bool, + /// A finite number from the first to the second. + Number(f64, f64), + /// A whole number from the first to the second. + Whole(u64, u64), + Text, + /// A value of the enumeration (its name and members); only the members in the last list are + /// available. + Choice(&'static str, &'static [&'static str], &'static [&'static str]), + /// An option object of the class named. + Child(&'static str), + File, +} + +/// The default a property reads as before it is assigned. +#[derive(Clone, Copy)] +enum Start { + None, + Bool(bool), + Num(f64), + Text(&'static str), + /// An enumerated value, by its member name. + Member(&'static str), +} + +impl Start { + fn value(self, kind: Kind) -> Data { + match (self, kind) { + (Start::Bool(b), _) => Data::Bool(b), + (Start::Num(n), _) => num(n), + (Start::Text(s), _) => text(s), + (Start::Member(m), Kind::Choice(e, ..)) => text(format!("{e}.{m}")), + _ => Data::Undefined, + } + } + + fn matches(self, kind: Kind, d: &Data) -> bool { + match (self, d) { + (Start::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9, + (Start::None, _) => false, + _ => self.value(kind) == *d, + } + } +} + +/// A property: its name, what it takes, its default, and whether `print` maps it. +struct Field { + name: &'static str, + kind: Kind, + start: Start, + mapped: bool, +} + +const fn f(name: &'static str, kind: Kind, start: Start) -> Field { + Field { name, kind, start, mapped: true } +} + +const fn kept(name: &'static str, kind: Kind, start: Start) -> Field { + Field { name, kind, start, mapped: false } +} + +struct Class { + name: &'static str, + fields: &'static [Field], +} + +const fn choice(e: &'static str, all: &'static [&'static str], ok: &'static [&'static str]) -> Kind { + Kind::Choice(e, all, ok) +} + +const PRINT_OPTIONS: Class = Class { + name: "PrintOptions", + fields: &[ + f("colorManagementOptions", Kind::Child("PrintColorManagementOptions"), Start::None), + f("colorSeparationOptions", Kind::Child("PrintColorSeparationOptions"), Start::None), + f("coordinateOptions", Kind::Child("PrintCoordinateOptions"), Start::None), + f("flattenerOptions", Kind::Child("PrintFlattenerOptions"), Start::None), + f("flattenerPreset", Kind::Text, Start::None), + f("fontOptions", Kind::Child("PrintFontOptions"), Start::None), + f("jobOptions", Kind::Child("PrintJobOptions"), Start::None), + f("pageMarksOptions", Kind::Child("PrintPageMarksOptions"), Start::None), + f("paperOptions", Kind::Child("PrintPaperOptions"), Start::None), + f("postScriptOptions", Kind::Child("PrintPostScriptOptions"), Start::None), + kept("PPDName", Kind::Text, Start::Text("")), + kept("printerName", Kind::Text, Start::Text("")), + f("printPreset", Kind::Text, Start::None), + ], +}; + +const JOB: Class = Class { + name: "PrintJobOptions", + fields: &[ + f("artboardRange", Kind::Text, Start::Text("1-")), + kept("bitmapResolution", Kind::Number(0.0, f64::MAX), Start::Num(0.0)), + f("collate", Kind::Bool, Start::Bool(false)), + f("copies", Kind::Whole(1, 999), Start::Num(1.0)), + f( + "designation", + choice("PrintArtworkDesignation", PRINT_ARTWORK_DESIGNATION, PRINT_ARTWORK_DESIGNATION), + Start::Member("VISIBLEPRINTABLELAYERS"), + ), + f("file", Kind::File, Start::None), + kept("name", Kind::Text, Start::None), + f("printAllArtboards", Kind::Bool, Start::Bool(true)), + f("printArea", choice("PrintingBounds", PRINTING_BOUNDS, &["ARTBOARDBOUNDS"]), Start::Member("ARTBOARDBOUNDS")), + f("printAsBitmap", Kind::Bool, Start::Bool(false)), + f("reversePages", Kind::Bool, Start::Bool(false)), + ], +}; + +const COLOR: Class = Class { + name: "PrintColorManagementOptions", + fields: &[ + f("colorProfileMode", choice("PrintColorProfile", PRINT_COLOR_PROFILE, &["CUSTOMPROFILE", "SOURCEPROFILE"]), Start::Member("SOURCEPROFILE")), + f("intent", choice("PrintColorIntent", PRINT_COLOR_INTENT, PRINT_COLOR_INTENT), Start::Member("RELATIVECOLORIMETRIC")), + f("name", Kind::Text, Start::None), + ], +}; + +const SEPARATION: Class = Class { + name: "PrintColorSeparationOptions", + fields: &[ + f( + "colorSeparationMode", + choice("PrintColorSeparationMode", PRINT_COLOR_SEPARATION_MODE, &["COMPOSITE", "HOSTBASEDSEPARATION"]), + Start::Member("COMPOSITE"), + ), + f("convertSpotColors", Kind::Bool, Start::Bool(false)), + kept("inkList", Kind::Text, Start::None), + f("overPrintBlack", Kind::Bool, Start::Bool(false)), + ], +}; + +const COORDINATE: Class = Class { + name: "PrintCoordinateOptions", + fields: &[ + f("emulsion", Kind::Bool, Start::Bool(false)), + f("fitToPage", Kind::Bool, Start::Bool(false)), + f("horizontalScale", Kind::Number(1.0, 10_000.0), Start::Num(100.0)), + f("orientation", choice("PrintOrientation", PRINT_ORIENTATION, PRINT_ORIENTATION), Start::Member("PORTRAIT")), + f("position", choice("PrintPosition", PRINT_POSITION, PRINT_POSITION), Start::Member("TRANSLATECENTER")), + f("tiling", choice("PrintTiling", PRINT_TILING, PRINT_TILING), Start::Member("TILESINGLEFULLPAGE")), + f("verticalScale", Kind::Number(1.0, 10_000.0), Start::Num(100.0)), + ], +}; + +const FLATTENER: Class = Class { + name: "PrintFlattenerOptions", + fields: &[ + kept("clipComplexRegions", Kind::Bool, Start::Bool(false)), + kept("convertStrokesToOutlines", Kind::Bool, Start::Bool(false)), + kept("convertTextToOutlines", Kind::Bool, Start::Bool(false)), + kept("flatteningBalance", Kind::Number(0.0, 100.0), Start::Num(100.0)), + kept("gradientResolution", Kind::Number(1.0, 9600.0), Start::Num(300.0)), + f("overprint", choice("PDFOverprint", PDF_OVERPRINT, PDF_OVERPRINT), Start::Member("PRESERVEPDFOVERPRINT")), + kept("rasterizationResolution", Kind::Number(1.0, 9600.0), Start::Num(300.0)), + ], +}; + +const FONT: Class = Class { + name: "PrintFontOptions", + fields: &[ + kept("downloadFonts", choice("PrintFontDownloadMode", PRINT_FONT_DOWNLOAD_MODE, &[]), Start::Member("DOWNLOADSUBSET")), + kept("fontSubstitution", choice("FontSubstitutionPolicy", FONT_SUBSTITUTION_POLICY, &[]), Start::Member("SUBSTITUTEOBLIQUE")), + ], +}; + +const MARKS: Class = Class { + name: "PrintPageMarksOptions", + fields: &[ + kept("bleedOffsetRect", Kind::Text, Start::None), + f("colorBars", Kind::Bool, Start::Bool(false)), + kept("marksOffsetRect", Kind::Text, Start::None), + f("pageInfoMarks", Kind::Bool, Start::Bool(false)), + f("pageMarksType", choice("PageMarksTypes", PAGE_MARKS_TYPES, PAGE_MARKS_TYPES), Start::Member("Roman")), + f("registrationMarks", Kind::Bool, Start::Bool(false)), + f("trimMarks", Kind::Bool, Start::Bool(false)), + f("trimMarksWeight", Kind::Number(0.0, 1000.0), Start::Num(0.125)), + ], +}; + +const PAPER: Class = Class { + name: "PrintPaperOptions", + fields: &[ + f("height", Kind::Number(0.0, 14_400.0), Start::Num(0.0)), + f("name", Kind::Text, Start::None), + kept("offset", Kind::Number(0.0, 14_400.0), Start::Num(0.0)), + f("transverse", Kind::Bool, Start::Bool(false)), + f("width", Kind::Number(0.0, 14_400.0), Start::Num(0.0)), + ], +}; + +const POSTSCRIPT: Class = Class { + name: "PrintPostScriptOptions", + fields: &[ + kept("binaryPrinting", Kind::Bool, Start::Bool(false)), + kept("compatibleShading", Kind::Bool, Start::Bool(false)), + kept("forceContinuousTone", Kind::Bool, Start::Bool(false)), + kept("imageCompression", choice("PostScriptImageCompressionType", POSTSCRIPT_IMAGE_COMPRESSION, &[]), Start::Member("IMAGECOMPRESSIONNONE")), + f("negativePrinting", Kind::Bool, Start::Bool(false)), + f("postScriptLevel", choice("PrinterPostScriptLevelEnum", POSTSCRIPT_LEVEL, &["PSLEVEL2", "PSLEVEL3"]), Start::Member("PSLEVEL2")), + kept("shadingResolution", Kind::Number(1.0, 9600.0), Start::Num(300.0)), + ], +}; + +/// The option classes, `PrintOptions` first. +const CLASSES: &[Class] = &[PRINT_OPTIONS, JOB, COLOR, SEPARATION, COORDINATE, FLATTENER, FONT, MARKS, PAPER, POSTSCRIPT]; + +fn class_index(name: &str) -> Option { + CLASSES.iter().position(|c| c.name == name) +} + +fn not_available(class: &str, name: &str) -> HostError { + HostError::Error(format!("{class}.{name} is not available yet")) +} + +/// A new option object of class `class`. +fn create(h: &Host, class: usize) -> Answer { + let mut objects = h.dom.printing.objects.borrow_mut(); + if objects.len() >= MAX_OPTION_OBJECTS { + return Err(HostError::Range(format!("a script can make at most {MAX_OPTION_OBJECTS} print option objects in a run"))); + } + objects.push(Options { class, set: Vec::new() }); + let slot = u64::try_from(objects.len() - 1).unwrap_or(u64::MAX); + Ok(host_ref(CLASSES[class].name, &[float(h.run), float(slot)])) +} + +/// The slot of the option object `d` of class `class`, made in this run. +fn slot_of(h: &Host, d: &Data, class: usize) -> std::result::Result { + let name = CLASSES[class].name; + let wrong = || HostError::Type(format!("this is not a {name}")); + let (c, handle) = host_ref_parts(d).ok_or_else(wrong)?; + if c != name { + return Err(wrong()); + } + let [run, slot] = handle.as_slice() else { return Err(wrong()) }; + let stale = || HostError::Error(STALE_OPTIONS.into()); + if whole(*run) != Some(h.run) { + return Err(stale()); + } + let slot = whole(*slot).and_then(|s| usize::try_from(s).ok()).ok_or_else(stale)?; + match h.dom.printing.objects.borrow().get(slot) { + Some(o) if o.class == class => Ok(slot), + _ => Err(stale()), + } +} + +/// The value `d` assigned to `field` of `class` stores, or `None` when it unsets it. +fn checked(h: &Host, class: &Class, field: &Field, d: &Data) -> std::result::Result, HostError> { + let what = format!("{}.{}", class.name, field.name); + if matches!(d, Data::Undefined) || (matches!(d, Data::Null) && matches!(field.kind, Kind::Child(_) | Kind::File)) { + return Ok(None); + } + if !field.mapped { + return if field.start.matches(field.kind, d) { Ok(None) } else { Err(not_available(class.name, field.name)) }; + } + match field.kind { + Kind::Bool => match d { + Data::Bool(_) => {} + _ => return Err(HostError::Type(format!("{what} must be true or false"))), + }, + Kind::Number(lo, hi) => match d { + Data::Number(n) if n.is_finite() => { + if !(lo..=hi).contains(n) { + return Err(HostError::Range(format!("{what} must be from {lo} to {hi}"))); + } + } + _ => return Err(HostError::Type(format!("{what} must be a finite number"))), + }, + Kind::Whole(lo, hi) => match d { + Data::Number(n) => { + if !whole(*n).is_some_and(|n| (lo..=hi).contains(&n)) { + return Err(HostError::Range(format!("{what} must be a whole number from {lo} to {hi}"))); + } + } + _ => return Err(HostError::Type(format!("{what} must be a number"))), + }, + Kind::Text => match d { + Data::String(s) if s.len() > MAX_TEXT_BYTES => return Err(HostError::Range(format!("{what} is too long"))), + Data::String(_) => {} + _ => return Err(HostError::Type(format!("{what} must be a string"))), + }, + Kind::Choice(e, all, ok) => { + let bad = || HostError::Type(format!("{what} must be a {e} value")); + let Data::String(s) = d else { return Err(bad()) }; + let m = s.strip_prefix(e).and_then(|r| r.strip_prefix('.')).filter(|m| all.contains(m)).ok_or_else(bad)?; + if !ok.contains(&m) { + return Err(HostError::Error(format!("{e}.{m} is not available yet"))); + } + } + Kind::Child(c) => { + let index = class_index(c).ok_or_else(|| HostError::Type(format!("{what} must be a {c}")))?; + slot_of(h, d, index).map_err(|e| match e { + HostError::Type(_) => HostError::Type(format!("{what} must be a {c}")), + e => e, + })?; + } + Kind::File => { + if vectorcraft_js::file_ref_path(d).is_none() { + return Err(HostError::Type(format!("{what} must be a File"))); + } + } + } + Ok(Some(d.clone())) +} + +fn read(h: &Host, class: usize, field: usize, this: &Data) -> Answer { + let slot = slot_of(h, this, class)?; + let spec = &CLASSES[class].fields[field]; + let stored = h.dom.printing.objects.borrow()[slot].set.iter().find(|(k, _)| *k == spec.name).map(|(_, v)| v.clone()); + if let Some(v) = stored { + return Ok(v); + } + match spec.kind { + Kind::Child(c) => { + let index = class_index(c).ok_or_else(|| HostError::Type(format!("no option class {c}")))?; + let child = create(h, index)?; + h.dom.printing.objects.borrow_mut()[slot].set.push((spec.name, child.clone())); + Ok(child) + } + kind => Ok(spec.start.value(kind)), + } +} + +fn write(h: &Host, class: usize, field: usize, this: &Data, d: &Data) -> Answer { + let slot = slot_of(h, this, class)?; + let c = &CLASSES[class]; + let spec = &c.fields[field]; + let value = checked(h, c, spec, d)?; + let mut objects = h.dom.printing.objects.borrow_mut(); + let set = &mut objects[slot].set; + set.retain(|(k, _)| *k != spec.name); + if let Some(v) = value { + set.push((spec.name, v)); + } + Ok(Data::Undefined) +} + +fn property(link: &Link, class: usize, field: usize) -> HostMember { + let (l, m) = (link.clone(), link.clone()); + let get: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + read(&h, class, field, arg(&a, 0)) + }); + let set: HostFunction = Rc::new(move |a: Vec| { + let h = current(&m)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + write(&h, class, field, arg(&a, 0), arg(&a, 1)) + }); + HostMember::Property { get, set } +} + +// ---- Mapping to file.print ---- + +/// What a `PrintOptions` asks `file.print` for. +#[derive(Default)] +struct Job { + preset: Option, + file: Option, + level: Option, + /// The assigned `artboardRange`, checked whether or not it picks the artboards. + range: Option, + /// The assigned names [`check_names`] checks before they go into `settings`: the flattener + /// preset, the color profile and the paper. + flattener: Option, + profile: Option, + paper: Option, + /// A paper `width` or `height` above 0 is assigned. + paper_size: bool, + /// `colorProfileMode` is `SOURCEPROFILE`: the colors print as they are, whatever `name` says. + source: bool, + /// The groups of `settings`: the top level and each nested object by its key. + top: Map, + groups: Vec<(&'static str, Map)>, +} + +impl Job { + fn group(&mut self, key: &'static str) -> &mut Map { + let i = match self.groups.iter().position(|(k, _)| *k == key) { + Some(i) => i, + None => { + self.groups.push((key, Map::new())); + self.groups.len() - 1 + } + }; + &mut self.groups[i].1 + } + + fn settings(&mut self) -> Map { + let mut s = std::mem::take(&mut self.top); + for (k, g) in self.groups.drain(..) { + if !g.is_empty() { + s.insert(k.into(), Value::Object(g)); + } + } + s + } +} + +/// The assigned properties of the option object in `slot`. +fn assigned(h: &Host, slot: usize) -> Vec<(&'static str, Data)> { + h.dom.printing.objects.borrow()[slot].set.clone() +} + +/// The member name of a checked enumerated value (`"PrintTiling.TILEFULLPAGES"` → `TILEFULLPAGES`). +fn member_of(d: &Data) -> &str { + match d { + Data::String(s) => s.rsplit_once('.').map_or("", |(_, m)| m), + _ => "", + } +} + +fn flag(d: &Data) -> bool { + matches!(d, Data::Bool(true)) +} + +fn number_of(d: &Data) -> f64 { + match d { + Data::Number(n) => *n, + _ => 0.0, + } +} + +fn string_of(d: &Data) -> String { + match d { + Data::String(s) => s.clone(), + _ => String::new(), + } +} + +/// The slot of the child a stored `Kind::Child` value names. +fn child_slot(h: &Host, d: &Data, class: &str) -> std::result::Result { + let index = class_index(class).ok_or_else(|| HostError::Type(format!("no option class {class}")))?; + slot_of(h, d, index) +} + +fn map_options(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<(), HostError> { + for (k, v) in assigned(h, slot) { + match k { + "flattenerPreset" => job.flattener = Some(string_of(&v)), + "printPreset" => job.preset = Some(string_of(&v)), + "jobOptions" => map_job(h, child_slot(h, &v, JOB.name)?, job), + "colorManagementOptions" => map_color(h, child_slot(h, &v, COLOR.name)?, job), + "colorSeparationOptions" => map_separation(h, child_slot(h, &v, SEPARATION.name)?, job), + "coordinateOptions" => map_coordinate(h, child_slot(h, &v, COORDINATE.name)?, job)?, + "flattenerOptions" => map_flattener(h, child_slot(h, &v, FLATTENER.name)?, job), + "fontOptions" => { + child_slot(h, &v, FONT.name)?; + } + "pageMarksOptions" => map_marks(h, child_slot(h, &v, MARKS.name)?, job), + "paperOptions" => map_paper(h, child_slot(h, &v, PAPER.name)?, job), + "postScriptOptions" => map_postscript(h, child_slot(h, &v, POSTSCRIPT.name)?, job), + _ => {} + } + } + Ok(()) +} + +fn map_job(h: &Host, slot: usize, job: &mut Job) { + let set = assigned(h, slot); + let value = |name: &str| set.iter().find(|(k, _)| *k == name).map(|(_, v)| v); + for (k, v) in &set { + let s = &mut job.top; + match *k { + "copies" => { + s.insert("copies".into(), json!(whole(number_of(v)).unwrap_or(1))); + } + "collate" => { + s.insert("collate".into(), json!(flag(v))); + } + "reversePages" => { + s.insert("reverse".into(), json!(flag(v))); + } + "designation" => { + let layers = match member_of(v) { + "ALLLAYERS" => "all", + "VISIBLELAYERS" => "visible", + _ => "visiblePrintable", + }; + s.insert("printLayers".into(), json!(layers)); + } + "printAllArtboards" if flag(v) => { + s.insert("artboards".into(), json!("all")); + } + "printAllArtboards" => match value("artboardRange").map(string_of).filter(|r| !r.trim().is_empty()) { + Some(range) => { + s.insert("artboards".into(), json!("range")); + s.insert("range".into(), json!(range)); + } + None => { + s.insert("artboards".into(), json!("all")); + } + }, + "printAsBitmap" => { + job.group("advanced").insert("printAsBitmap".into(), json!(flag(v))); + } + "file" => job.file = Some(v.clone()), + "artboardRange" => job.range = Some(string_of(v)).filter(|r| !r.trim().is_empty()), + _ => {} + } + } +} + +fn map_color(h: &Host, slot: usize, job: &mut Job) { + let set = assigned(h, slot); + let source = set.iter().any(|(k, v)| *k == "colorProfileMode" && member_of(v) == "SOURCEPROFILE"); + job.profile = set.iter().find(|(k, _)| *k == "name").map(|(_, v)| string_of(v)); + job.source = source; + let g = job.group("color"); + for (k, v) in &set { + if *k == "intent" { + let intent = match member_of(v) { + "ABSOLUTECOLORIMETRIC" => "absoluteColorimetric", + "PERCEPTUALINTENT" => "perceptual", + "SATURATIONINTENT" => "saturation", + _ => "relativeColorimetric", + }; + g.insert("intent".into(), json!(intent)); + } + } + if source { + g.insert("profile".into(), json!("")); + } +} + +fn map_separation(h: &Host, slot: usize, job: &mut Job) { + let g = job.group("output"); + for (k, v) in assigned(h, slot) { + match k { + "colorSeparationMode" => { + g.insert("mode".into(), json!(if member_of(&v) == "HOSTBASEDSEPARATION" { "separations" } else { "composite" })); + } + "convertSpotColors" => { + g.insert("spotsToProcess".into(), json!(flag(&v))); + } + "overPrintBlack" => { + g.insert("overprintBlack".into(), json!(flag(&v))); + } + _ => {} + } + } +} + +fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<(), HostError> { + let set = assigned(h, slot); + let value = |name: &str| set.iter().find(|(k, _)| *k == name).map(|(_, v)| v); + let (hs, vs) = (value("horizontalScale").map(number_of), value("verticalScale").map(number_of)); + for (name, n) in [("horizontalScale", hs), ("verticalScale", vs)] { + if n.is_some_and(|n| n > MAX_PRINT_SCALE) { + return Err(HostError::Error(format!("PrintCoordinateOptions.{name} above {MAX_PRINT_SCALE} is not available yet"))); + } + } + let tiling = value("tiling").map(|v| match member_of(v) { + "TILEFULLPAGES" => "tileFull", + "TILEIMAGEABLEAREAS" => "tileImageable", + _ => "none", + }); + let fit = value("fitToPage").map(flag); + let scaled = hs.is_some() || vs.is_some(); + let scaling = if fit == Some(true) { + Some("fit") + } else if let Some(t) = tiling.filter(|t| *t != "none") { + Some(t) + } else if scaled { + Some("custom") + } else if fit.is_some() || tiling.is_some() { + Some("none") + } else { + None + }; + if let Some(scaling) = scaling { + job.top.insert("scaling".into(), json!(scaling)); + } + if scaled && fit != Some(true) { + // Only the assigned factors are sent; with one of them, the other keeps the saved value. + let g = job.group("scale"); + if let Some(w) = hs { + g.insert("width".into(), json!(w)); + } + if let Some(hh) = vs { + g.insert("height".into(), json!(hh)); + } + let linked = match (hs, vs) { + (Some(w), Some(hh)) => (w - hh).abs() < 1e-9, + _ => false, + }; + g.insert("linked".into(), json!(linked)); + } + for (k, v) in &set { + match *k { + "emulsion" => { + job.group("output").insert("emulsion".into(), json!(if flag(v) { "down" } else { "up" })); + } + "orientation" => { + let orientation = match member_of(v) { + "AUTOROTATE" => None, + "LANDSCAPE" => Some("landscape"), + "REVERSEPORTRAIT" => Some("portraitFlipped"), + "REVERSELANDSCAPE" => Some("landscapeFlipped"), + _ => Some("portrait"), + }; + job.top.insert("autoRotate".into(), json!(orientation.is_none())); + if let Some(o) = orientation { + job.top.insert("orientation".into(), json!(o)); + } + } + "position" => { + let origin = match member_of(v) { + "TRANSLATEBOTTOM" => "bottom", + "TRANSLATEBOTTOMLEFT" => "bottomLeft", + "TRANSLATEBOTTOMRIGHT" => "bottomRight", + "TRANSLATELEFT" => "left", + "TRANSLATERIGHT" => "right", + "TRANSLATETOP" => "top", + "TRANSLATETOPLEFT" => "topLeft", + "TRANSLATETOPRIGHT" => "topRight", + _ => "center", + }; + job.group("placement").insert("origin".into(), json!(origin)); + } + _ => {} + } + } + Ok(()) +} + +fn map_flattener(h: &Host, slot: usize, job: &mut Job) { + for (k, v) in assigned(h, slot) { + if k == "overprint" { + let keep = member_of(&v) == "PRESERVEPDFOVERPRINT"; + job.group("advanced").insert("overprints".into(), json!(if keep { "preserve" } else { "discard" })); + } + } +} + +fn map_marks(h: &Host, slot: usize, job: &mut Job) { + let g = job.group("marks"); + for (k, v) in assigned(h, slot) { + let (key, value) = match k { + "colorBars" => ("colorBars", json!(flag(&v))), + "pageInfoMarks" => ("pageInfo", json!(flag(&v))), + "registrationMarks" => ("registration", json!(flag(&v))), + "trimMarks" => ("trim", json!(flag(&v))), + "pageMarksType" => ("kind", json!(if member_of(&v) == "Japanese" { "japanese" } else { "roman" })), + "trimMarksWeight" => ("weight", json!(number_of(&v))), + _ => continue, + }; + g.insert(key.into(), value); + } +} + +fn map_paper(h: &Host, slot: usize, job: &mut Job) { + let set = assigned(h, slot); + let size = |name: &str| set.iter().find(|(k, _)| *k == name).map(|(_, v)| number_of(v)).filter(|n| *n > 0.0); + let (width, height) = (size("width"), size("height")); + job.paper = set.iter().find(|(k, _)| *k == "name").map(|(_, v)| string_of(v)); + job.paper_size = width.is_some() || height.is_some(); + let s = &mut job.top; + if job.paper.is_none() && (width.is_some() || height.is_some()) { + s.insert("media".into(), json!("custom")); + } + if let Some(w) = width { + s.insert("width".into(), json!(w)); + } + if let Some(hh) = height { + s.insert("height".into(), json!(hh)); + } + if let Some((_, v)) = set.iter().find(|(k, _)| *k == "transverse") { + s.insert("transverse".into(), json!(flag(v))); + } +} + +fn map_postscript(h: &Host, slot: usize, job: &mut Job) { + for (k, v) in assigned(h, slot) { + match k { + "negativePrinting" => { + job.group("output").insert("image".into(), json!(if flag(&v) { "negative" } else { "positive" })); + } + "postScriptLevel" => job.level = Some(if member_of(&v) == "PSLEVEL2" { 2 } else { 3 }), + _ => {} + } + } +} + +/// `document.print(options?)`: `file.print` of the document to the file `jobOptions.file` names, +/// with the assigned options over the document's print settings. +fn doc_print(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let mut job = Job::default(); + if let Some(o) = given(arg(a, 1)).filter(|d| !matches!(d, Data::Null)) { + let slot = slot_of(h, o, 0).map_err(|e| match e { + HostError::Type(_) => HostError::Type("print's options must be a PrintOptions object".into()), + e => e, + })?; + map_options(h, slot, &mut job)?; + } + let Some(file) = job.file.take() else { return Err(HostError::Error(NO_PRINTER.into())) }; + check_names(h, doc, &mut job)?; + let path = file_path(&file, "print")?; + let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; + let mut p = Map::new(); + if let Some(preset) = job.preset.take() { + p.insert("preset".into(), json!(preset)); + } + if let Some(level) = job.level { + p.insert("format".into(), json!("postscript")); + p.insert("level".into(), json!(level)); + } + let settings = job.settings(); + if !settings.is_empty() { + p.insert("settings".into(), Value::Object(settings)); + } + p.insert("path".into(), json!(plain(real))); + let printed = exactly(h, || on_doc(h, doc.uid, false, |h| unfenced(h, PRINT, &Value::Object(p))))?; + // What the job lost or how its options apply: one Script Console line each. + let warnings = match &printed { + Data::Object(fields) => fields.iter().find(|(k, _)| k == "warnings").map(|(_, v)| v), + _ => None, + }; + if let Some(Data::Array(warnings)) = warnings { + for w in warnings.iter().take(MAX_LISTED) { + if let Data::String(w) = w { + super::super::each_line(&format!("Document.print: {w}"), |line, cut| h.line(super::super::console::Entry::Output(line), cut)); + } + } + } + Ok(Data::Undefined) +} + +/// Checks, before anything is written, the artboard range against the document's artboards and +/// each assigned name against the list it must come from, and puts the checked names into the +/// job: a print or flattener preset by its name (any case), an RGB or CMYK color profile by its +/// name (any case) and a paper by its id or label. An empty name, or one with a path separator or +/// a control character, throws. +fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> { + if let Some(range) = &job.range { + let count = with_doc(h, doc, |_, st| st.doc.artboards.len()); + vectorcraft_doc::range::parse_range(range, count).map_err(|e| HostError::Range(format!("PrintJobOptions.artboardRange: {e}")))?; + } + let s = h.session.borrow(); + if let Some(name) = job.preset.take() { + let n = plain_name("PrintOptions.printPreset", "print preset", &name)?; + if s.print_preset_settings(n).is_none() { + return Err(no_such("PrintOptions.printPreset", "print preset", &name)); + } + job.preset = Some(n.to_string()); + } + if let Some(name) = job.flattener.take() { + let n = plain_name("PrintOptions.flattenerPreset", "flattener preset", &name)?; + if FlattenOptions::find_preset(n, &s.prefs.flattener_presets).is_none() { + return Err(no_such("PrintOptions.flattenerPreset", "flattener preset", &name)); + } + job.group("advanced").insert("flattenerPreset".into(), json!(n)); + } + if let Some(name) = job.profile.take() { + let what = "PrintColorManagementOptions.name"; + let n = plain_name(what, "color profile", &name)?; + let n = cms::LEGACY_NAMES.iter().find(|(old, _)| old.eq_ignore_ascii_case(n)).map_or(n, |(_, new)| new); + let profile = cms::profiles() + .into_iter() + .find(|p| p.kind != cms::ProfileKind::Gray && p.name.eq_ignore_ascii_case(n)) + .ok_or_else(|| no_such(what, "color profile", &name))?; + if !job.source { + job.group("color").insert("profile".into(), json!(profile.name)); + } + } + if let Some(name) = job.paper.take() { + let n = plain_name("PrintPaperOptions.name", "paper", &name)?; + let media = vectorcraft_pdf::Media::from_name(n).ok_or_else(|| no_such("PrintPaperOptions.name", "paper", &name))?; + if job.paper_size && media != vectorcraft_pdf::Media::Custom { + return Err(HostError::Error(format!("PrintPaperOptions.width and height apply only to custom paper, not {name}"))); + } + job.top.insert("media".into(), json!(media.id())); + } + Ok(()) +} + +/// The error for a name that is not on its list. +fn no_such(what: &str, kind: &str, name: &str) -> HostError { + HostError::Error(format!("{what} names no {kind}: {name}")) +} + +/// `name` without the spaces around it, or an error when it is empty or holds a path separator or +/// a control character. +fn plain_name<'a>(what: &str, kind: &str, name: &'a str) -> std::result::Result<&'a str, HostError> { + let n = name.trim(); + if n.is_empty() { + return Err(HostError::Error(format!("{what} must name a {kind}"))); + } + if n.contains(['/', '\\']) || n.chars().any(char::is_control) { + return Err(no_such(what, kind, name)); + } + Ok(n) +} + +const PRINT: &str = "file.print"; + +/// Runs `id`, which scripts may not run through `vc.run`, for a member that checked its params: +/// only `id` passes the fence, and only for this one command. +fn unfenced(h: &Host, id: &'static str, params: &Value) -> Answer { + h.session.borrow_mut().script_unfenced = Some(id); + let r = command(h, id, params); + h.session.borrow_mut().script_unfenced = None; + r +} + +/// `app.printPresetsList`: the names of the print presets, `[Default]` first. +fn app_presets(h: &Host, _: &[Data]) -> Answer { + let presets = h.session.borrow().print_presets(); + Ok(Data::Array(presets.into_iter().take(MAX_LISTED).map(|p| text(p.name)).collect())) +} + +fn app_ppd_files(_: &Host, _: &[Data]) -> Answer { + Ok(Data::Array(Vec::new())) +} + +/// The members these add to `Application`. +pub(super) fn application_members(l: &Link) -> Vec<(String, HostMember)> { + let mut members = named(vec![("printPresetsList", get(l, app_presets)), ("PPDFileList", get(l, app_ppd_files))]); + members.push(later(l, "Application", "printerList")); + members +} + +/// The members these add to `Document`. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("print", method(l, doc_print))]) +} + +/// The option classes: each `new Name()` gives a new option object with nothing assigned. +pub(super) fn classes(link: &Link) -> Vec { + CLASSES + .iter() + .enumerate() + .map(|(index, c)| { + let l = link.clone(); + let construct: HostFunction = Rc::new(move |_: Vec| { + let h = current(&l)?; + h.charge_call(64)?; + create(&h, index) + }); + let mut members = vec![("typename".to_string(), super::typename_of(c.name))]; + members.extend(c.fields.iter().enumerate().map(|(i, field)| (field.name.to_string(), property(link, index, i)))); + HostClass { name: c.name.into(), parent: None, members, index: None, construct: Some(construct) } + }) + .collect() +} diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index c76ae0f44e..b6a5743f51 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -548,18 +548,18 @@ fn typename(d: &Data) -> Option<&str> { // ---- Files ---- /// The path of the `File` argument `d`, or a `TypeError` naming the method. -fn file_path<'a>(d: &'a Data, method: &str) -> std::result::Result<&'a str, HostError> { +pub(super) fn file_path<'a>(d: &'a Data, method: &str) -> std::result::Result<&'a str, HostError> { vectorcraft_js::file_ref_path(d).ok_or_else(|| HostError::Type(format!("{method} needs a File"))) } /// The error a refused path throws: the `File` error and the path. -fn refused(message: &str, path: &str) -> HostError { +pub(super) fn refused(message: &str, path: &str) -> HostError { HostError::Error(format!("{message}: {path}")) } /// Runs `f` with the commands' reads and writes held to the script's own grants /// ([`super::super::files::Disk::exact`]). -fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer { +pub(super) fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer { h.disk.borrow_mut().exact = true; let r = f(); h.disk.borrow_mut().exact = false; @@ -567,7 +567,7 @@ fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer { } /// The path to give a command for the real path `real`. -fn plain(real: std::path::PathBuf) -> String { +pub(super) fn plain(real: std::path::PathBuf) -> String { crate::cmd::findfiles::plain(real).to_string_lossy().into_owned() } diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..9a439f1437 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -166,6 +166,7 @@ impl Session { script_frames: false, script_high_water: Default::default(), script_in_run: false, + script_unfenced: None, script_copy_first: cfg!(target_arch = "wasm32"), } } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 046c480079..59fc6df773 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -65,7 +65,7 @@ impl Session { return Err(EngineError::Busy); } // A step of a batch a script runs is held to the same rule as the script's own commands. - if self.script_in_run && crate::script::refused_to_scripts(id) { + if self.script_in_run && crate::script::refused_to_scripts(id) && self.script_unfenced != Some(id) { return Err(EngineError::Other(crate::script::refused_text(id))); } // An edit the active tool is computing on another thread (a Shape Builder merge) is diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 436d74cf75..9c17868014 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -177,6 +177,7 @@ mod script_engines; mod script_folder; mod script_include; mod script_io; +mod script_print; mod script_run; mod script_save_open; mod scripts; diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs new file mode 100644 index 0000000000..104687e0e3 --- /dev/null +++ b/crates/engine/src/tests/script_print.rs @@ -0,0 +1,406 @@ +//! Printing from a script: `Document.print` with `PrintOptions` and its option classes, +//! `app.printPresetsList`, `app.PPDFileList`, and the checks every option and the file go through. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +const DENIED: &str = "Script file access denied"; + +/// A fresh folder for test `name`, by its real path, with `main` for the script. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-print-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("outside")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// A session whose scripts keep their data folders in `base/settings/Script Data`, with a +/// 300 × 200 document of two artboards holding a rectangle. +fn session(base: &Path) -> Session { + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 2})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + s +} + +/// Runs `main/main.jsx` in `base` with the text `text` in `s`. +fn run(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text.as_bytes()).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +fn logged(s: &mut Session, base: &Path, text: &str) -> Value { + run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"))["log"].clone() +} + +fn failure(s: &mut Session, base: &Path, text: &str) -> String { + run(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string() +} + +/// The script's data folder, where it may write. +fn data_folder(s: &mut Session, base: &Path) -> PathBuf { + PathBuf::from(logged(s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap()) +} + +fn quoted(p: &Path) -> String { + serde_json::to_string(&p.to_string_lossy()).unwrap() +} + +fn pages(path: &Path) -> Vec<(f64, f64)> { + let info = vectorcraft_pdf::info(&std::fs::read(path).unwrap(), None).unwrap(); + info.pages.iter().map(|p| (p.width.round(), p.height.round())).collect() +} + +#[test] +fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() { + let base = folder("happy"); + let mut s = session(&base); + s.execute("print.setup", &json!({"settings": {"collate": true, "marks": {"trim": true}}})).unwrap(); + let saved = s.execute("print.setup", &json!({})).unwrap()["settings"].clone(); + let undo = s.active().unwrap().history.undo.len(); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, doc = app.activeDocument;\n\ + var o = new PrintOptions(), j = new PrintJobOptions();\n\ + vc.log([o.typename, j.typename, j.copies, j.collate, j.printAllArtboards, j.designation, o.coordinateOptions.typename]);\n\ + o.jobOptions = j; j.copies = 2; j.file = new File(dir + '/a.pdf');\n\ + j.copies = 3; vc.log([o.jobOptions.copies, j.collate]);\n\ + doc.print(o);\n\ + var back = o.jobOptions.file; j.file = back; vc.log([back instanceof File, back.name]);\n\ + j.printAllArtboards = false; j.artboardRange = '2'; j.copies = 1; j.file = new File(dir + '/b.pdf');\n\ + o.paperOptions.name = 'a4'; o.coordinateOptions.fitToPage = true; o.coordinateOptions.orientation = PrintOrientation.PORTRAIT;\n\ + o.printerName = ''; o.fontOptions.downloadFonts = PrintFontDownloadMode.DOWNLOADSUBSET;\n\ + doc.print(o);\n\ + o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2; j.file = new File(dir + '/c.ps');\n\ + doc.print(o);\n\ + vc.log([app.printPresetsList[0], app.PPDFileList.length]);" + ), + ); + let expected = + json!(["PrintOptions", "PrintJobOptions", 1, false, true, "PrintArtworkDesignation.VISIBLEPRINTABLELAYERS", "PrintCoordinateOptions"]); + assert_eq!(out[0], expected, "a new option object reads as its help page's defaults"); + assert_eq!(out[1], json!([3, false]), "a change after the assignment is read through the PrintOptions"); + assert_eq!(out[2], json!([true, "a.pdf"]), "jobOptions.file reads back as a File"); + assert_eq!(out[3], json!(["[Default]", 0])); + assert_eq!(pages(&dir.join("a.pdf")).len(), 6, "two artboards, three copies"); + assert_eq!(pages(&dir.join("b.pdf")), vec![(595.0, 842.0)], "artboard 2 only, on upright A4"); + let ps = std::fs::read_to_string(dir.join("c.ps")).unwrap(); + assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 2"), "{}", &ps[..ps.len().min(200)]); + assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved, "printing leaves the saved settings as they are"); + assert_eq!(s.active().unwrap().history.undo.len(), undo, "and adds no undo step"); + // The commands stay closed to vc.run, before and after a print. + for case in [ + "vc.run('file.print', {});", + "var o = new PrintOptions(); o.jobOptions.file = new File(Folder.userData.fsName + '/d.pdf'); app.activeDocument.print(o); vc.run('file.print', {});", + "vc.run('print.setup', {settings: {copies: 5}});", + ] { + let e = failure(&mut s, &base, case); + assert!(e.contains("a script cannot run"), "{case}: {e}"); + } + assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn print_without_a_file_does_not_print() { + let base = folder("no-file"); + let mut s = session(&base); + for case in [ + "app.activeDocument.print();", + "app.activeDocument.print(new PrintOptions());", + "var o = new PrintOptions(); o.jobOptions.copies = 2; app.activeDocument.print(o);", + ] { + let e = failure(&mut s, &base, case); + assert!(e.contains("Printing to a printer is not available to scripts yet"), "{case}: {e}"); + } + let e = failure(&mut s, &base, "app.printerList;"); + assert!(e.contains("Application.printerList is not available yet"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + +/// Bad values throw when they are assigned, and nothing prints. +#[test] +fn print_options_refuse_bad_values() { + let base = folder("bad"); + let mut s = session(&base); + let cases = [ + ("j.copies = 0;", "RangeError", "copies must be a whole number from 1 to 999"), + ("j.copies = NaN;", "TypeError", "copies"), + ("j.copies = 1e12;", "RangeError", "copies must be a whole number"), + ("j.copies = 1.5;", "RangeError", "copies must be a whole number"), + ("j.copies = '2';", "TypeError", "copies must be a number"), + ("j.collate = 1;", "TypeError", "collate must be true or false"), + ("c.horizontalScale = NaN;", "TypeError", "horizontalScale"), + ("c.horizontalScale = Infinity;", "TypeError", "horizontalScale"), + ("c.verticalScale = 20000;", "RangeError", "verticalScale must be from 1 to 10000"), + ("c.verticalScale = 0;", "RangeError", "verticalScale must be from 1 to 10000"), + ("m.trimMarksWeight = -1;", "RangeError", "trimMarksWeight must be from 0"), + ("c.orientation = 'PrintOrientation.SIDEWAYS';", "TypeError", "orientation must be a PrintOrientation value"), + ("c.orientation = 'PrintTiling.TILEFULLPAGES';", "TypeError", "orientation must be a PrintOrientation value"), + ("j.file = 'C:/out.pdf';", "TypeError", "file must be a File"), + ("j.file = {};", "TypeError", "file must be a File"), + ("o.jobOptions = new PrintCoordinateOptions();", "TypeError", "jobOptions must be a PrintJobOptions"), + ("o.jobOptions = {copies: 2};", "TypeError", "jobOptions must be a PrintJobOptions"), + ("o.printPreset = new Array(5000).join('x');", "RangeError", "printPreset is too long"), + ("app.activeDocument.print({jobOptions: j});", "TypeError", "print's options must be a PrintOptions object"), + ("app.activeDocument.print(j);", "TypeError", "print's options must be a PrintOptions object"), + ]; + let prefix = "var o = new PrintOptions(), j = o.jobOptions, c = o.coordinateOptions, m = o.pageMarksOptions;"; + for (case, kind, part) in cases { + let e = failure(&mut s, &base, &format!("{prefix} {case}")); + assert!(e.contains(kind) && e.contains(part), "{case}: {e}"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// Options that `file.print` cannot honor throw instead of being dropped. +#[test] +fn options_that_are_not_available_throw() { + let base = folder("later"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf"))); + let cases = [ + ("o.printerName = 'Office';", "PrintOptions.printerName is not available yet"), + ("o.printerName = '\\\\\\\\server\\\\share';", "PrintOptions.printerName is not available yet"), + ("o.PPDName = 'Generic';", "PrintOptions.PPDName is not available yet"), + ("o.PPDName = '/etc/cups/ppd/office.ppd';", "PrintOptions.PPDName is not available yet"), + ("j.name = 'Job';", "PrintJobOptions.name is not available yet"), + ("j.printArea = PrintingBounds.ARTWORKBOUNDS;", "PrintingBounds.ARTWORKBOUNDS is not available yet"), + ("o.colorSeparationOptions.colorSeparationMode = PrintColorSeparationMode.INRIPSEPARATION;", "INRIPSEPARATION is not available yet"), + ("o.colorManagementOptions.colorProfileMode = PrintColorProfile.PRINTERPROFILE;", "PRINTERPROFILE is not available yet"), + ("o.colorSeparationOptions.inkList = [];", "PrintColorSeparationOptions.inkList is not available yet"), + ("o.fontOptions.downloadFonts = PrintFontDownloadMode.DOWNLOADCOMPLETE;", "PrintFontOptions.downloadFonts is not available yet"), + ("o.flattenerOptions.rasterizationResolution = 600;", "PrintFlattenerOptions.rasterizationResolution is not available yet"), + ("o.flattenerOptions.rasterizationResolution = NaN;", "PrintFlattenerOptions.rasterizationResolution"), + ("o.pageMarksOptions.bleedOffsetRect = [0, 0, 0, 0];", "PrintPageMarksOptions.bleedOffsetRect is not available yet"), + ("o.paperOptions.offset = 10;", "PrintPaperOptions.offset is not available yet"), + ("o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL1;", "PSLEVEL1 is not available yet"), + ("o.postScriptOptions.binaryPrinting = true;", "PrintPostScriptOptions.binaryPrinting is not available yet"), + ( + &format!("{file} o.coordinateOptions.horizontalScale = 2000; app.activeDocument.print(o);"), + "horizontalScale above 1000 is not available yet", + ), + ]; + let prefix = "Folder.userData; var o = new PrintOptions(), j = o.jobOptions;"; + for (case, part) in cases { + let e = failure(&mut s, &base, &format!("{prefix} {case}")); + assert!(e.contains(part), "{case}: {e}"); + } + assert!(!dir.join("x.pdf").exists(), "nothing printed"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn print_writes_only_where_the_script_may() { + let base = folder("refused"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let grants = base.join("settings/Script Grants.json"); + std::fs::write(&grants, "{}").unwrap(); + for target in [base.join("outside/x.pdf"), grants.clone(), dir.clone()] { + let case = + format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);", quoted(&target)); + let e = failure(&mut s, &base, &case); + assert!(e.contains("Script file"), "{case}: {e}"); + if target != dir { + assert!(e.contains(DENIED), "{case}: {e}"); + } + } + assert!(!base.join("outside/x.pdf").exists()); + assert_eq!(std::fs::read_to_string(&grants).unwrap(), "{}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A print to a file a `File` object holds open for writing throws, so the object's bytes written at +/// the end of the run do not replace the printed file. +#[test] +fn print_does_not_write_a_file_open_for_writing() { + let base = folder("openhandle"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let p = quoted(&dir.join("x.pdf")); + let log = logged( + &mut s, + &base, + &format!( + "Folder.userData; var w = new File({p}); w.open('w'); w.write('pending');\nvar o = new PrintOptions(); o.jobOptions.file = new File({p});\ntry {{ app.activeDocument.print(o); vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}" + ), + ); + assert!(log[0].as_str().unwrap().contains(crate::script::files::OPEN_FOR_WRITING), "{log}"); + assert_eq!(std::fs::read_to_string(dir.join("x.pdf")).unwrap(), "pending", "the File's own bytes"); + let _ = std::fs::remove_dir_all(base); +} + +/// One assigned scale factor leaves the other at the document's saved value. +#[test] +fn one_assigned_scale_factor_keeps_the_saved_other() { + let base = folder("scale"); + let mut s = session(&base); + let common = json!({"media": "letter", "autoRotate": false, "orientation": "portrait", "artboards": "range", "range": "1"}); + let mut saved = common.clone(); + saved["scale"] = json!({"width": 100, "height": 500, "linked": false}); + s.execute("print.setup", &json!({"settings": saved})).unwrap(); + let dir = data_folder(&mut s, &base); + let mut expected = common; + expected["scaling"] = json!("tileFull"); + expected["scale"] = json!({"width": 400, "height": 500, "linked": false}); + let want = s.execute("file.print", &json!({"settings": expected, "path": dir.join("want.pdf").to_string_lossy()})).unwrap(); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});\n\ + o.coordinateOptions.horizontalScale = 400; o.coordinateOptions.tiling = PrintTiling.TILEFULLPAGES;\n\ + app.activeDocument.print(o);", + quoted(&dir.join("got.pdf")) + ), + ); + let got = pages(&dir.join("got.pdf")); + assert_eq!(got.len() as u64, want["pages"].as_u64().unwrap(), "the saved vertical scale of 500% is kept"); + assert!(got.len() >= 4, "1200 by 1000 pt of art tiles over at least four letter pages: {got:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// Artboard ranges the document does not hold and preset names that are not presets, such as +/// paths, throw before anything is written. +#[test] +fn print_refuses_ranges_and_preset_names_it_cannot_honor() { + let base = folder("names"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf"))); + let cases = [ + ("j.printAllArtboards = false; j.artboardRange = '3';", "RangeError", "artboardRange: range `3`"), + ("j.printAllArtboards = false; j.artboardRange = '0-1';", "RangeError", "artboardRange"), + ("j.printAllArtboards = false; j.artboardRange = '../../outside';", "RangeError", "artboardRange"), + ("j.printAllArtboards = false; j.artboardRange = '2-1';", "RangeError", "artboardRange"), + ("j.artboardRange = '3';", "RangeError", "artboardRange: range `3`"), + ("o.printPreset = 'Office';", "Error", "printPreset names no print preset: Office"), + (&format!("o.printPreset = {};", quoted(&base.join("settings/Script Grants.json"))), "Error", "printPreset names no print preset"), + ("o.printPreset = '../../preset';", "Error", "printPreset names no print preset"), + ("o.flattenerPreset = '/etc/passwd';", "Error", "flattenerPreset names no flattener preset"), + (&format!("o.flattenerPreset = {};", quoted(&base.join("outside/f.xml"))), "Error", "flattenerPreset names no flattener preset"), + ]; + let prefix = format!("Folder.userData; var o = new PrintOptions(), j = o.jobOptions; {file}"); + for (case, kind, part) in cases { + let e = failure(&mut s, &base, &format!("{prefix} {case} app.activeDocument.print(o);")); + assert!(e.contains(kind) && e.contains(part), "{case}: {e}"); + } + assert!(!dir.join("x.pdf").exists(), "nothing printed"); + // The names the lists give print, in any case. + logged(&mut s, &base, &format!("{prefix} o.printPreset = '[default]'; o.flattenerPreset = 'high resolution'; app.activeDocument.print(o);")); + assert!(dir.join("x.pdf").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// A color profile, a paper or a preset name that is empty, path-shaped, holds a control character +/// or is not on its list throws before anything is written; a listed name in any case prints. +#[test] +fn print_refuses_profile_paper_and_blank_preset_names() { + let base = folder("profile-paper"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf"))); + let profile = "PrintColorManagementOptions.name names no color profile"; + let paper = "PrintPaperOptions.name names no paper"; + let cases = [ + ("c.name = '../sRGB IEC61966-2.1';", profile), + ("c.name = 'C:/Windows/System32/spool/drivers/color/sRGB IEC61966-2.1';", profile), + ("c.name = '\\\\\\\\server\\\\share\\\\cmyk.icc';", profile), + ("c.name = 'No Such Profile';", profile), + ("c.colorProfileMode = PrintColorProfile.SOURCEPROFILE; c.name = '../cmyk.icc';", profile), + ("c.name = ' ';", "PrintColorManagementOptions.name must name a color profile"), + ("p.name = '../letter';", paper), + ("p.name = 'let\\u0007ter';", paper), + ("p.name = 'Office Tray 2';", paper), + ("p.name = '';", "PrintPaperOptions.name must name a paper"), + ("p.name = 'a4'; p.width = 300;", "PrintPaperOptions.width and height apply only to custom paper, not a4"), + ("o.flattenerPreset = ' ';", "PrintOptions.flattenerPreset must name a flattener preset"), + ("o.flattenerPreset = '';", "PrintOptions.flattenerPreset must name a flattener preset"), + ("o.printPreset = ' ';", "PrintOptions.printPreset must name a print preset"), + ]; + let prefix = format!("Folder.userData; var o = new PrintOptions(), j = o.jobOptions, c = o.colorManagementOptions, p = o.paperOptions; {file}"); + for (case, part) in cases { + let e = failure(&mut s, &base, &format!("{prefix} {case} app.activeDocument.print(o);")); + assert!(e.contains(part), "{case}: {e}"); + } + assert!(!dir.join("x.pdf").exists(), "nothing printed"); + // Listed names print in any case and with spaces around them. + logged( + &mut s, + &base, + &format!( + "{prefix} c.colorProfileMode = PrintColorProfile.CUSTOMPROFILE; c.name = 'srgb iec61966-2.1'; p.name = ' A4 ';\n\ + o.printPreset = ' [Default] '; o.flattenerPreset = ' High Resolution '; app.activeDocument.print(o);" + ), + ); + let sizes = pages(&dir.join("x.pdf")); + assert!(!sizes.is_empty() && sizes.iter().all(|&(w, h)| [(595.0, 842.0), (842.0, 595.0)].contains(&(w, h))), "A4: {sizes:?}"); + // A custom paper takes the assigned size. + let custom = format!( + "Folder.userData; var o = new PrintOptions(), p = o.paperOptions; o.jobOptions.file = new File({});\n\ + p.name = 'Custom'; p.width = 360; p.height = 504; o.coordinateOptions.orientation = PrintOrientation.PORTRAIT;\n\ + app.activeDocument.print(o);", + quoted(&dir.join("custom.pdf")) + ); + logged(&mut s, &base, &custom); + let sizes = pages(&dir.join("custom.pdf")); + assert!(!sizes.is_empty() && sizes.iter().all(|&size| size == (360.0, 504.0)), "custom: {sizes:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// Each warning `file.print` gives goes to the Script Console. +#[test] +fn print_writes_its_warnings_to_the_script_console() { + let base = folder("warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let settings = json!({"color": {"profile": "sRGB IEC61966-2.1"}}); + let want = + s.execute("file.print", &json!({"format": "postscript", "settings": settings, "path": dir.join("want.ps").to_string_lossy()})).unwrap(); + let warnings: Vec = want["warnings"].as_array().unwrap().iter().map(|w| format!("Document.print: {}", w.as_str().unwrap())).collect(); + assert!(warnings.iter().any(|w| w.contains("printer profile")), "{want}"); + let report = run( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});\n\ + o.colorManagementOptions.name = 'sRGB IEC61966-2.1'; o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL3;\n\ + app.activeDocument.print(o);", + quoted(&dir.join("got.ps")) + ), + ) + .unwrap(); + assert_eq!(report["console"]["lines"], json!(warnings)); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn option_objects_are_bounded_and_go_stale_after_their_run() { + let base = folder("bounds"); + let mut s = session(&base); + let e = failure(&mut s, &base, "for (var i = 0; i < 1000; i++) new PrintJobOptions();"); + assert!(e.contains("RangeError") && e.contains("at most 256 print option objects"), "{e}"); + let e = failure(&mut s, &base, "var o = new PrintOptions(); for (var i = 0; i < 1000; i++) o.jobOptions = new PrintJobOptions();"); + assert!(e.contains("at most 256"), "{e}"); + // A named engine keeps its globals, but an option object from an earlier run is stale. + run(&mut s, &base, "#targetengine keep\nvar held = new PrintOptions();").unwrap(); + let e = failure(&mut s, &base, "#targetengine keep\nnew PrintOptions(); held.printPreset;"); + assert!(e.contains("Stale print options"), "{e}"); + let e = failure(&mut s, &base, "#targetengine keep\napp.activeDocument.print(held);"); + assert!(e.contains("Stale print options"), "{e}"); + let e = failure(&mut s, &base, "#targetengine keep\nvar o = new PrintOptions(); o.jobOptions = held.jobOptions;"); + assert!(e.contains("Stale print options"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index e46fd9f77d..a80697343d 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -49,9 +49,9 @@ impl Classes { } } -/// The one key of the [`crate::Data`] object that stands for a `File` given to a member of a host -/// class ([`crate::HostClass`]), with the file's path in the host's platform form as its value. A -/// plain object a script made that carries the key is refused. +/// The one key of the [`crate::Data`] object that stands for a `File` given to or by a member of a +/// host class ([`crate::HostClass`]), with the file's path in the host's platform form as its value. +/// A plain object a script made that carries the key is refused. pub const FILE_REF_KEY: &str = "\u{0}fileRef"; /// The path of the `File` that `d` stands for ([`FILE_REF_KEY`]). @@ -78,6 +78,12 @@ impl Interp { _ => None, }) } + + /// A new `File` for `path`, the path a [`file_ref_path`] value a host function gives back holds. + pub(crate) fn write_file_ref(&mut self, path: &str) -> JsResult { + let Some(proto) = self.files.as_ref().map(|c| c.file_proto) else { return Err(self.type_error("File is not available")) }; + instance(self, proto, Value::str(path)) + } } /// The path of `o` when the `File` or `Folder` class made it. diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index a639dbd0cb..0dc2a9570a 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -362,6 +362,12 @@ impl Interp { Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, _)] if k == crate::HOST_REF_KEY) => { self.write_host_ref(&Data::Object(items))? } + Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, Data::String(_))] if k == crate::FILE_REF_KEY) => { + match items.into_iter().next() { + Some((_, Data::String(path))) => self.write_file_ref(&path)?, + _ => Value::Undefined, + } + } Data::Object(items) => self.write_container(items.into_iter().map(|(k, d)| (Slot::Name(k), d)).collect(), false, depth, frozen)?, }) } diff --git a/docs/mcp.md b/docs/mcp.md index acb6c3317f..93dac91b5c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2719,6 +2719,47 @@ app through the global object `vc`, and writes to the Script Console and runs ot an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`; properties the help pages do not list are left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default keeps the preset's value. A bad value throws an error before anything is written. +- `Document.print(options?)` runs `file.print` on the document, with the options a script assigned over the + document's print settings, which stay as they are, and adds no undo step + (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/). + `options` is a `new PrintOptions()`, whose `jobOptions`, `colorManagementOptions`, `colorSeparationOptions`, + `coordinateOptions`, `flattenerOptions`, `fontOptions`, `pageMarksOptions`, `paperOptions` and `postScriptOptions` + are `new PrintJobOptions()`, `new PrintColorManagementOptions()`, `new PrintColorSeparationOptions()`, + `new PrintCoordinateOptions()`, `new PrintFlattenerOptions()`, `new PrintFontOptions()`, + `new PrintPageMarksOptions()`, `new PrintPaperOptions()` and `new PrintPostScriptOptions()` + (https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ and the pages beside it). Each property reads as + its help page's default until it is assigned, and a `PrintOptions` holds its option objects by reference, so a change + made after the assignment is printed. `print` maps `printPreset` (a print preset's name) and `flattenerPreset`; + `copies` (1 to 999), `collate`, `reversePages`, `designation`, `printAllArtboards`, `artboardRange`, + `printAsBitmap` and `file` of the job; `colorProfileMode` (`SOURCEPROFILE` and `CUSTOMPROFILE`), `intent` and + `name` (an RGB or CMYK profile) of color management; `colorSeparationMode` (`COMPOSITE` and + `HOSTBASEDSEPARATION`), `convertSpotColors` and `overPrintBlack`; `emulsion`, `fitToPage`, `horizontalScale` and + `verticalScale` (1 to 1000), `orientation`, `position` and `tiling`; `overprint` of the flattener; `colorBars`, + `pageInfoMarks`, `registrationMarks`, `trimMarks`, `pageMarksType` and `trimMarksWeight`; `name`, `width`, + `height` and `transverse` of the paper; and `negativePrinting` and `postScriptLevel` (`PSLEVEL2` and `PSLEVEL3`). + `app.printPresetsList` gives the print presets' names, `[Default]` first, and `app.PPDFileList` is empty. + The enumerations `PrintColorProfile`, `PrintColorIntent`, `PrintColorSeparationMode`, `PrintOrientation`, + `PrintPosition`, `PrintTiling`, `PrintArtworkDesignation`, `PrintingBounds`, `PrintFontDownloadMode`, + `FontSubstitutionPolicy`, `PageMarksTypes`, `PostScriptImageCompressionType` and `PrinterPostScriptLevelEnum` hold + strings such as `"PrintTiling.TILEFULLPAGES"`. VectorCraft's own rules: `print` writes the file `jobOptions.file` + names, checked as `saveAs` checks its file: PostScript when the name ends with `.ps` or `postScriptLevel` is + assigned, a print-ready PDF otherwise. Without a file it throws `Printing to a printer is not available to scripts + yet`, and `app.printerList` throws an error that says it is not available yet. `fitToPage` set to true wins over + the scale factors and the tiling mode. With `printAllArtboards` false, `artboardRange` picks the artboards, and + without a range every artboard prints. With one of `horizontalScale` and `verticalScale` assigned, the other keeps + the document's saved value. `print` throws before anything is written when an assigned `artboardRange` names an + artboard the document does not have, also with `printAllArtboards` true, when `printPreset` or `flattenerPreset` + is not a preset's name (any case), when `colorManagementOptions.name` is not an RGB or CMYK profile's name (any + case), when `paperOptions.name` is not a paper `file.print` knows, or when it names a paper other than `custom` + and `width` or `height` is assigned above 0. An assigned name that is empty or only + spaces, or holds `/`, `\` or a control character, throws too, and each checked name is sent without the spaces + around it. `printerName` and `PPDName` take only `""`. A listed option that is not mapped, or a value that is not mapped such as + `PrintingBounds.ARTWORKBOUNDS`, `INRIPSEPARATION`, `PSLEVEL1` or a scale above 1000, throws an error that says it + is not available yet. Each value is checked when it is assigned: a wrong type, a number that is not finite or is + out of range, a string longer than 4,096 bytes, an option object of the wrong class or from an earlier run, and a + path given as a string all throw. A run makes at most 256 option objects. Each warning `file.print` gives goes to + the Script Console as a line that starts with `Document.print: `. `vc.run` still cannot run `file.print` or + `print.*`. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0f5208319d..4ca0ab994b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,6 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. + - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets. Printing to a printer from a script and `app.printerList` are not available yet (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From b965a3ef1f86cedac66bfda94af4d0df6dbcaad9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:51:08 -0800 Subject: [PATCH 02/72] Scripts: Document.print sends to a printer after the run and the person's approval, and app.printerList lists printers Document.print without jobOptions.file now prints to the printer that PrintOptions.printerName names, or to the default printer. A run started in the app gets a bounded list of the print service's printer names (at most 256, names up to 512 bytes, no control characters), and app.printerList gives a Printer object for each. A name must match a listed printer exactly. print composes each job as a print-ready PDF and holds it until the run ends. When the run's changes are kept, a dialog lists each job's document, printer and pages, and only the person at the keyboard can choose Print: ui.dialog.confirm and synthetic input are refused. Cancel drops the jobs. A failed or stopped run sends nothing, and no job is sent if one of its printers is no longer installed. A run prepares at most 4 jobs, 100 pages and 32 MiB, and pages are counted before a job is composed. The web, MCP and the command line cannot print to a printer from a script. Docs: docs/mcp.md, docs/target-app-parity.md. --- apps/vectorcraft/src/printing.rs | 3 + crates/engine/src/lib.rs | 6 + crates/engine/src/script/dom.rs | 13 +- crates/engine/src/script/dom/print.rs | 238 +++++++++++++++++++---- crates/engine/src/script/mod.rs | 46 ++++- crates/engine/src/script/printing.rs | 85 ++++++++ crates/engine/src/session/documents.rs | 2 + crates/engine/src/tests/script_print.rs | 183 ++++++++++++++++- crates/ui-egui/src/app/commands.rs | 2 +- crates/ui-egui/src/dialogs.rs | 4 + crates/ui-egui/src/dialogs/script_run.rs | 83 ++++++++ crates/ui-egui/src/print.rs | 76 ++++++++ crates/ui-egui/src/script_runs.rs | 4 + crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/script_print.rs | 176 +++++++++++++++++ docs/mcp.md | 28 ++- docs/target-app-parity.md | 3 +- 17 files changed, 902 insertions(+), 51 deletions(-) create mode 100644 crates/engine/src/script/printing.rs create mode 100644 crates/ui-egui/src/tests/script_print.rs diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index a5d450b854..d23a600d7b 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -28,6 +28,9 @@ impl PrintService for SystemPrint { fn setup(&mut self, printer: Option<&str>) -> Result<(), String> { system::setup(printer) } + fn scripts_may_print(&self) -> bool { + true + } } /// The status after the job `title` went to `printer` (the default one without a name), with the diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 0a29bb2cc7..c2cf8b194b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -315,6 +315,12 @@ pub struct Session { /// [`script::refused_to_scripts`] while it is set: `file.print` for `Document.print`, after the /// member checked its options and its file. pub(crate) script_unfenced: Option<&'static str>, + /// The printers the frontend lists for the next run, which takes them: `app.printerList` and + /// `Document.print` to a printer read them. `None`: scripts cannot print to a printer here. + pub script_printers: Option, + /// The jobs the last run that printed to a printer prepared, until the frontend takes them + /// ([`Session::take_script_prints`]). + pub(crate) script_prints: Vec, /// Write recovery copies of the unsaved documents before a run, and don't start without them. pub script_copy_first: bool, /// While the active tool's actions run: their commands aren't "a command from outside the diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 278ed1eb1b..b44fec0020 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -35,7 +35,7 @@ use serde_json::{Value, json}; use vectorcraft_geom::{Point, Rect}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts}; -use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; +use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; mod print; @@ -106,6 +106,17 @@ impl State { pub(super) fn saving(&self) -> bool { self.saving.get() } + + /// Gives the run the printers the frontend listed (`None`: none can be printed to here), and + /// whether jobs an earlier run prepared still wait. + pub(super) fn start_printing(&self, printers: Option, waiting: bool) { + self.printing.start(printers, waiting); + } + + /// The jobs the run prepared for a printer, which the run no longer holds. + pub(super) fn take_prints(&self) -> Vec { + self.printing.take_jobs() + } } /// Runs `f`, whose commands are kept together or put back together: when `f` fails, every diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index c2acec376e..23c84e45b3 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -18,10 +18,17 @@ //! into `file.print`'s settings before anything is written. //! //! VectorCraft's own rules, which the help pages do not state: -//! - `print` writes a file: `jobOptions.file` names it, a `File` the script may write -//! ([`super::super::files`]). PostScript is written when the name ends with `.ps` or -//! `postScriptOptions.postScriptLevel` is set, a print-ready PDF otherwise. Printing to a printer -//! from a script is not available yet, so `print` without a file throws an error. +//! - `print` with `jobOptions.file` writes a file, a `File` the script may write +//! ([`super::super::files`]), and `printerName` does not apply. PostScript is written when the +//! name ends with `.ps` or `postScriptOptions.postScriptLevel` is set, a print-ready PDF otherwise. +//! - `print` without a file prepares a job for the printer `printerName` names, or for the +//! system's default printer when it is empty or not assigned ([`super::super::printing`]): a +//! print-ready PDF composed when `print` is called, which the run keeps until it ends. A name +//! must be exactly the name of a printer the frontend listed for the run. Where the frontend lists +//! no printers for scripts (the web, a run without the app), `print` without a file throws. A run +//! prepares at most [`MAX_JOBS`] jobs, of at most [`MAX_SHEETS`] sheets and [`MAX_JOB_BYTES`] +//! together, and none while jobs of an earlier run still wait. A job for a printer is a PDF, so +//! `postScriptLevel` applies only to a file. //! - Only the properties a script assigned apply; the others keep the document's print settings //! (`print.setup`), which `print` leaves as they are. A property that was not assigned reads as //! the default its help page gives. @@ -38,23 +45,26 @@ //! the id or label of a paper `file.print` knows, or names a paper other than `custom` while //! `width` or `height` is assigned above 0. An assigned name that is empty or only spaces, //! or that holds `/`, `\` or a control character, throws too. Each checked name goes to -//! `file.print` without the spaces around it. `printerName` and `PPDName` take only the empty -//! string. +//! `file.print` without the spaces around it. `PPDName` takes only the empty string. //! - A run makes at most [`MAX_OPTION_OBJECTS`] option objects. -//! - `app.printerList` is not available yet, and `app.PPDFileList` is empty: VectorCraft prints -//! without PPD files. +//! - `app.printerList` lists the printers the frontend listed for the run as `Printer` objects, +//! whose `name` is read-only and whose `printerInfo` is not available yet. It throws with no +//! document open, as the help page +//! describes, and where the frontend lists no printers for scripts. `app.PPDFileList` is empty: +//! VectorCraft prints without PPD files. -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; use serde_json::{Map, Value, json}; use vectorcraft_color::cms; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, host_ref, host_ref_parts}; +use super::super::printing::{MAX_JOB_BYTES, MAX_JOBS, MAX_SHEETS, PreparedPrint, Printers}; use super::save_open::{exactly, file_path, plain, refused}; use super::{ - Answer, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, arg, command, current, float, get, given, later, method, named, num, on_doc, text, this_doc, - whole, with_doc, + Answer, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, arg, command, command_kept, current, float, get, given, later, method, named, num, on_doc, + text, this_doc, whole, with_doc, }; use crate::cmd::flatten::FlattenOptions; @@ -62,16 +72,44 @@ use crate::cmd::flatten::FlattenOptions; pub const MAX_OPTION_OBJECTS: usize = 256; /// The largest scale factor `file.print` takes, in percent. pub const MAX_PRINT_SCALE: f64 = 1000.0; -/// The error of `print` without `jobOptions.file`. -pub const NO_PRINTER: &str = "Printing to a printer is not available to scripts yet: set jobOptions.file to print to a file"; +/// The error of `print` without `jobOptions.file` where the frontend lists no printers for scripts. +pub const NO_PRINTER: &str = "Printing to a printer is not available here: set jobOptions.file to print to a file"; +/// The error of `app.printerList` where the frontend lists no printers for scripts. +pub const NO_PRINTERS: &str = "Application.printerList is not available here"; +/// The error of `app.printerList` with no document open. +pub const PRINTERS_NEED_DOCUMENT: &str = "Application.printerList needs an open document"; +/// The error of `print` to the default printer when the system names none. +pub const NO_DEFAULT_PRINTER: &str = "There is no default printer: set PrintOptions.printerName"; +/// The error of `print` to a printer while jobs an earlier run prepared wait. +pub const PRINT_WAITING: &str = "A print job from an earlier script still waits for approval"; +/// The error of `print` to a printer with `postScriptLevel` assigned. +pub const POSTSCRIPT_TO_FILE: &str = "PostScript prints only to a file: set jobOptions.file"; /// The error for an option object from an earlier run. pub const STALE_OPTIONS: &str = "Stale print options"; +/// The error for a `Printer` object from an earlier run. +pub const STALE_PRINTER: &str = "Stale printer"; /// The option objects of the run: each one's class, as an index into [`CLASSES`], and the -/// properties the script assigned. +/// properties the script assigned; the printers the frontend listed for the run, and the jobs the +/// run prepared for them. #[derive(Default)] pub(in crate::script) struct State { objects: RefCell>, + printers: RefCell>, + /// Jobs an earlier run prepared wait to be sent or dropped. + waiting: Cell, + jobs: RefCell>, +} + +impl State { + pub(in crate::script) fn start(&self, printers: Option, waiting: bool) { + *self.printers.borrow_mut() = printers; + self.waiting.set(waiting); + } + + pub(in crate::script) fn take_jobs(&self) -> Vec { + std::mem::take(&mut *self.jobs.borrow_mut()) + } } struct Options { @@ -209,7 +247,7 @@ const PRINT_OPTIONS: Class = Class { f("paperOptions", Kind::Child("PrintPaperOptions"), Start::None), f("postScriptOptions", Kind::Child("PrintPostScriptOptions"), Start::None), kept("PPDName", Kind::Text, Start::Text("")), - kept("printerName", Kind::Text, Start::Text("")), + f("printerName", Kind::Text, Start::Text("")), f("printPreset", Kind::Text, Start::None), ], }; @@ -485,6 +523,8 @@ fn property(link: &Link, class: usize, field: usize) -> HostMember { struct Job { preset: Option, file: Option, + /// The assigned `printerName`. + printer: Option, level: Option, /// The assigned `artboardRange`, checked whether or not it picks the artboards. range: Option, @@ -567,6 +607,7 @@ fn map_options(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<(), match k { "flattenerPreset" => job.flattener = Some(string_of(&v)), "printPreset" => job.preset = Some(string_of(&v)), + "printerName" => job.printer = Some(string_of(&v)), "jobOptions" => map_job(h, child_slot(h, &v, JOB.name)?, job), "colorManagementOptions" => map_color(h, child_slot(h, &v, COLOR.name)?, job), "colorSeparationOptions" => map_separation(h, child_slot(h, &v, SEPARATION.name)?, job), @@ -811,7 +852,8 @@ fn map_postscript(h: &Host, slot: usize, job: &mut Job) { } /// `document.print(options?)`: `file.print` of the document to the file `jobOptions.file` names, -/// with the assigned options over the document's print settings. +/// with the assigned options over the document's print settings, or without a file the job for a +/// printer ([`prepare`]). fn doc_print(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; let mut job = Job::default(); @@ -822,10 +864,36 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer { })?; map_options(h, slot, &mut job)?; } - let Some(file) = job.file.take() else { return Err(HostError::Error(NO_PRINTER.into())) }; + let Some(file) = job.file.take() else { return prepare(h, doc, job) }; check_names(h, doc, &mut job)?; let path = file_path(&file, "print")?; let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; + let mut p = print_params(&mut job); + p.insert("path".into(), json!(plain(real))); + let printed = exactly(h, || on_doc(h, doc.uid, false, |h| unfenced(h, PRINT, || command(h, PRINT, &Value::Object(p)))))?; + // What the job lost or how its options apply: one Script Console line each. + let warnings = match &printed { + Data::Object(fields) => fields.iter().find(|(k, _)| k == "warnings").map(|(_, v)| v), + _ => None, + }; + if let Some(Data::Array(warnings)) = warnings { + for w in warnings.iter().take(MAX_LISTED) { + if let Data::String(w) = w { + console_warning(h, w); + } + } + } + Ok(Data::Undefined) +} + +/// Writes `file.print`'s warning `w` to the Script Console. +fn console_warning(h: &Host, w: &str) { + super::super::each_line(&format!("Document.print: {w}"), |line, cut| h.line(super::super::console::Entry::Output(line), cut)); +} + +/// `file.print`'s params for `job`, without a path: the print preset, the PostScript level and the +/// settings. +fn print_params(job: &mut Job) -> Map { let mut p = Map::new(); if let Some(preset) = job.preset.take() { p.insert("preset".into(), json!(preset)); @@ -838,20 +906,67 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer { if !settings.is_empty() { p.insert("settings".into(), Value::Object(settings)); } - p.insert("path".into(), json!(plain(real))); - let printed = exactly(h, || on_doc(h, doc.uid, false, |h| unfenced(h, PRINT, &Value::Object(p))))?; - // What the job lost or how its options apply: one Script Console line each. - let warnings = match &printed { - Data::Object(fields) => fields.iter().find(|(k, _)| k == "warnings").map(|(_, v)| v), - _ => None, + p +} + +/// `document.print(options?)` without `jobOptions.file`: the job for the printer `printerName` +/// names, or for the system's default printer, as `file.print` composes it now. The run keeps it, +/// and the session takes it only when the run's changes are kept ([`super::super::printing`]). +/// Everything is checked before the job is composed, and its size after. +fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer { + let state = &h.dom.printing; + let (printer, for_printer) = { + let printers = state.printers.borrow(); + let Some(printers) = printers.as_ref() else { return Err(HostError::Error(NO_PRINTER.into())) }; + let printer = match job.printer.take().filter(|n| !n.is_empty()) { + Some(name) if printers.has(&name) => name, + Some(name) => return Err(HostError::Error(format!("PrintOptions.printerName names no installed printer: {name}"))), + None => printers.default_name().map(str::to_string).ok_or_else(|| HostError::Error(NO_DEFAULT_PRINTER.into()))?, + }; + (printer, printers.for_printer) }; - if let Some(Data::Array(warnings)) = warnings { - for w in warnings.iter().take(MAX_LISTED) { - if let Data::String(w) = w { - super::super::each_line(&format!("Document.print: {w}"), |line, cut| h.line(super::super::console::Entry::Output(line), cut)); - } + if state.waiting.get() { + return Err(HostError::Error(PRINT_WAITING.into())); + } + if job.level.is_some() { + return Err(HostError::Error(POSTSCRIPT_TO_FILE.into())); + } + let (count, sheets, bytes) = { + let jobs = state.jobs.borrow(); + (jobs.len(), jobs.iter().map(|j| j.sheets).sum::(), jobs.iter().map(|j| j.pdf.len()).sum::()) + }; + if count >= MAX_JOBS { + return Err(HostError::Range(format!("a script can print at most {MAX_JOBS} jobs to a printer in a run"))); + } + check_names(h, doc, &mut job)?; + let mut p = print_params(&mut job); + if for_printer { + p.insert("forPrinter".into(), json!(true)); + } + // The pages are counted from the layout before the job is composed. + let plan: serde_json::Map = + p.iter().filter(|(k, _)| matches!(k.as_str(), "preset" | "settings")).map(|(k, v)| (k.clone(), v.clone())).collect(); + let planned = on_doc(h, doc.uid, false, |h| unfenced(h, PREVIEW, || command_kept(h, PREVIEW, &Value::Object(plan))))?; + let pages = planned.get("pages").and_then(Value::as_u64).unwrap_or(0); + sheets_fit(sheets, pages)?; + let printed = on_doc(h, doc.uid, false, |h| unfenced(h, PRINT, || command_kept(h, PRINT, &Value::Object(p))))?; + let pdf = printed + .get("dataBase64") + .and_then(Value::as_str) + .and_then(vectorcraft_format::base64_decode) + .ok_or_else(|| HostError::Error("the print job has no data".into()))?; + let pages = printed.get("pages").and_then(Value::as_u64).unwrap_or(pages); + sheets_fit(sheets, pages)?; + if bytes.saturating_add(pdf.len()) > MAX_JOB_BYTES { + return Err(HostError::Range("a script's printer jobs can hold at most 32 MiB in a run".into())); + } + for w in printed.get("warnings").and_then(Value::as_array).into_iter().flatten().take(MAX_LISTED) { + if let Some(w) = w.as_str() { + console_warning(h, w); } } + let title = with_doc(h, doc, |_, st| st.title()); + state.jobs.borrow_mut().push(PreparedPrint { printer, title, pdf, sheets: pages }); Ok(Data::Undefined) } @@ -921,13 +1036,24 @@ fn plain_name<'a>(what: &str, kind: &str, name: &'a str) -> std::result::Result< Ok(n) } -const PRINT: &str = "file.print"; +/// The error when a job of `pages` sheets would take a run's jobs past [`MAX_SHEETS`], after +/// `sheets` in earlier jobs. +fn sheets_fit(sheets: u64, pages: u64) -> std::result::Result<(), HostError> { + if sheets.saturating_add(pages) > MAX_SHEETS { + return Err(HostError::Range(format!("a script's printer jobs can hold at most {MAX_SHEETS} sheets in a run; this job has {pages}"))); + } + Ok(()) +} -/// Runs `id`, which scripts may not run through `vc.run`, for a member that checked its params: -/// only `id` passes the fence, and only for this one command. -fn unfenced(h: &Host, id: &'static str, params: &Value) -> Answer { +const PRINT: &str = "file.print"; +/// Counts a job's pages without composing it. +const PREVIEW: &str = "print.preview"; + +/// Runs `run`, which runs `id`, a command scripts may not run through `vc.run`, for a member that +/// checked its params: only `id` passes the fence, and only while `run` runs. +fn unfenced(h: &Host, id: &'static str, run: impl FnOnce() -> std::result::Result) -> std::result::Result { h.session.borrow_mut().script_unfenced = Some(id); - let r = command(h, id, params); + let r = run(); h.session.borrow_mut().script_unfenced = None; r } @@ -942,11 +1068,39 @@ fn app_ppd_files(_: &Host, _: &[Data]) -> Answer { Ok(Data::Array(Vec::new())) } +/// `app.printerList`: a `Printer` for each printer the frontend listed for the run. +fn app_printers(h: &Host, _: &[Data]) -> Answer { + if h.session.borrow().active().is_none() { + return Err(HostError::Error(PRINTERS_NEED_DOCUMENT.into())); + } + let printers = h.dom.printing.printers.borrow(); + let printers = printers.as_ref().ok_or_else(|| HostError::Error(NO_PRINTERS.into()))?; + let count = u64::try_from(printers.names().len()).unwrap_or(0); + Ok(Data::Array((0..count).map(|i| host_ref(PRINTER, &[float(h.run), float(i)])).collect())) +} + +const PRINTER: &str = "Printer"; + +/// `printer.name`: the name the frontend listed for the printer. +fn printer_name(h: &Host, a: &[Data]) -> Answer { + let wrong = || HostError::Type("this is not a Printer".into()); + let (class, handle) = host_ref_parts(arg(a, 0)).ok_or_else(wrong)?; + if class != PRINTER { + return Err(wrong()); + } + let [run, index] = handle.as_slice() else { return Err(wrong()) }; + let stale = || HostError::Error(STALE_PRINTER.into()); + if whole(*run) != Some(h.run) { + return Err(stale()); + } + let index = whole(*index).and_then(|i| usize::try_from(i).ok()).ok_or_else(stale)?; + let printers = h.dom.printing.printers.borrow(); + printers.as_ref().and_then(|p| p.names().get(index)).map(|n| text(n.clone())).ok_or_else(stale) +} + /// The members these add to `Application`. pub(super) fn application_members(l: &Link) -> Vec<(String, HostMember)> { - let mut members = named(vec![("printPresetsList", get(l, app_presets)), ("PPDFileList", get(l, app_ppd_files))]); - members.push(later(l, "Application", "printerList")); - members + named(vec![("printPresetsList", get(l, app_presets)), ("PPDFileList", get(l, app_ppd_files)), ("printerList", get(l, app_printers))]) } /// The members these add to `Document`. @@ -954,9 +1108,10 @@ pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { named(vec![("print", method(l, doc_print))]) } -/// The option classes: each `new Name()` gives a new option object with nothing assigned. +/// The option classes: each `new Name()` gives a new option object with nothing assigned. And +/// `Printer`, whose objects only `app.printerList` gives. pub(super) fn classes(link: &Link) -> Vec { - CLASSES + let mut classes: Vec = CLASSES .iter() .enumerate() .map(|(index, c)| { @@ -970,5 +1125,10 @@ pub(super) fn classes(link: &Link) -> Vec { members.extend(c.fields.iter().enumerate().map(|(i, field)| (field.name.to_string(), property(link, index, i)))); HostClass { name: c.name.into(), parent: None, members, index: None, construct: Some(construct) } }) - .collect() + .collect(); + let mut printer = named(vec![("name", get(link, printer_name))]); + printer.insert(0, ("typename".to_string(), super::typename_of(PRINTER))); + printer.push(later(link, PRINTER, "printerInfo")); + classes.push(HostClass { name: PRINTER.into(), parent: None, members: printer, index: None, construct: None }); + classes } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..8d12c6b6d3 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -47,12 +47,17 @@ //! run. An engine keeps no document and no run: its host functions reach the run through a link //! that holds the run's host only while the run goes on. An error, a limit or a stop puts the //! documents back and keeps the engine's globals; an internal error drops the engine. +//! +//! `Document.print` to a printer prepares its job in memory; the session holds the jobs of a run +//! only after the run's changes are kept, for the frontend to send once the person approves them +//! ([`printing`]). pub mod console; pub mod dialogs; pub mod dollar; pub mod dom; pub mod include; +pub mod printing; pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog}; @@ -1309,6 +1314,17 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result std::result::Result<(Data, Value), HostError> { + command_crossing(host, id, params, true).map(|(data, value)| (data.unwrap_or(Data::Undefined), value)) +} + +/// [`command`] for a member that keeps the command's result itself: the result does not cross to +/// the script, so it is not held to the limits of a crossing. → the result as the command gave it. +fn command_kept(host: &Host, id: &str, params: &Value) -> std::result::Result { + command_crossing(host, id, params, false).map(|(_, value)| value) +} + +/// [`command_value`], with the script's copy of the result made only when `cross` is true. +fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::result::Result<(Option, Value), HostError> { let id = id.to_string(); let params = params.clone(); let session = host.session.clone(); @@ -1332,10 +1348,13 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( Err(e) => return Err(HostError::Error(e.to_string())), }; let crossed = host.charge_growth(objects, added).and_then(|()| { + if !cross { + return Ok(None); + } let data = to_data(&value, &result_limits(), 0, &mut (0, 0)) .map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?; host.charge_call(data_size(&data))?; - Ok(data) + Ok(Some(data)) }); // A command whose result does not reach the script is put back, like one that failed. if let Some(save) = save { @@ -1786,6 +1805,22 @@ impl Session { self.script_report.as_ref() } + /// Whether jobs a run prepared for a printer wait to be sent or dropped ([`printing`]). + pub fn script_prints_waiting(&self) -> bool { + !self.script_prints.is_empty() + } + + /// The jobs that wait, as [`Self::take_script_prints`] would give them. + pub fn script_prints(&self) -> &[printing::PreparedPrint] { + &self.script_prints + } + + /// The jobs the last run that printed to a printer prepared, which the session no longer holds: + /// the frontend sends them or drops them ([`printing`]). + pub fn take_script_prints(&mut self) -> Vec { + std::mem::take(&mut self.script_prints) + } + /// The Script Console: the lines of this session's runs, oldest first. pub fn script_console(&self) -> &console::Console { &self.script_console @@ -2066,6 +2101,9 @@ impl Session { args: RefCell::new((Data::Undefined, 0)), dom: dom::State::default(), }); + // The printers the frontend listed are this run's alone, and a run may not print while + // jobs an earlier run prepared still wait for the person. + host.dom.start_printing(self.script_printers.take(), !self.script_prints.is_empty()); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { Ok(args) => args, @@ -2290,6 +2328,12 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); + // The jobs it prepared for a printer wait for the frontend now that its changes are kept. + let prints = host.dom.take_prints(); + if !prints.is_empty() { + report["prints"] = json!(prints.len()); + self.script_prints = prints; + } close_run(self, host, &mut report, console::Ending::Finished); self.end_job(job, false); self.script_report = Some(report.clone()); diff --git a/crates/engine/src/script/printing.rs b/crates/engine/src/script/printing.rs new file mode 100644 index 0000000000..fd31e25a4c --- /dev/null +++ b/crates/engine/src/script/printing.rs @@ -0,0 +1,85 @@ +//! Printing to a printer from a script: the printers a frontend lists for a run ([`Printers`]), +//! which `app.printerList` and `PrintOptions.printerName` read, and the jobs `Document.print` +//! prepares ([`PreparedPrint`]). +//! +//! A run that prints to a printer sends nothing while it runs: each job is composed in memory and +//! kept with the run. When the run fails or is stopped, its jobs are dropped with its changes. When +//! it ends and its changes are kept, the session holds its jobs ([`crate::Session::take_script_prints`]) +//! for the frontend, which sends them only when the person at the computer approves them. +//! +//! A printer name is only a key into the list the frontend gave: it never becomes a path, a URL or +//! a command line. +//! +//! The limits are VectorCraft's own: [`MAX_PRINTERS`], [`MAX_PRINTER_NAME_BYTES`], [`MAX_JOBS`], +//! [`MAX_SHEETS`] and [`MAX_JOB_BYTES`]. + +/// The most printers a run lists. +pub const MAX_PRINTERS: usize = 256; +/// The longest printer name a run lists, in bytes. +pub const MAX_PRINTER_NAME_BYTES: usize = 512; +/// The most printer jobs one run prepares. +pub const MAX_JOBS: usize = 4; +/// The most sheets of paper the jobs of one run hold together, every copy counted. +pub const MAX_SHEETS: u64 = 100; +/// The most bytes the jobs of one run hold together. +pub const MAX_JOB_BYTES: usize = 32 << 20; + +/// The printers a frontend lists for a run, by name, with the system's default printer. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Printers { + names: Vec, + default: Option, + /// The printer turns no landscape page to fit its paper: jobs are written upright + /// (`file.print`'s `forPrinter`). + pub for_printer: bool, +} + +impl Printers { + /// The printers of `list` (name, whether it is the default), in its order. A name that is + /// empty, longer than [`MAX_PRINTER_NAME_BYTES`], holds a control character or repeats an + /// earlier one is left out, and so is every printer after the first [`MAX_PRINTERS`]. + pub fn new(list: impl IntoIterator, for_printer: bool) -> Self { + let mut names: Vec = Vec::new(); + let mut default = None; + for (name, is_default) in list { + if names.len() >= MAX_PRINTERS { + break; + } + if name.is_empty() || name.len() > MAX_PRINTER_NAME_BYTES || name.chars().any(char::is_control) || names.contains(&name) { + continue; + } + if is_default && default.is_none() { + default = Some(names.len()); + } + names.push(name); + } + Self { names, default, for_printer } + } + + /// The printers' names. + pub fn names(&self) -> &[String] { + &self.names + } + + /// The system's default printer, when the list holds it. + pub fn default_name(&self) -> Option<&str> { + self.default.map(|i| self.names[i].as_str()) + } + + /// Whether the list holds a printer named exactly `name`. + pub fn has(&self, name: &str) -> bool { + self.names.iter().any(|n| n == name) + } +} + +/// A job a run prepared for a printer: a print-ready PDF, every copy in it. +#[derive(Clone, Debug, PartialEq)] +pub struct PreparedPrint { + /// The printer, by the name the run's list gave it. + pub printer: String, + /// The title of the document it prints, the job's name in the print queue. + pub title: String, + pub pdf: Vec, + /// The sheets of paper it prints, every copy counted. + pub sheets: u64, +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 9a439f1437..526ab221db 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -167,6 +167,8 @@ impl Session { script_high_water: Default::default(), script_in_run: false, script_unfenced: None, + script_printers: None, + script_prints: Vec::new(), script_copy_first: cfg!(target_arch = "wasm32"), } } diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index 104687e0e3..5598bc3468 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -5,6 +5,7 @@ use std::path::{Path, PathBuf}; use serde_json::{Value, json}; +use crate::script::printing::{MAX_PRINTER_NAME_BYTES, MAX_PRINTERS, PreparedPrint, Printers}; use crate::*; const DENIED: &str = "Script file access denied"; @@ -111,6 +112,8 @@ fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() { let _ = std::fs::remove_dir_all(base); } +/// Without the printers a frontend lists for scripts (a run outside the app, the web), printing to +/// a printer and `app.printerList` throw, and nothing is prepared. #[test] fn print_without_a_file_does_not_print() { let base = folder("no-file"); @@ -119,12 +122,186 @@ fn print_without_a_file_does_not_print() { "app.activeDocument.print();", "app.activeDocument.print(new PrintOptions());", "var o = new PrintOptions(); o.jobOptions.copies = 2; app.activeDocument.print(o);", + "var o = new PrintOptions(); o.printerName = 'Office'; app.activeDocument.print(o);", ] { let e = failure(&mut s, &base, case); - assert!(e.contains("Printing to a printer is not available to scripts yet"), "{case}: {e}"); + assert!(e.contains("Printing to a printer is not available here"), "{case}: {e}"); } let e = failure(&mut s, &base, "app.printerList;"); - assert!(e.contains("Application.printerList is not available yet"), "{e}"); + assert!(e.contains("Application.printerList is not available here"), "{e}"); + assert!(!s.script_prints_waiting()); + let _ = std::fs::remove_dir_all(base); +} + +/// The printers a frontend lists, `Office` the default, with a name a shell or a file system would +/// read as more than a name. +const ODD_NAME: &str = "Lab; rm -rf / & \\\\srv\\q $(x) ../p"; + +fn printers() -> Printers { + Printers::new([("Office".to_string(), true), (ODD_NAME.to_string(), false)], false) +} + +/// The PDF pages a prepared job holds. +fn job_pages(job: &PreparedPrint) -> usize { + vectorcraft_pdf::info(&job.pdf, None).unwrap().pages.len() +} + +/// `app.printerList` gives a `Printer` for each printer the frontend listed, at most 256 of them, +/// without names that are empty, too long, hold a control character or repeat; the list is the +/// run's own, needs an open document, and its objects go stale after the run. +#[test] +fn printer_list_is_the_bounded_list_the_frontend_gave() { + let base = folder("printer-list"); + let mut s = session(&base); + let mut list: Vec<(String, bool)> = (0..300).map(|i| (format!("Printer {i}"), i == 1)).collect(); + list.insert(0, ("x".repeat(MAX_PRINTER_NAME_BYTES + 1), true)); + list.insert(1, ("Bad\nName".into(), false)); + list.insert(2, (String::new(), false)); + list.insert(3, ("Printer 5".into(), false)); + let snapshot = Printers::new(list, false); + assert_eq!(snapshot.names().len(), MAX_PRINTERS); + assert_eq!(snapshot.default_name(), Some("Printer 1")); + s.script_printers = Some(snapshot); + let out = logged( + &mut s, + &base, + "#targetengine keep\nvar l = app.printerList; held = l[0];\n\ + vc.log([l.length, l[0].name, l[0].typename, l[1].name, l[255].name]);\n\ + try { l[0].name = 'Other'; } catch (e) {} vc.log(l[0].name);\n\ + try { l[0].printerInfo; } catch (e) { vc.log(e.message); }", + ); + assert_eq!(out[0], json!([256, "Printer 5", "Printer", "Printer 0", "Printer 255"])); + assert_eq!(out[1], json!("Printer 5"), "name is read-only"); + assert_eq!(out[2], json!("Printer.printerInfo is not available yet")); + // The next run has no list unless the frontend gives one again. + let e = failure(&mut s, &base, "app.printerList;"); + assert!(e.contains("Application.printerList is not available here"), "{e}"); + s.script_printers = Some(printers()); + let e = failure(&mut s, &base, "#targetengine keep\nheld.name;"); + assert!(e.contains("Stale printer"), "{e}"); + s.script_printers = Some(printers()); + assert_eq!(logged(&mut s, &base, "vc.log(app.printerList[1].name);")[0], json!(ODD_NAME)); + // With no document open there is no list. + let mut empty = Session::new(); + empty.attach_script_data(base.join("settings/Script Data")); + empty.script_printers = Some(printers()); + let e = failure(&mut empty, &base, "app.printerList;"); + assert!(e.contains("Application.printerList needs an open document"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + +/// `print` without a file prepares a print-ready PDF for the printer it names, or the default one, +/// and sends nothing: the session holds the jobs once the run's changes are kept, for the frontend +/// to take. A name is matched exactly, whatever characters it holds. +#[test] +fn print_to_a_printer_holds_the_job_until_the_run_ends() { + let base = folder("prepared"); + let mut s = session(&base); + s.script_printers = Some(printers()); + let name = serde_json::to_string(ODD_NAME).unwrap(); + let report = run( + &mut s, + &base, + &format!( + "var o = new PrintOptions(); o.printerName = {name}; o.jobOptions.copies = 2; o.jobOptions.collate = true;\n\ + app.activeDocument.print(o);\n\ + vc.run('shape.rectangle', {{x: 150, y: 10, width: 20, height: 20}});\n\ + app.activeDocument.print();" + ), + ) + .unwrap(); + assert_eq!(report["prints"], 2, "{report}"); + assert!(s.script_prints_waiting()); + let title = s.active().unwrap().title(); + let jobs = s.take_script_prints(); + assert!(!s.script_prints_waiting()); + assert_eq!(jobs.len(), 2); + assert_eq!((jobs[0].printer.as_str(), jobs[0].sheets, job_pages(&jobs[0])), (ODD_NAME, 4, 4), "two artboards, two copies"); + assert_eq!((jobs[1].printer.as_str(), jobs[1].sheets, job_pages(&jobs[1])), ("Office", 2, 2), "the default printer"); + assert!(jobs.iter().all(|j| j.title == title && j.pdf.starts_with(b"%PDF"))); + assert_ne!(jobs[0].pdf, jobs[1].pdf, "each job holds the document as it was when print was called"); + assert!(s.take_script_prints().is_empty(), "a job is taken once"); + let _ = std::fs::remove_dir_all(base); +} + +/// A run that throws, runs out of fuel or ends at a failed command keeps no job. +#[test] +fn a_run_that_fails_keeps_no_print_job() { + let base = folder("rollback"); + let mut s = session(&base); + let objects = s.active().unwrap().doc.layers[0].children().map_or(0, Vec::len); + for case in [ + "app.activeDocument.print(); throw new Error('late');", + "app.activeDocument.print(); vc.run('no.such.command', {});", + "app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print();", + ] { + s.script_printers = Some(printers()); + failure(&mut s, &base, case); + assert!(!s.script_prints_waiting(), "{case}"); + } + s.script_printers = Some(printers()); + let stopped = s.execute("script.run", &json!({"source": "app.activeDocument.print(); while (true) {}", "name": "t.js", "maxFuel": 2_000_000})); + assert!(stopped.is_err()); + assert!(s.take_script_prints().is_empty()); + assert_eq!(s.active().unwrap().doc.layers[0].children().map_or(0, Vec::len), objects); + let _ = std::fs::remove_dir_all(base); +} + +/// A name that is not exactly a listed printer's, a list with no default, PostScript, more jobs or +/// sheets than a run may prepare and jobs an earlier run left waiting all throw, and nothing is +/// prepared; a file wins over a printer name. +#[test] +fn print_to_a_printer_refuses_what_it_cannot_send() { + let base = folder("refuse"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let cases = [ + ("o.printerName = 'office';", "PrintOptions.printerName names no installed printer: office"), + ("o.printerName = 'Offic';", "names no installed printer: Offic"), + ("o.printerName = ' Office';", "names no installed printer: Office"), + ("o.printerName = 'Office\\n';", "names no installed printer"), + ("o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2;", "PostScript prints only to a file"), + ("o.jobOptions.copies = 51;", "at most 100 sheets in a run; this job has 102"), + ("for (var i = 0; i < 4; i++) app.activeDocument.print(o);", "at most 4 jobs to a printer in a run"), + ("o.printPreset = 'Nope';", "printPreset names no print preset"), + ]; + for (case, part) in cases { + s.script_printers = Some(printers()); + let e = failure(&mut s, &base, &format!("var o = new PrintOptions(); {case} app.activeDocument.print(o);")); + assert!(e.contains(part), "{case}: {e}"); + assert!(!s.script_prints_waiting(), "{case}"); + } + // A job past the sheet limit is refused before it is composed. + s.script_printers = Some(printers()); + failure(&mut s, &base, "var o = new PrintOptions(); o.jobOptions.copies = 999; app.activeDocument.print(o);"); + let report = s.script_report().unwrap(); + let ran: Vec<&str> = report["slowestCommands"].as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).collect(); + assert_eq!(ran, ["print.preview"], "{report}"); + s.script_printers = Some(Printers::new([("Office".to_string(), false)], false)); + let e = failure(&mut s, &base, "app.activeDocument.print();"); + assert!(e.contains("There is no default printer: set PrintOptions.printerName"), "{e}"); + // Jobs an earlier run left waiting: the next run cannot print to a printer until they are taken. + s.script_printers = Some(printers()); + logged(&mut s, &base, "app.activeDocument.print();"); + s.script_printers = Some(printers()); + let e = failure(&mut s, &base, "app.activeDocument.print();"); + assert!(e.contains("A print job from an earlier script still waits for approval"), "{e}"); + assert_eq!(s.take_script_prints().len(), 1, "the earlier job is kept"); + s.script_printers = Some(printers()); + logged(&mut s, &base, "app.activeDocument.print();"); + assert_eq!(s.take_script_prints().len(), 1); + // A file wins over the printer name. + s.script_printers = Some(printers()); + let file = quoted(&dir.join("f.pdf")); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(); o.printerName = 'Nowhere'; o.jobOptions.file = new File({file}); app.activeDocument.print(o);" + ), + ); + assert!(dir.join("f.pdf").exists()); + assert!(!s.script_prints_waiting()); let _ = std::fs::remove_dir_all(base); } @@ -171,8 +348,6 @@ fn options_that_are_not_available_throw() { let dir = data_folder(&mut s, &base); let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf"))); let cases = [ - ("o.printerName = 'Office';", "PrintOptions.printerName is not available yet"), - ("o.printerName = '\\\\\\\\server\\\\share';", "PrintOptions.printerName is not available yet"), ("o.PPDName = 'Generic';", "PrintOptions.PPDName is not available yet"), ("o.PPDName = '/etc/cups/ppd/office.ppd';", "PrintOptions.PPDName is not available yet"), ("j.name = 'Job';", "PrintJobOptions.name is not available yet"), diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 042e8b37a5..4a4b1c2da2 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -247,7 +247,7 @@ impl VectorcraftApp { let ime_before = crate::ime::stamp(&mut self.session, ime_view); let cursor_settings = (self.session.caps_lock, self.session.prefs.use_precise_cursors); let spot_base = panels::color_guide::before_command(self); - let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string()); + let r = crate::print::execute_listing_printers(self, id, ¶ms); let r = panels::actions::after_recorded_command(self, r); if r.is_ok() && cursor_settings != (self.session.caps_lock, self.session.prefs.use_precise_cursors) { self.canvas.hover_cursor = None; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a24755ab12..669a8740ed 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -466,6 +466,7 @@ registry! { ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC, ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC, ScriptFiles: [script_run::PICKER_KIND] => script_run::PICKER_SPEC, + ScriptPrint: [script_run::PRINT_KIND] => script_run::PRINT_SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, ObjectMosaic: [object_mosaic::KIND] => object_mosaic::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, @@ -811,6 +812,9 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == script_run::PICKER_KIND { script_run::picker_cancel(app, &d); } + if d.kind == script_run::PRINT_KIND { + script_run::print_cancel(app, &d); + } missing_links::cancelled(app, &d); // Cancel discards Recolor Artwork's own history of color edits with them. if d.kind == recolor::KIND { diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index f8baa7b7de..6add1104b5 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -24,6 +24,13 @@ //! and the dialog's own fields change neither what it allows nor what it says it allows. Escape, //! `ui.dialog.cancel`, Enter, and OK or `ui.dialog.confirm` without an `answer` give Deny. //! `selectDlg` opens the host's folder picker in its own folder. +//! +//! The jobs a script prepared for a printer (`Document.print` without a file) wait for the dialog of +//! kind `scriptPrint`, which opens once the run has ended and its changes are kept, when no other +//! dialog is open. It lists each job's document, printer and sheets from the jobs themselves, which +//! no field changes. Only the person at the keyboard prints them, with Print: from +//! `ui.dialog.confirm` or synthetic input Print is refused and the dialog stays open. Cancel, +//! Escape and `ui.dialog.cancel` drop the jobs, from anyone; the script's changes stay either way. use serde_json::{Value, json}; use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; @@ -46,6 +53,18 @@ pub const CLOSE_KIND: &str = "scriptClose"; pub const NOTICE_KIND: &str = "scriptDialog"; /// The dialog kind of a script's file dialogs. pub const PICKER_KIND: &str = "scriptFiles"; +/// The dialog kind of the question before the jobs a script prepared for a printer are sent. +pub const PRINT_KIND: &str = "scriptPrint"; + +pub(super) const PRINT_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Print").into(), + body: print_body, + confirm: print_confirm, + ok: Some("Print"), + min_width: 420.0, + max_width: Some(560.0), + ..DialogSpec::FORM +}; pub(super) const PICKER_SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Script File Access").into(), @@ -546,3 +565,67 @@ fn answers_for(kind: &str) -> &'static str { _ => "ok, stop", } } + +/// Opens the question before the jobs a script prepared for a printer are sent, once the run has +/// ended and no other dialog is open. +pub(crate) fn ask_print(app: &mut VectorcraftApp) { + if app.ui.dialog.is_none() && !app.session.script_running() && app.session.script_prints_waiting() { + app.ui.dialog = Some(Dialog::new(PRINT_KIND, json!({}))); + } +} + +/// The jobs, read from the session, so `ui.dialog.set` cannot change what the person reads. +fn print_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, _: &mut Dialog) -> bool { + let t = Tokens::get(ui.ctx()); + ui.label(tl!("The script asks to print these jobs. Its changes to the documents are kept whether or not you print.")); + ui.add_space(8.0); + egui::ScrollArea::vertical().max_height(200.0).show(ui, |ui| { + egui::Grid::new("script-print-jobs").num_columns(3).spacing([16.0, 4.0]).show(ui, |ui| { + for head in [tl!("Document"), tl!("Printer"), tl!("Pages")] { + ui.label(egui::RichText::new(head).font(theme::semibold(12.0)).color(t.text)); + } + ui.end_row(); + for job in app.session.script_prints() { + ui.label(egui::RichText::new(shown_text(&job.title, false)).color(t.text_strong)); + ui.label(egui::RichText::new(shown_text(&job.printer, false)).color(t.text_strong)); + ui.label(egui::RichText::new(job.sheets.to_string()).color(t.text_strong)); + ui.end_row(); + } + }); + }); + false +} + +/// Print: sends the jobs, when the person at the keyboard asked. From automation (a control or MCP +/// request, or synthetic input) it is refused and the dialog stays open. +fn print_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result { + if app.automation_asked() { + return Err(PRINT_BY_PERSON.into()); + } + close_print(app); + let jobs = app.session.take_script_prints(); + if jobs.is_empty() { + return Ok(Value::Null); + } + // The dialog is closed and the jobs are taken: a failure is reported in the status bar. + crate::print::send_script_prints(app, jobs).inspect_err(|e| app.status(e.clone())) +} + +/// Cancel or Escape, from anyone: the jobs are dropped. +pub(super) fn print_cancel(app: &mut VectorcraftApp, _: &Dialog) { + close_print(app); + if !app.session.take_script_prints().is_empty() { + app.status(PRINTS_DROPPED); + } +} + +fn close_print(app: &mut VectorcraftApp) { + if app.ui.dialog.as_ref().is_some_and(|open| open.kind == PRINT_KIND) { + app.ui.dialog = None; + } +} + +/// Print's error when automation asked. +pub(crate) const PRINT_BY_PERSON: &str = "Only the person at the keyboard can print a script's print jobs"; +/// The status after Cancel. +pub(crate) const PRINTS_DROPPED: &str = "The script's print jobs were not sent"; diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 6c94e0cad8..48d857a504 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -4,10 +4,16 @@ //! it, or saves the PDF when asked to (`toFile`, `path`) or when there is no print service; a //! PostScript file (`format: "postscript"`, or a `.ps` path) is always saved. `print.printers` //! lists the printers. +//! +//! A script run started in the app gets the printers of a service that lets scripts print +//! ([`PrintService::scripts_may_print`], the desktop's), as names only. The jobs a script prepares +//! for them are sent after the run's changes are kept and the person approves them +//! ([`crate::dialogs::script_run::PRINT_KIND`], [`send_script_prints`]). use serde::Serialize; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio; +use vectorcraft_engine::script::printing::{PreparedPrint, Printers}; use crate::{VectorcraftApp, io}; @@ -55,6 +61,11 @@ pub trait PrintService { fn has_setup(&self) -> bool { false } + /// Whether scripts may list this service's printers and send jobs to them once the person + /// approves them. The browser's print dialog picks its own printer, so the web's does not. + fn scripts_may_print(&self) -> bool { + false + } /// Setup…: open the system's settings of `printer` (`None`: the printers). fn setup(&mut self, _printer: Option<&str>) -> Result<(), String> { Err("there are no printer settings to open here".into()) @@ -67,6 +78,71 @@ pub fn printers(app: &mut VectorcraftApp) -> Value { json!({ "printers": printers, "service": app.services.print.is_some(), "setup": setup }) } +/// The printers a script run may print to: the print service's, by name, when it lets scripts +/// print; `None` otherwise. +pub fn script_printers(app: &mut VectorcraftApp) -> Option { + let service = app.services.print.as_mut().filter(|s| s.scripts_may_print())?; + let for_printer = !service.turns_landscape(); + Some(Printers::new(service.printers().into_iter().map(|p| (p.name, p.default)), for_printer)) +} + +/// Runs the engine command `id`. A `script.run` started here lists the printers it may print to +/// ([`script_printers`]), and only that run lists them. +pub(crate) fn execute_listing_printers(app: &mut VectorcraftApp, id: &str, params: &Value) -> Result { + if id == "script.run" { + app.session.script_printers = script_printers(app); + } + let r = app.session.execute(id, params).map_err(|e| e.to_string()); + app.session.script_printers = None; + r +} + +/// The error for a script's jobs when the print service does not let scripts print. +const NO_SCRIPT_PRINTING: &str = "Printing from scripts is not available here: the script's print jobs were not sent"; + +/// Sends the jobs a script prepared, which the person approved, each to its printer. Every printer +/// must still be one the service lists, by its exact name, or no job is sent. → `{sent}`, or +/// `{background: true}` while the desktop's worker sends them. +pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec) -> Result { + let service = app.services.print.as_mut().filter(|s| s.scripts_may_print()).ok_or(NO_SCRIPT_PRINTING)?; + let listed: Vec = service.printers().into_iter().map(|p| p.name).collect(); + if let Some(gone) = jobs.iter().find(|j| !listed.contains(&j.printer)) { + return Err(format!("The printer {} is no longer installed: the script's print jobs were not sent", gone.printer)); + } + let count = jobs.len(); + if let Some(submit) = service.shared_print() { + return crate::background::run( + app, + true, + "Printing from a script".into(), + None, + move |_| send_each(&mut |job| submit(job), &jobs).map(|notes| json!({ "notes": notes })), + move |app, result| { + let notes = result?; + app.status(notes["notes"].as_array().and_then(|n| n.last()).and_then(Value::as_str).unwrap_or_default()); + Ok(json!({ "sent": count })) + }, + ); + } + let notes = send_each(&mut |job| service.print(job), &jobs)?; + app.status(notes.last().cloned().unwrap_or_default()); + Ok(json!({ "sent": count })) +} + +/// Gives each of `jobs` to `submit`, in order, stopping at the first that fails. → what each one +/// gave, or the error, which says how many were sent before it. +fn send_each(submit: &mut dyn FnMut(&PrintJob<'_>) -> 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 }) { + 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())), + } + } + Ok(notes) +} + /// `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 diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 7bc52f35b1..0dcedd5dce 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -2,6 +2,7 @@ //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with //! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer. +//! A run that prepared jobs for a printer ends with the question before they are sent. use serde_json::json; @@ -12,6 +13,7 @@ use crate::state::Dialog; /// Advances the running script by one slice, or asks what its growth needs asked. pub fn poll(app: &mut VectorcraftApp) { script_run::drain(app); + script_run::ask_print(app); if !app.session.script_running() { return; } @@ -39,6 +41,8 @@ pub fn poll(app: &mut VectorcraftApp) { if !crate::panels::actions::after_journaled_edit(app) { app.status(format!("Ran {name}")); } + // The jobs it prepared for a printer wait for the person's answer. + script_run::ask_print(app); } Err(e) => failed(app, e.to_string()), } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index e0619ddaf7..7e49b50c8d 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -42,6 +42,7 @@ mod screenmode; mod screenshots; mod script_check; mod script_dialogs; +mod script_print; mod script_run; mod scripts_menu; mod scrub; diff --git a/crates/ui-egui/src/tests/script_print.rs b/crates/ui-egui/src/tests/script_print.rs new file mode 100644 index 0000000000..094299d2bb --- /dev/null +++ b/crates/ui-egui/src/tests/script_print.rs @@ -0,0 +1,176 @@ +//! A script's jobs for a printer (`Document.print` without a file): the run lists the print +//! service's printers, and its jobs are sent after it ends, only when the person at the keyboard +//! approves them. + +use std::cell::RefCell; +use std::rc::Rc; + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use crate::dialogs::script_run::{PRINT_BY_PERSON, PRINT_KIND, PRINTS_DROPPED}; +use crate::print::{PrintJob, PrintService, Printer}; +use crate::{Services, VectorcraftApp, dialogs, menus, script_runs}; + +/// What the service was sent: (printer, title, bytes). +type Sent = Rc, String, Vec)>>>; + +/// A print service that records the jobs it is sent, with the printers `names` (the first one the +/// default), which lets scripts print when `scripts` is true. +struct Spool { + sent: Sent, + names: Rc>>, + scripts: bool, +} + +impl PrintService for Spool { + fn printers(&mut self) -> Vec { + self.names.borrow().iter().enumerate().map(|(i, name)| Printer { name: name.clone(), default: i == 0 }).collect() + } + + fn print(&mut self, job: &PrintJob) -> Result { + self.sent.borrow_mut().push((job.printer.map(str::to_string), job.title.to_string(), job.pdf.to_vec())); + Ok(format!("Sent to {}", job.printer.unwrap_or("the default printer"))) + } + + fn scripts_may_print(&self) -> bool { + self.scripts + } +} + +/// An app with a document, a print service listing Office (the default) and Lab, and no warning +/// before a script runs. +fn print_app(scripts: bool) -> (VectorcraftApp, Sent, Rc>>) { + let sent = Sent::default(); + let names = Rc::new(RefCell::new(vec!["Office".to_string(), "Lab".to_string()])); + let spool = Spool { sent: sent.clone(), names: names.clone(), scripts }; + let mut app = VectorcraftApp::new(Session::new(), Services { print: Some(Box::new(spool)), ..Default::default() }); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + (app, sent, names) +} + +fn objects(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +/// Runs `source` as File › Scripts › Other Script… runs it, to its end. +fn run(app: &mut VectorcraftApp, source: &str) { + menus::run_ui_command(app, "ui.runScript", &json!({ "source": source, "name": "p.js" })).unwrap().unwrap(); + for _ in 0..10_000 { + script_runs::poll(app); + if !app.session.script_running() { + return; + } + } + panic!("the script did not end"); +} + +const PRINT_TO_LAB: &str = + "var o = new PrintOptions(); o.printerName = 'Lab'; app.activeDocument.print(o); vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"; + +fn open_kind(app: &VectorcraftApp) -> Option<&str> { + app.ui.dialog.as_ref().map(|d| d.kind.as_str()) +} + +/// A control request, handled as the app handles one: while `answering_control` is set. +fn control(app: &mut VectorcraftApp, method: &str, params: Value) -> Value { + let (req, _) = crate::control::ControlRequest::new(method, params); + app.ui.answering_control = true; + let outcome = crate::control::handle(app, &egui::Context::default(), &req); + app.ui.answering_control = false; + let crate::control::Outcome::Done(r) = outcome else { panic!("expected an immediate reply") }; + r +} + +/// The job is sent after the run's changes are kept, once, and only when the person at the +/// keyboard approves it: Print from a control request or synthetic input is refused. +#[test] +fn a_scripts_print_job_is_sent_only_when_the_person_approves_it() { + let (mut app, sent, _) = print_app(true); + run(&mut app, PRINT_TO_LAB); + assert_eq!(objects(&app), 1, "the run's changes are kept"); + assert_eq!(open_kind(&app), Some(PRINT_KIND)); + assert!(sent.borrow().is_empty(), "nothing is sent before the person answers"); + let r = control(&mut app, "ui.dialog.confirm", json!({})); + assert_eq!(r["error"], PRINT_BY_PERSON, "{r}"); + app.synthetic_frame = true; + assert_eq!(dialogs::confirm(&mut app).unwrap_err(), PRINT_BY_PERSON); + app.synthetic_frame = false; + assert_eq!(open_kind(&app), Some(PRINT_KIND), "the question stays open"); + assert!(sent.borrow().is_empty()); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(open_kind(&app), None); + { + let sent = sent.borrow(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].0.as_deref(), Some("Lab")); + assert!(sent[0].2.starts_with(b"%PDF")); + } + assert_eq!(app.ui.status, "Sent to Lab"); + for _ in 0..5 { + script_runs::poll(&mut app); + } + assert_eq!(sent.borrow().len(), 1, "a job is sent once"); + assert_eq!(open_kind(&app), None); +} + +/// Cancel, from anyone, drops the jobs and keeps the run's changes. +#[test] +fn cancel_drops_a_scripts_print_jobs_and_keeps_its_changes() { + let (mut app, sent, _) = print_app(true); + run(&mut app, &format!("app.activeDocument.print(); {PRINT_TO_LAB}")); + assert_eq!(app.session.script_prints().len(), 2); + let r = control(&mut app, "ui.dialog.cancel", json!({})); + assert!(r.get("error").is_none_or(Value::is_null), "{r}"); + assert_eq!(open_kind(&app), None); + assert!(!app.session.script_prints_waiting()); + assert_eq!(app.ui.status, PRINTS_DROPPED); + script_runs::poll(&mut app); + assert_eq!(open_kind(&app), None, "the question does not come back"); + assert!(sent.borrow().is_empty()); + assert_eq!(objects(&app), 1); +} + +/// A run that fails asks nothing and sends nothing; a printer that went away before Print is +/// refused and no job is sent. +#[test] +fn a_failed_run_or_a_printer_that_went_away_sends_nothing() { + let (mut app, sent, names) = print_app(true); + run(&mut app, &format!("{PRINT_TO_LAB} throw new Error('late');")); + assert_eq!(open_kind(&app), None); + assert!(!app.session.script_prints_waiting()); + assert_eq!(objects(&app), 0); + run(&mut app, &format!("app.activeDocument.print(); {PRINT_TO_LAB}")); + assert_eq!(open_kind(&app), Some(PRINT_KIND)); + names.borrow_mut().retain(|n| n != "Lab"); + let e = dialogs::confirm(&mut app).unwrap_err(); + assert_eq!(e, "The printer Lab is no longer installed: the script's print jobs were not sent"); + assert_eq!(app.ui.status, e); + assert!(sent.borrow().is_empty(), "neither job is sent"); + assert_eq!(open_kind(&app), None); +} + +/// Without a service that lets scripts print (the web's), or without any, printing to a printer +/// from a script throws and nothing is asked or sent. +#[test] +fn a_script_cannot_print_to_a_printer_without_a_service_that_allows_it() { + let (mut app, sent, _) = print_app(false); + run(&mut app, PRINT_TO_LAB); + assert!(app.ui.status.contains("Printing to a printer is not available here"), "{}", app.ui.status); + assert_eq!(open_kind(&app), None); + assert!(sent.borrow().is_empty()); + let mut bare = VectorcraftApp::new(Session::new(), Services::default()); + bare.run("file.new", json!({})).unwrap(); + bare.session.prefs.show_external_script_warning = false; + run(&mut bare, "vc.log(app.printerList.length);"); + assert!(bare.ui.status.contains("Application.printerList is not available here"), "{}", bare.ui.status); + // A run the app started lists the service's printers; a later run without one does not. + let (mut app, _, _) = print_app(true); + run(&mut app, "var l = app.printerList; vc.log([l.length, l[0].name, l[1].name]);"); + assert_eq!(app.session.script_report().unwrap()["log"], json!([[2, "Office", "Lab"]])); + assert!(app.session.script_printers.is_none()); + // A run that does not start leaves no list behind for a later one. + assert!(app.run("script.run", json!({"source": "1", "path": "x.js"})).is_err()); + assert!(app.session.script_printers.is_none()); +} diff --git a/docs/mcp.md b/docs/mcp.md index 93dac91b5c..b2312d4d8b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2743,8 +2743,27 @@ app through the global object `vc`, and writes to the Script Console and runs ot `FontSubstitutionPolicy`, `PageMarksTypes`, `PostScriptImageCompressionType` and `PrinterPostScriptLevelEnum` hold strings such as `"PrintTiling.TILEFULLPAGES"`. VectorCraft's own rules: `print` writes the file `jobOptions.file` names, checked as `saveAs` checks its file: PostScript when the name ends with `.ps` or `postScriptLevel` is - assigned, a print-ready PDF otherwise. Without a file it throws `Printing to a printer is not available to scripts - yet`, and `app.printerList` throws an error that says it is not available yet. `fitToPage` set to true wins over + assigned, a print-ready PDF otherwise, and `printerName` does not apply. Without a file, `print` prints to the + printer `printerName` names, or to the system's default printer when it is `""` or not assigned + (https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/). The name must be exactly the name of a printer the + app listed for the run, or `print` throws `PrintOptions.printerName names no installed printer`; with no default + printer it throws `There is no default printer`. `print` composes the job as a print-ready PDF when it is called + and sends nothing while the run goes on. When the run ends and its changes are kept, the app asks before it sends + the jobs (dialog kind `scriptPrint`, listing each job's document, printer and pages). Only the person at the + keyboard can choose Print: `ui.dialog.confirm` and synthetic input are refused, and the dialog stays open. Cancel, + Escape and `ui.dialog.cancel` drop the jobs and keep the run's changes. A run that fails or is stopped sends + nothing. Before it sends them, the app checks that each printer is still installed under that name, and sends none + when one is not. A run prepares at most 4 jobs, together at most 100 pages, every copy counted, and 32 MiB, and + none while an earlier run's jobs wait for an answer. A job for a printer is a PDF, so `postScriptLevel` with no + file throws. Where the app lists no printers for scripts (the web, MCP or the command line without the app), + `print` with no file throws `Printing to a printer is not available here`. `app.printerList` gives a `Printer` for + each printer the app listed for the run, at most 256, leaving out names longer than 512 bytes or with a control + character (https://ai-scripting.docsforadobe.dev/jsobjref/Application/, + https://ai-scripting.docsforadobe.dev/jsobjref/Printer/). Its `name` is read-only and its `printerInfo` throws an + error that says it is not available yet. With no document open, `app.printerList` throws `Application.printerList + needs an open document`, as the Printer help page describes, and where the app lists no printers for scripts it + throws `Application.printerList is not available here`. A printer name is only compared with the listed names: it + is never read as a path, a URL or a command. `fitToPage` set to true wins over the scale factors and the tiling mode. With `printAllArtboards` false, `artboardRange` picks the artboards, and without a range every artboard prints. With one of `horizontalScale` and `verticalScale` assigned, the other keeps the document's saved value. `print` throws before anything is written when an assigned `artboardRange` names an @@ -2753,7 +2772,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot case), when `paperOptions.name` is not a paper `file.print` knows, or when it names a paper other than `custom` and `width` or `height` is assigned above 0. An assigned name that is empty or only spaces, or holds `/`, `\` or a control character, throws too, and each checked name is sent without the spaces - around it. `printerName` and `PPDName` take only `""`. A listed option that is not mapped, or a value that is not mapped such as + around it. `PPDName` takes only `""`. A listed option that is not mapped, or a value that is not mapped such as `PrintingBounds.ARTWORKBOUNDS`, `INRIPSEPARATION`, `PSLEVEL1` or a scale above 1000, throws an error that says it is not available yet. Each value is checked when it is assigned: a wrong type, a number that is not finite or is out of range, a string longer than 4,096 bytes, an option object of the wrong class or from an earlier run, and a @@ -2959,7 +2978,8 @@ In the app, a script past the growth limit stops at a question to continue or to `ui.dialog.cancel` all stop the run. A run with nobody to ask, such as a call over MCP or the command line, ends with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls, runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console, dialogs, dialogCount, dialogsTruncated}`. In -the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`. The +the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`, with +`prints`, the number of jobs the run prepared for a printer, when it prepared any. The report of a failed run has the same fields after `kind`, `message`, `messageOrigin`, `line`, `column`, `file` (when the error is in another file than the script) and `fuelLeft`. `messageOrigin` is `script` when `message` is text the script supplied (a value it threw, or an error it made or whose name or message it changed) and `built-in` for the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4ca0ab994b..04eeaed988 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,7 +1026,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets. Printing to a printer from a script and `app.printerList` are not available yet (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`. + - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`. + - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard approves them, nothing is sent from a failed run, and the web, MCP and the command line cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From b2d458f66754a3233d1effc411c2158446113ce5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:01:28 -0800 Subject: [PATCH 03/72] Scripts: print lists in the host name check, applies range and print area over saved settings - The host name check lists Document.print as a file write, and app's print lists, PrintOptions, its option classes and the printing enumerations as names that stay inside the run. - The script checker reports a file write for print called on a document: app.activeDocument, app.documents[i], documents.add(), documents.getByName() and app.open(), or a variable that holds one. A print method of any other object is not reported. - An assigned artboardRange without printAllArtboards replaces the saved range. An assigned printArea prints by artboard when the saved settings, or the preset's, ignore the artboards: the assigned range, or each artboard. - The two scale factors are linked only when they are equal, as file.print compares them. - The format follows the name jobOptions.file gives, also when that name is a link to a file with another extension. - A print option name with a control character at either end throws. --- crates/engine/src/script/dom/print.rs | 56 +++++++++---- crates/engine/src/tests/script_print.rs | 64 +++++++++++++- .../tests/it/script_host_vs_scriptcheck.rs | 84 ++++++++++++++++++- crates/scriptcheck/src/analyze/features.rs | 17 +++- crates/scriptcheck/src/catalog.rs | 19 +++++ crates/scriptcheck/src/tests.rs | 20 +++++ docs/mcp.md | 23 ++--- 7 files changed, 253 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index c2acec376e..8019ce2583 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -29,7 +29,12 @@ //! and throws an error that says it is not available yet at any other value. //! - `fitToPage` set to true wins over the scale factors and the tiling mode. //! - With `printAllArtboards` set to false, `artboardRange` picks the artboards; without a range -//! every artboard prints. +//! every artboard prints. With `printAllArtboards` not assigned, an assigned `artboardRange` +//! replaces the saved range, which prints when the saved settings print a range. +//! - An assigned `printArea` prints by artboard when the saved settings, or the preset's, ignore +//! the artboards: the artboards an assigned `artboardRange` names, otherwise each artboard. +//! - The format follows the name `jobOptions.file` gives, also when that name is a link to a file +//! with another extension. //! - With one of `horizontalScale` and `verticalScale` assigned, the other keeps the saved value. //! - `print` throws, before anything is written, when an assigned `artboardRange` names an artboard //! the document does not have, also with `printAllArtboards` true; when `printPreset` or @@ -37,8 +42,8 @@ //! not the name of an RGB or CMYK color profile (any case); and when `paperOptions.name` is not //! the id or label of a paper `file.print` knows, or names a paper other than `custom` while //! `width` or `height` is assigned above 0. An assigned name that is empty or only spaces, -//! or that holds `/`, `\` or a control character, throws too. Each checked name goes to -//! `file.print` without the spaces around it. `printerName` and `PPDName` take only the empty +//! or that holds `/`, `\` or a control character (also at either end), throws too. Each checked +//! name goes to `file.print` without the spaces around it. `printerName` and `PPDName` take only the empty //! string. //! - A run makes at most [`MAX_OPTION_OBJECTS`] option objects. //! - `app.printerList` is not available yet, and `app.PPDFileList` is empty: VectorCraft prints @@ -497,6 +502,8 @@ struct Job { paper_size: bool, /// `colorProfileMode` is `SOURCEPROFILE`: the colors print as they are, whatever `name` says. source: bool, + /// `printArea` is assigned: the artboards print even when the base settings ignore them. + print_area: bool, /// The groups of `settings`: the top level and each nested object by its key. top: Map, groups: Vec<(&'static str, Map)>, @@ -623,7 +630,15 @@ fn map_job(h: &Host, slot: usize, job: &mut Job) { job.group("advanced").insert("printAsBitmap".into(), json!(flag(v))); } "file" => job.file = Some(v.clone()), - "artboardRange" => job.range = Some(string_of(v)).filter(|r| !r.trim().is_empty()), + "artboardRange" => { + job.range = Some(string_of(v)).filter(|r| !r.trim().is_empty()); + // Without `printAllArtboards`, the range replaces the base range and the base + // settings still decide whether a range prints. + if let Some(range) = job.range.as_ref().filter(|_| value("printAllArtboards").is_none()) { + s.insert("range".into(), json!(range)); + } + } + "printArea" => job.print_area = true, _ => {} } } @@ -708,10 +723,8 @@ fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<( if let Some(hh) = vs { g.insert("height".into(), json!(hh)); } - let linked = match (hs, vs) { - (Some(w), Some(hh)) => (w - hh).abs() < 1e-9, - _ => false, - }; + // Linked only when the factors are equal, as `file.print` compares them. + let linked = matches!((hs, vs), (Some(w), Some(hh)) if w == hh); g.insert("linked".into(), json!(linked)); } for (k, v) in &set { @@ -830,8 +843,10 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer { if let Some(preset) = job.preset.take() { p.insert("preset".into(), json!(preset)); } + // The format follows the name `jobOptions.file` gives, not the real path a link leads to. + let postscript = job.level.is_some() || crate::cmd::fileio::extension(path) == "ps"; + p.insert("format".into(), json!(if postscript { "postscript" } else { "pdf" })); if let Some(level) = job.level { - p.insert("format".into(), json!("postscript")); p.insert("level".into(), json!(level)); } let settings = job.settings(); @@ -861,18 +876,27 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer { /// name (any case) and a paper by its id or label. An empty name, or one with a path separator or /// a control character, throws. fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> { + let (count, saved_ignore) = with_doc(h, doc, |_, st| { + let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str); + (st.doc.artboards.len(), mode == Some("ignore")) + }); if let Some(range) = &job.range { - let count = with_doc(h, doc, |_, st| st.doc.artboards.len()); vectorcraft_doc::range::parse_range(range, count).map_err(|e| HostError::Range(format!("PrintJobOptions.artboardRange: {e}")))?; } let s = h.session.borrow(); + let mut base_ignore = saved_ignore; if let Some(name) = job.preset.take() { let n = plain_name("PrintOptions.printPreset", "print preset", &name)?; - if s.print_preset_settings(n).is_none() { - return Err(no_such("PrintOptions.printPreset", "print preset", &name)); - } + let preset = s.print_preset_settings(n).ok_or_else(|| no_such("PrintOptions.printPreset", "print preset", &name))?; + base_ignore = matches!(preset.artboards, vectorcraft_pdf::PrintArtboards::Ignore); job.preset = Some(n.to_string()); } + // An assigned `printArea` prints by artboard when the base settings ignore the artboards: the + // assigned `artboardRange` when there is one, otherwise every artboard. + if job.print_area && base_ignore && !job.top.contains_key("artboards") { + let mode = if job.top.contains_key("range") { "range" } else { "all" }; + job.top.insert("artboards".into(), json!(mode)); + } if let Some(name) = job.flattener.take() { let n = plain_name("PrintOptions.flattenerPreset", "flattener preset", &name)?; if FlattenOptions::find_preset(n, &s.prefs.flattener_presets).is_none() { @@ -911,11 +935,15 @@ fn no_such(what: &str, kind: &str, name: &str) -> HostError { /// `name` without the spaces around it, or an error when it is empty or holds a path separator or /// a control character. fn plain_name<'a>(what: &str, kind: &str, name: &'a str) -> std::result::Result<&'a str, HostError> { + // Control characters are looked for before the trim, which would drop a tab or a line break. + if name.chars().any(char::is_control) { + return Err(no_such(what, kind, name)); + } let n = name.trim(); if n.is_empty() { return Err(HostError::Error(format!("{what} must name a {kind}"))); } - if n.contains(['/', '\\']) || n.chars().any(char::is_control) { + if n.contains(['/', '\\']) { return Err(no_such(what, kind, name)); } Ok(n) diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index 104687e0e3..a9eb84b75d 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -81,7 +81,8 @@ fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() { o.paperOptions.name = 'a4'; o.coordinateOptions.fitToPage = true; o.coordinateOptions.orientation = PrintOrientation.PORTRAIT;\n\ o.printerName = ''; o.fontOptions.downloadFonts = PrintFontDownloadMode.DOWNLOADSUBSET;\n\ doc.print(o);\n\ - o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2; j.file = new File(dir + '/c.ps');\n\ + j.file = new File(dir + '/c.ps'); doc.print(o);\n\ + o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2; j.file = new File(dir + '/level2.prn');\n\ doc.print(o);\n\ vc.log([app.printPresetsList[0], app.PPDFileList.length]);" ), @@ -95,7 +96,9 @@ fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() { assert_eq!(pages(&dir.join("a.pdf")).len(), 6, "two artboards, three copies"); assert_eq!(pages(&dir.join("b.pdf")), vec![(595.0, 842.0)], "artboard 2 only, on upright A4"); let ps = std::fs::read_to_string(dir.join("c.ps")).unwrap(); - assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 2"), "{}", &ps[..ps.len().min(200)]); + assert!(ps.starts_with("%!PS") && !ps.contains("%%LanguageLevel: 2"), "a .ps name alone: {}", &ps[..ps.len().min(200)]); + let ps = std::fs::read_to_string(dir.join("level2.prn")).unwrap(); + assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 2"), "a level alone: {}", &ps[..ps.len().min(200)]); assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved, "printing leaves the saved settings as they are"); assert_eq!(s.active().unwrap().history.undo.len(), undo, "and adds no undo step"); // The commands stay closed to vc.run, before and after a print. @@ -272,6 +275,61 @@ fn one_assigned_scale_factor_keeps_the_saved_other() { let _ = std::fs::remove_dir_all(base); } +/// An assigned `artboardRange` replaces a saved range, an assigned `printArea` prints by artboard over +/// saved settings that ignore the artboards, and two scale factors that differ by any amount print +/// unlinked. +#[test] +fn assigned_job_and_scale_options_apply_over_the_saved_settings() { + let base = folder("over-saved"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let print = |s: &mut Session, name: &str, body: &str| { + let file = quoted(&dir.join(name)); + logged( + s, + &base, + &format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({file}); {body} app.activeDocument.print(o);"), + ); + pages(&dir.join(name)).len() + }; + s.execute("print.setup", &json!({"settings": {"artboards": "range", "range": "1"}})).unwrap(); + assert_eq!(print(&mut s, "saved.pdf", ""), 1, "the saved range"); + assert_eq!(print(&mut s, "range.pdf", "o.jobOptions.artboardRange = '1-2';"), 2, "the assigned range replaces the saved one"); + s.execute("print.setup", &json!({"settings": {"artboards": "ignore"}})).unwrap(); + assert_eq!(print(&mut s, "ignore.pdf", ""), 1, "all the art as one page"); + assert_eq!(print(&mut s, "area.pdf", "o.jobOptions.printArea = PrintingBounds.ARTBOARDBOUNDS;"), 2, "each artboard prints"); + assert_eq!(print(&mut s, "range-ignored.pdf", "o.jobOptions.artboardRange = '2';"), 1, "a range alone keeps ignoring the artboards"); + let area_range = "o.jobOptions.printArea = PrintingBounds.ARTBOARDBOUNDS; o.jobOptions.artboardRange = '2';"; + assert_eq!(print(&mut s, "area-range.pdf", area_range), 1, "printArea with a range prints the range"); + let scaled = "o.coordinateOptions.horizontalScale = 100; o.coordinateOptions.verticalScale = 100.0000000005;"; + assert!(print(&mut s, "scale.pdf", scaled) >= 1, "factors that differ by a tiny amount print unlinked"); + assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["artboards"], json!("ignore"), "the saved settings stay"); + let _ = std::fs::remove_dir_all(base); +} + +/// The format follows the name `jobOptions.file` gives, not the extension of the file a link in the +/// granted folder leads to. +#[cfg(unix)] +#[test] +fn the_format_follows_the_name_the_script_gives() { + let base = folder("format-name"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + std::fs::write(dir.join("proof.pdf"), "old").unwrap(); + std::os::unix::fs::symlink(dir.join("proof.pdf"), dir.join("proof.ps")).unwrap(); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);", + quoted(&dir.join("proof.ps")) + ), + ); + let written = std::fs::read(dir.join("proof.pdf")).unwrap(); + assert!(written.starts_with(b"%!PS"), "PostScript for a .ps name: {:?}", String::from_utf8_lossy(&written[..written.len().min(40)])); + let _ = std::fs::remove_dir_all(base); +} + /// Artboard ranges the document does not hold and preset names that are not presets, such as /// paths, throw before anything is written. #[test] @@ -323,6 +381,8 @@ fn print_refuses_profile_paper_and_blank_preset_names() { ("c.name = ' ';", "PrintColorManagementOptions.name must name a color profile"), ("p.name = '../letter';", paper), ("p.name = 'let\\u0007ter';", paper), + ("p.name = '\\tA4\\n';", paper), + ("o.printPreset = '[Default]\\n';", "PrintOptions.printPreset names no print preset"), ("p.name = 'Office Tray 2';", paper), ("p.name = '';", "PrintPaperOptions.name must name a paper"), ("p.name = 'a4'; p.width = 300;", "PrintPaperOptions.width and height apply only to custom paper, not a4"), diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 26b476a0b6..88574f94e9 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -39,6 +39,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), ("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"), ("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"), + ("Document.prototype.print", "var o = new PrintOptions(); o.jobOptions.file = new File(p); app.activeDocument.print(o);", "filesWritten"), ]; /// The names the host adds that stay inside the document and the run, by the object that has them. @@ -83,7 +84,8 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - open selection typename userInteractionLevel userInteractionLevel=", + open PPDFileList printPresetsList printerList printerList= selection typename userInteractionLevel \ + userInteractionLevel=", ), ("Documents.", "prototype"), ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), @@ -137,6 +139,86 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), + // The print option classes and the enumerations of printing. + ( + "", + "FontSubstitutionPolicy PageMarksTypes PostScriptImageCompressionType PrintArtworkDesignation PrintColorIntent \ + PrintColorManagementOptions PrintColorProfile PrintColorSeparationMode PrintColorSeparationOptions \ + PrintCoordinateOptions PrintFlattenerOptions PrintFontDownloadMode PrintFontOptions PrintJobOptions PrintOptions \ + PrintOrientation PrintPageMarksOptions PrintPaperOptions PrintPosition PrintPostScriptOptions PrintTiling \ + PrinterPostScriptLevelEnum PrintingBounds", + ), + ("PrintOptions.", "prototype"), + ( + "PrintOptions.prototype.", + "PPDName PPDName= colorManagementOptions colorManagementOptions= colorSeparationOptions colorSeparationOptions= \ + constructor coordinateOptions coordinateOptions= flattenerOptions flattenerOptions= flattenerPreset \ + flattenerPreset= fontOptions fontOptions= jobOptions jobOptions= pageMarksOptions pageMarksOptions= paperOptions \ + paperOptions= postScriptOptions postScriptOptions= printPreset printPreset= printerName printerName= typename", + ), + ("PrintJobOptions.", "prototype"), + ( + "PrintJobOptions.prototype.", + "artboardRange artboardRange= bitmapResolution bitmapResolution= collate collate= constructor copies copies= \ + designation designation= file file= name name= printAllArtboards printAllArtboards= printArea printArea= \ + printAsBitmap printAsBitmap= reversePages reversePages= typename", + ), + ("PrintColorManagementOptions.", "prototype"), + ("PrintColorManagementOptions.prototype.", "colorProfileMode colorProfileMode= constructor intent intent= name name= typename"), + ("PrintColorSeparationOptions.", "prototype"), + ( + "PrintColorSeparationOptions.prototype.", + "colorSeparationMode colorSeparationMode= constructor convertSpotColors convertSpotColors= inkList inkList= \ + overPrintBlack overPrintBlack= typename", + ), + ("PrintCoordinateOptions.", "prototype"), + ( + "PrintCoordinateOptions.prototype.", + "constructor emulsion emulsion= fitToPage fitToPage= horizontalScale horizontalScale= orientation orientation= \ + position position= tiling tiling= typename verticalScale verticalScale=", + ), + ("PrintFlattenerOptions.", "prototype"), + ( + "PrintFlattenerOptions.prototype.", + "clipComplexRegions clipComplexRegions= constructor convertStrokesToOutlines convertStrokesToOutlines= \ + convertTextToOutlines convertTextToOutlines= flatteningBalance flatteningBalance= gradientResolution \ + gradientResolution= overprint overprint= rasterizationResolution rasterizationResolution= typename", + ), + ("PrintFontOptions.", "prototype"), + ("PrintFontOptions.prototype.", "constructor downloadFonts downloadFonts= fontSubstitution fontSubstitution= typename"), + ("PrintPageMarksOptions.", "prototype"), + ( + "PrintPageMarksOptions.prototype.", + "bleedOffsetRect bleedOffsetRect= colorBars colorBars= constructor marksOffsetRect marksOffsetRect= pageInfoMarks \ + pageInfoMarks= pageMarksType pageMarksType= registrationMarks registrationMarks= trimMarks trimMarks= \ + trimMarksWeight trimMarksWeight= typename", + ), + ("PrintPaperOptions.", "prototype"), + ("PrintPaperOptions.prototype.", "constructor height height= name name= offset offset= transverse transverse= typename width width="), + ("PrintPostScriptOptions.", "prototype"), + ( + "PrintPostScriptOptions.prototype.", + "binaryPrinting binaryPrinting= compatibleShading compatibleShading= constructor forceContinuousTone \ + forceContinuousTone= imageCompression imageCompression= negativePrinting negativePrinting= postScriptLevel \ + postScriptLevel= shadingResolution shadingResolution= typename", + ), + ("FontSubstitutionPolicy.", "SUBSTITUTEDEVICE SUBSTITUTEOBLIQUE SUBSTITUTETINT"), + ("PageMarksTypes.", "Japanese Roman"), + ("PostScriptImageCompressionType.", "IMAGECOMPRESSIONNONE JPEG RLE"), + ("PrintArtworkDesignation.", "ALLLAYERS VISIBLELAYERS VISIBLEPRINTABLELAYERS"), + ("PrintColorIntent.", "ABSOLUTECOLORIMETRIC PERCEPTUALINTENT RELATIVECOLORIMETRIC SATURATIONINTENT"), + ("PrintColorProfile.", "CUSTOMPROFILE OLDSTYLEPROFILE PRINTERPROFILE SOURCEPROFILE"), + ("PrintColorSeparationMode.", "COMPOSITE HOSTBASEDSEPARATION INRIPSEPARATION"), + ("PrintFontDownloadMode.", "DOWNLOADCOMPLETE DOWNLOADNONE DOWNLOADSUBSET"), + ("PrintOrientation.", "AUTOROTATE LANDSCAPE PORTRAIT REVERSELANDSCAPE REVERSEPORTRAIT"), + ( + "PrintPosition.", + "TRANSLATEBOTTOM TRANSLATEBOTTOMLEFT TRANSLATEBOTTOMRIGHT TRANSLATECENTER TRANSLATELEFT TRANSLATERIGHT TRANSLATETOP \ + TRANSLATETOPLEFT TRANSLATETOPRIGHT", + ), + ("PrintTiling.", "TILEFULLPAGES TILEIMAGEABLEAREAS TILESINGLEFULLPAGE"), + ("PrinterPostScriptLevelEnum.", "PSLEVEL1 PSLEVEL2 PSLEVEL3"), + ("PrintingBounds.", "ARTBOARDBOUNDS ARTWORKBOUNDS"), ]; /// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset`, diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 354a0540aa..4704e4baf8 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -284,14 +284,22 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// Whether this `(` calls a document's `print`: the document-model member chain the `(` has just + /// set aside until its `)` is one of [`catalog::DOM_DOCUMENTS`] followed by `called`, the method + /// as the chain writes it (`.print()`, or `[]()` when brackets name it). + fn document_print(&self, called: &str) -> bool { + let chain = self.suspended.last().filter(|c| c.wait.saturating_add(1) == self.depth()); + chain.and_then(|c| c.path.strip_suffix(called)).is_some_and(|receiver| catalog::DOM_DOCUMENTS.contains(&receiver)) + } + /// `(` after a name: a call. fn call(&mut self, line: Option) { let [h0, h1, h2, h3] = self.h; // `doc['saveAs'](f)`: a document method named by a string literal in brackets. if is(h0, "]") && is(h2, "[") - && let Some(name) = h1.filter(|s| s.kind == T::Str) - && catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str()) + && let Some(name) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32)) + && (catalog::DOM_FILE_WRITES.contains(&name.as_str()) || (name == catalog::DOM_PRINT && self.document_print("[]()"))) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); @@ -311,7 +319,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.acc.feature(FeatureId::FileDialog, line); } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { self.acc.feature(FeatureId::FileRead, line); - } else if (file && catalog::FILE_WRITES.contains(&n)) || catalog::DOM_FILE_WRITES.contains(&n) { + } else if (file && catalog::FILE_WRITES.contains(&n)) + || catalog::DOM_FILE_WRITES.contains(&n) + || (n == catalog::DOM_PRINT && self.document_print(".print()")) + { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); } else if n == catalog::EXECUTE { diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index ee5b63dfb2..9ebf0c52a5 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -75,6 +75,25 @@ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", " // Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "saveAs"]; +// The document method that writes the file its options' `jobOptions.file` names, on the same page. +// It counts only when a member chain that ends with one of `DOM_DOCUMENTS` calls it. +pub(crate) const DOM_PRINT: &str = "print"; + +// The member chains that give a document, whole and as the chains are written (`[]` for an index, +// `()` for a call): https://ai-scripting.docsforadobe.dev/jsobjref/Application/ (`activeDocument`, +// `documents`, `open`) and https://ai-scripting.docsforadobe.dev/jsobjref/Documents/ (`add`, `getByName`). +pub(crate) const DOM_DOCUMENTS: &[&str] = &[ + "activeDocument", + "app.activeDocument", + "documents[]", + "app.documents[]", + "documents.add()", + "app.documents.add()", + "documents.getByName()", + "app.documents.getByName()", + "app.open()", +]; + // Application methods that page doesn't list, named in public forum posts: // https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand, // doScript, loadAction, unloadAction) and diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 12e5527811..361b5e0865 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -558,6 +558,26 @@ fn save_as_and_export_file_in_brackets_write_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } +/// A document's `print` writes the file its options' `jobOptions.file` names, called with a dot or +/// with its name in brackets, on a document or a variable that holds one; reading the method without +/// calling it, and a `print` method of another object, do not. +#[test] +fn print_writes_a_file() { + let r = report(concat!( + "var o = new PrintOptions(); o.jobOptions.file = new File(p);\n", + "app.activeDocument.print(o);\n", + "app.activeDocument['print'](o);\n", + "var n = app.activeDocument['print'];\n", + "var d = app.documents[0]; d.print(o);\n", + "logger.print('hello'); logger['print']('hello');\n", + "app.activeDocument.name.concat(logger.print('x'));\n", + "app.print(o); app.activeDocument.layers[0]['print'](o); app.documents['print'](o); app.preferences.activeDocument.print(o);\n", + "var e = app.open(new File(p)); e.print(o); activeDocument.print(o);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3, 5, 9][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[2, 3, 5, 9][..])]); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 93dac91b5c..24bf498130 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2558,8 +2558,9 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, (`app.executeMenuCommand('…')`), each with a count and its lines, and `menuCommands.dynamic` counts the calls whose argument isn't a string literal. - `outside` lists what the script does outside the document: `filesWritten` (with the open modes used; setting a - File object's `length`, `hidden` or `readonly` counts too, and so does a document's `saveAs` or `exportFile`), - `filesOpened` (files opened in other apps), `network`, + File object's `length`, `hidden` or `readonly` counts too, and so does a document's `saveAs` or `exportFile`, and + `print` called on `app.activeDocument`, `app.documents[i]`, `documents.add()`, `documents.getByName()` or + `app.open()`, or on a variable that holds one of them), `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed). - `problems` lists what would stop the script loading as written (strings, comments, regular expressions, @@ -2743,17 +2744,19 @@ app through the global object `vc`, and writes to the Script Console and runs ot `FontSubstitutionPolicy`, `PageMarksTypes`, `PostScriptImageCompressionType` and `PrinterPostScriptLevelEnum` hold strings such as `"PrintTiling.TILEFULLPAGES"`. VectorCraft's own rules: `print` writes the file `jobOptions.file` names, checked as `saveAs` checks its file: PostScript when the name ends with `.ps` or `postScriptLevel` is - assigned, a print-ready PDF otherwise. Without a file it throws `Printing to a printer is not available to scripts - yet`, and `app.printerList` throws an error that says it is not available yet. `fitToPage` set to true wins over - the scale factors and the tiling mode. With `printAllArtboards` false, `artboardRange` picks the artboards, and - without a range every artboard prints. With one of `horizontalScale` and `verticalScale` assigned, the other keeps - the document's saved value. `print` throws before anything is written when an assigned `artboardRange` names an + assigned, a print-ready PDF otherwise, also when that name is a link to a file with another extension. Without a + file it throws `Printing to a printer is not available to scripts yet`, and `app.printerList` throws an error + that says it is not available yet. `fitToPage` set to true wins over the scale factors and the tiling mode. With + `printAllArtboards` false, `artboardRange` picks the artboards, and without a range every artboard prints. With + `printAllArtboards` not assigned, an assigned `artboardRange` replaces the saved range, which prints when the + saved settings print a range. When the saved settings, or the preset's, ignore the artboards, an assigned + `printArea` prints the artboards an assigned `artboardRange` names, or each artboard without a range. With one of + `horizontalScale` and `verticalScale` assigned, the other keeps the document's saved value. `print` throws before anything is written when an assigned `artboardRange` names an artboard the document does not have, also with `printAllArtboards` true, when `printPreset` or `flattenerPreset` is not a preset's name (any case), when `colorManagementOptions.name` is not an RGB or CMYK profile's name (any case), when `paperOptions.name` is not a paper `file.print` knows, or when it names a paper other than `custom` - and `width` or `height` is assigned above 0. An assigned name that is empty or only - spaces, or holds `/`, `\` or a control character, throws too, and each checked name is sent without the spaces - around it. `printerName` and `PPDName` take only `""`. A listed option that is not mapped, or a value that is not mapped such as + and `width` or `height` is assigned above 0. An assigned name that is empty or only spaces, or holds `/`, `\` or + a control character (also at either end), throws too, and each checked name is sent without the spaces around it. `printerName` and `PPDName` take only `""`. A listed option that is not mapped, or a value that is not mapped such as `PrintingBounds.ARTWORKBOUNDS`, `INRIPSEPARATION`, `PSLEVEL1` or a scale above 1000, throws an error that says it is not available yet. Each value is checked when it is assigned: a wrong type, a number that is not finite or is out of range, a string longer than 4,096 bytes, an option object of the wrong class or from an earlier run, and a From 141dc48e1a111642dc76631b54dbbc75bfe43efa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 22:25:50 -0800 Subject: [PATCH 04/72] Scripts: addDocument and addDocumentNoUI count for print, docs name the preset base The script checker reports `print` on a document that `documents.addDocument()` or `documents.addDocumentNoUI()` returns, with or without `app.`, as a file write, as it does for `documents.add()`. Both methods return a Document on the Documents help page. docs/mcp.md and the print module's notes say that with `printPreset` assigned, `print` starts from the preset's settings: an assigned `artboardRange` replaces that range, and an unassigned scale factor keeps the preset's value. --- crates/engine/src/script/dom/print.rs | 16 ++++++++++------ crates/scriptcheck/src/catalog.rs | 7 ++++++- crates/scriptcheck/src/tests.rs | 15 +++++++++++---- docs/mcp.md | 10 ++++++---- 4 files changed, 33 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index 8019ce2583..29d09da58c 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -22,7 +22,8 @@ //! ([`super::super::files`]). PostScript is written when the name ends with `.ps` or //! `postScriptOptions.postScriptLevel` is set, a print-ready PDF otherwise. Printing to a printer //! from a script is not available yet, so `print` without a file throws an error. -//! - Only the properties a script assigned apply; the others keep the document's print settings +//! - Only the properties a script assigned apply; the others keep the settings `print` starts +//! from: the preset's when `printPreset` is assigned, otherwise the document's print settings //! (`print.setup`), which `print` leaves as they are. A property that was not assigned reads as //! the default its help page gives. //! - A property the help pages list that is not mapped accepts the default its help page gives @@ -30,12 +31,14 @@ //! - `fitToPage` set to true wins over the scale factors and the tiling mode. //! - With `printAllArtboards` set to false, `artboardRange` picks the artboards; without a range //! every artboard prints. With `printAllArtboards` not assigned, an assigned `artboardRange` -//! replaces the saved range, which prints when the saved settings print a range. -//! - An assigned `printArea` prints by artboard when the saved settings, or the preset's, ignore -//! the artboards: the artboards an assigned `artboardRange` names, otherwise each artboard. +//! replaces the range of the settings `print` starts from, which prints when those settings +//! print a range. +//! - An assigned `printArea` prints by artboard when the settings `print` starts from ignore the +//! artboards: the artboards an assigned `artboardRange` names, otherwise each artboard. //! - The format follows the name `jobOptions.file` gives, also when that name is a link to a file //! with another extension. -//! - With one of `horizontalScale` and `verticalScale` assigned, the other keeps the saved value. +//! - With one of `horizontalScale` and `verticalScale` assigned, the other keeps its value in the +//! settings `print` starts from. //! - `print` throws, before anything is written, when an assigned `artboardRange` names an artboard //! the document does not have, also with `printAllArtboards` true; when `printPreset` or //! `flattenerPreset` is not the name of a preset (any case); when `colorManagementOptions.name` is @@ -715,7 +718,8 @@ fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<( job.top.insert("scaling".into(), json!(scaling)); } if scaled && fit != Some(true) { - // Only the assigned factors are sent; with one of them, the other keeps the saved value. + // Only the assigned factors are sent; with one of them, the other keeps its value in the + // base settings (the preset's or the saved ones). let g = job.group("scale"); if let Some(w) = hs { g.insert("width".into(), json!(w)); diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index fac0173879..ad3931117a 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -83,7 +83,8 @@ pub(crate) const DOM_PRINT: &str = "print"; // The member chains that give a document, whole and as the chains are written (`[]` for an index, // `()` for a call): https://ai-scripting.docsforadobe.dev/jsobjref/Application/ (`activeDocument`, -// `documents`, `open`) and https://ai-scripting.docsforadobe.dev/jsobjref/Documents/ (`add`, `getByName`). +// `documents`, `open`) and https://ai-scripting.docsforadobe.dev/jsobjref/Documents/ (`add`, `addDocument`, +// `addDocumentNoUI`, `getByName`). pub(crate) const DOM_DOCUMENTS: &[&str] = &[ "activeDocument", "app.activeDocument", @@ -91,6 +92,10 @@ pub(crate) const DOM_DOCUMENTS: &[&str] = &[ "app.documents[]", "documents.add()", "app.documents.add()", + "documents.addDocument()", + "app.documents.addDocument()", + "documents.addDocumentNoUI()", + "app.documents.addDocumentNoUI()", "documents.getByName()", "app.documents.getByName()", "app.open()", diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 4867b440c3..c833ccb540 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -559,7 +559,8 @@ fn save_as_and_export_file_in_brackets_write_a_file() { } /// A document's `print` writes the file its options' `jobOptions.file` names, called with a dot or -/// with its name in brackets, on a document or a variable that holds one; reading the method without +/// with its name in brackets, on a document (also one `add`, `addDocument` or `addDocumentNoUI` +/// returns) or a variable that holds one; reading the method without /// calling it, and a `print` method of another object, do not. #[test] fn print_writes_a_file() { @@ -572,10 +573,16 @@ fn print_writes_a_file() { "logger.print('hello'); logger['print']('hello');\n", "app.activeDocument.name.concat(logger.print('x'));\n", "app.print(o); app.activeDocument.layers[0]['print'](o); app.documents['print'](o); app.preferences.activeDocument.print(o);\n", - "var e = app.open(new File(p)); e.print(o); activeDocument.print(o);\n", + "var e = app.open(new File(p)); e.print(o);\n", + "activeDocument.print(o);\n", + "documents.addDocument('Print').print(o);\n", + "app.documents.addDocument('Print', s, false).print(o);\n", + "documents.addDocumentNoUI('Print').print(o);\n", + "app.documents.addDocumentNoUI('Print').print(o);\n", )); - assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3, 5, 9][..])); - assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[2, 3, 5, 9][..])]); + let lines = &[2, 3, 5, 9, 10, 11, 12, 13, 14][..]; + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines)); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", lines)]); } /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing diff --git a/docs/mcp.md b/docs/mcp.md index fd15234565..8e55502bac 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2736,7 +2736,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot pages do not list are left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default keeps the preset's value. A bad value throws an error before anything is written. - `Document.print(options?)` runs `file.print` on the document, with the options a script assigned over the - document's print settings, which stay as they are, and adds no undo step + document's print settings, or over the preset's when `printPreset` is assigned. The document's print settings + stay as they are, and `print` adds no undo step (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/). `options` is a `new PrintOptions()`, whose `jobOptions`, `colorManagementOptions`, `colorSeparationOptions`, `coordinateOptions`, `flattenerOptions`, `fontOptions`, `pageMarksOptions`, `paperOptions` and `postScriptOptions` @@ -2763,10 +2764,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot file it throws `Printing to a printer is not available to scripts yet`, and `app.printerList` throws an error that says it is not available yet. `fitToPage` set to true wins over the scale factors and the tiling mode. With `printAllArtboards` false, `artboardRange` picks the artboards, and without a range every artboard prints. With - `printAllArtboards` not assigned, an assigned `artboardRange` replaces the saved range, which prints when the - saved settings print a range. When the saved settings, or the preset's, ignore the artboards, an assigned + `printAllArtboards` not assigned, an assigned `artboardRange` replaces the range of the settings `print` starts + from, which prints when those settings print a range. `print` starts from the preset's settings when `printPreset` + is assigned, otherwise from the document's saved settings. When those settings ignore the artboards, an assigned `printArea` prints the artboards an assigned `artboardRange` names, or each artboard without a range. With one of - `horizontalScale` and `verticalScale` assigned, the other keeps the document's saved value. `print` throws before anything is written when an assigned `artboardRange` names an + `horizontalScale` and `verticalScale` assigned, the other keeps its value in the settings `print` starts from. `print` throws before anything is written when an assigned `artboardRange` names an artboard the document does not have, also with `printAllArtboards` true, when `printPreset` or `flattenerPreset` is not a preset's name (any case), when `colorManagementOptions.name` is not an RGB or CMYK profile's name (any case), when `paperOptions.name` is not a paper `file.print` knows, or when it names a paper other than `custom` From 058d83c8c7cf2a297009078700f880f85d6e0734 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 00:00:19 -0800 Subject: [PATCH 05/72] Scripts: a script's print jobs are sent only after a deliberate Print press The question before a script's print jobs are sent no longer has a default button. Enter does nothing; the jobs are sent only after the person clicks Print, or presses Space once Tab has moved the focus to it. Print takes no click or focus for one second after the dialog is first drawn (VectorCraft's own value, on the app's clock), and the dialog does not open while a text field or text on the canvas has the keyboard. ui.dialog.confirm and synthetic input stay refused. Cancel, Escape and ui.dialog.cancel drop the jobs. File.hidden: the setter stores the new path with set_path, which the merge of main requires. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/js/src/file_classes.rs | 2 +- crates/ui-egui/src/app.rs | 14 +- crates/ui-egui/src/dialogs/script_run.rs | 85 ++++++++++-- crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/tests/script_print.rs | 165 +++++++++++++++++++++-- docs/mcp.md | 9 +- docs/target-app-parity.md | 2 +- 7 files changed, 249 insertions(+), 31 deletions(-) diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 83bf8428a8..c024991556 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -524,7 +524,7 @@ fn set_hidden(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult< if outcome(i, o, &r)? { let fs = i.rooted(std::slice::from_ref(&r), |i| field(i, &r, "fs"))?; if matches!(fs, Value::String(_)) { - set_slot(i, o, PATH, fs)?; + set_path(i, o, fs)?; } } Ok(Value::Undefined) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..20a32d393d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -193,6 +193,7 @@ impl VectorcraftApp { queued_profile_opens: Default::default(), script_picked: Vec::new(), script_picked_left_out: false, + script_print_shown_at: None, pen_end: Default::default(), host_iteration: 0, #[cfg(test)] @@ -292,6 +293,14 @@ impl VectorcraftApp { self.shortcuts_frames.clear(); } + /// The app's monotonic clock in seconds ([`now_secs`]), or a test's clock when it set one. + pub(crate) fn clock_secs(&self) -> f64 { + #[cfg(test)] + return self.now_override.unwrap_or_else(now_secs); + #[cfg(not(test))] + now_secs() + } + /// Background work, once per host iteration (full or logic-only): control requests, background /// saves/exports/opens, plug-ins, recovery, font and clipboard polls, capture completion. It /// reads only viewport state from `ctx.input` — never events or `i.time`: a logic-only pass @@ -327,10 +336,7 @@ impl VectorcraftApp { // Monotonic host time, never egui's `InputState::time`: a logic-only (hidden) iteration // replays the last shown pass's time, freezing recovery, clipboard polling and deadlines. // Tests inject a clock to drive idle scheduling deterministically. - #[cfg(test)] - let now = self.now_override.unwrap_or_else(now_secs); - #[cfg(not(test))] - let now = now_secs(); + let now = self.clock_secs(); self.perf.fps = self.frame_rate.frame(now, self.perf.frame_ms / 1000.0); self.sync_views(); self.refresh_replace_font_warning(false); diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 6add1104b5..87927fa35f 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -27,9 +27,12 @@ //! //! The jobs a script prepared for a printer (`Document.print` without a file) wait for the dialog of //! kind `scriptPrint`, which opens once the run has ended and its changes are kept, when no other -//! dialog is open. It lists each job's document, printer and sheets from the jobs themselves, which -//! no field changes. Only the person at the keyboard prints them, with Print: from -//! `ui.dialog.confirm` or synthetic input Print is refused and the dialog stays open. Cancel, +//! dialog is open and no text field or text being typed on the canvas has the keyboard. It lists +//! each job's document, printer and sheets from the jobs themselves, which no field changes. Only +//! the person at the keyboard prints them, with a click on its Print button or Space once Tab gave +//! it the focus: the button takes no click or focus for [`PRINT_ENABLE_DELAY_SECS`] after the +//! dialog is first drawn, Enter does not print, and +//! from `ui.dialog.confirm` or synthetic input Print is refused and the dialog stays open. Cancel, //! Escape and `ui.dialog.cancel` drop the jobs, from anyone; the script's changes stay either way. use serde_json::{Value, json}; @@ -58,9 +61,9 @@ pub const PRINT_KIND: &str = "scriptPrint"; pub(super) const PRINT_SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Print").into(), - body: print_body, + body_with_actions: Some(print_body), confirm: print_confirm, - ok: Some("Print"), + ok: None, min_width: 420.0, max_width: Some(560.0), ..DialogSpec::FORM @@ -566,16 +569,64 @@ fn answers_for(kind: &str) -> &'static str { } } +/// How long the print question's Print button takes no click after the dialog is first drawn, in +/// seconds: VectorCraft's own value, so a click or key meant for what was there before does not +/// send a job. +pub(crate) const PRINT_ENABLE_DELAY_SECS: f64 = 1.0; + /// Opens the question before the jobs a script prepared for a printer are sent, once the run has -/// ended and no other dialog is open. +/// ended, no other dialog is open and nothing is being typed: while a text field or text on the +/// canvas has the keyboard it waits, and a later poll opens it. pub(crate) fn ask_print(app: &mut VectorcraftApp) { - if app.ui.dialog.is_none() && !app.session.script_running() && app.session.script_prints_waiting() { - app.ui.dialog = Some(Dialog::new(PRINT_KIND, json!({}))); + if app.ui.dialog.is_some() || app.session.script_running() || !app.session.script_prints_waiting() { + return; } + let typing = app.ui_ctx.as_ref().is_some_and(egui::Context::text_edit_focused) || app.session.tool_wants_text(); + if typing { + return; + } + app.script_print_shown_at = None; + app.ui.dialog = Some(Dialog::new(PRINT_KIND, json!({}))); } -/// The jobs, read from the session, so `ui.dialog.set` cannot change what the person reads. -fn print_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, _: &mut Dialog) -> bool { +/// Seconds until Print takes a click, from when the dialog was first drawn: 0 once it does. +fn print_wait(app: &VectorcraftApp) -> f64 { + app.script_print_shown_at.map_or(PRINT_ENABLE_DELAY_SECS, |at| (at + PRINT_ENABLE_DELAY_SECS - app.clock_secs()).max(0.0)) +} + +/// The jobs, read from the session, so `ui.dialog.set` cannot change what the person reads, then +/// Cancel and Print. Enter gives nothing, and Print takes no click until [`PRINT_ENABLE_DELAY_SECS`] +/// after the dialog was first drawn. +fn print_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + if app.script_print_shown_at.is_none() { + app.script_print_shown_at = Some(app.clock_secs()); + } + print_jobs(app, ui); + ui.add_space(16.0); + let wait = print_wait(app); + if wait > 0.0 { + ui.ctx().request_repaint_after_secs(wait as f32); + } + let mut action = DialogAction::None; + let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y); + ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| { + // A click, Space on the button once Tab gave it the focus, or a screen reader's press; + // never Enter. + let print = widgets::primary_button_enabled(ui, tl!("Print"), wait <= 0.0); + if print.clicked() && !ui.input(|i| i.key_pressed(egui::Key::Enter)) { + d.fields.insert("answer".into(), json!("print")); + action = DialogAction::Confirm; + } + ui.add_space(8.0); + if widgets::secondary_button(ui, tl!("Cancel")).clicked() { + action = DialogAction::Cancel; + } + }); + action +} + +/// The question and the table of jobs: document, printer and pages. +fn print_jobs(app: &VectorcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); ui.label(tl!("The script asks to print these jobs. Its changes to the documents are kept whether or not you print.")); ui.add_space(8.0); @@ -593,15 +644,18 @@ fn print_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, _: &mut Dialog) -> bo } }); }); - false } -/// Print: sends the jobs, when the person at the keyboard asked. From automation (a control or MCP -/// request, or synthetic input) it is refused and the dialog stays open. -fn print_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result { +/// Print: sends the jobs, when the person at the keyboard clicked Print once it took clicks. From +/// automation (a control or MCP request, or synthetic input) it is refused, as a confirm without +/// that click is, and the dialog stays open. +fn print_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { if app.automation_asked() { return Err(PRINT_BY_PERSON.into()); } + if d.fields.get("answer").and_then(Value::as_str) != Some("print") || print_wait(app) > 0.0 { + return Err(PRINT_BY_CLICK.into()); + } close_print(app); let jobs = app.session.take_script_prints(); if jobs.is_empty() { @@ -623,9 +677,12 @@ fn close_print(app: &mut VectorcraftApp) { if app.ui.dialog.as_ref().is_some_and(|open| open.kind == PRINT_KIND) { app.ui.dialog = None; } + app.script_print_shown_at = None; } /// Print's error when automation asked. pub(crate) const PRINT_BY_PERSON: &str = "Only the person at the keyboard can print a script's print jobs"; +/// The error of a confirm without a click on Print once it took clicks. +pub(crate) const PRINT_BY_CLICK: &str = "Click Print to send the script's print jobs"; /// The status after Cancel. pub(crate) const PRINTS_DROPPED: &str = "The script's print jobs were not sent"; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a50527cede..051003099a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -371,6 +371,9 @@ pub struct VectorcraftApp { pub(crate) script_picked: Vec, /// Choose… left out files past the most a script is given. pub(crate) script_picked_left_out: bool, + /// When the question before a script's print jobs were sent was first drawn, on + /// [`Self::clock_secs`]; `None` while it is not open. + pub(crate) script_print_shown_at: Option, /// The pen end the canvas saw last and the tool its eraser end stands in for /// ([`stylus::sync_eraser_tool`]). pub(crate) pen_end: stylus::PenEnd, diff --git a/crates/ui-egui/src/tests/script_print.rs b/crates/ui-egui/src/tests/script_print.rs index 094299d2bb..660442fe85 100644 --- a/crates/ui-egui/src/tests/script_print.rs +++ b/crates/ui-egui/src/tests/script_print.rs @@ -1,14 +1,15 @@ //! A script's jobs for a printer (`Document.print` without a file): the run lists the print //! service's printers, and its jobs are sent after it ends, only when the person at the keyboard -//! approves them. +//! approves them with a click on Print. use std::cell::RefCell; use std::rc::Rc; +use egui::{Pos2, Rect, vec2}; use serde_json::{Value, json}; use vectorcraft_engine::Session; -use crate::dialogs::script_run::{PRINT_BY_PERSON, PRINT_KIND, PRINTS_DROPPED}; +use crate::dialogs::script_run::{PRINT_BY_CLICK, PRINT_BY_PERSON, PRINT_ENABLE_DELAY_SECS, PRINT_KIND, PRINTS_DROPPED}; use crate::print::{PrintJob, PrintService, Printer}; use crate::{Services, VectorcraftApp, dialogs, menus, script_runs}; @@ -83,10 +84,60 @@ fn control(app: &mut VectorcraftApp, method: &str, params: Value) -> Value { r } +/// The open dialog, drawn as the app draws it at `time` on the app's clock and egui's, with +/// `events` → the texts drawn, with where. +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec) -> Vec<(String, Rect)> { + fn texts(s: &egui::Shape, out: &mut Vec<(String, Rect)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + app.now_override = Some(time); + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 800.0))); + let raw = egui::RawInput { screen_rect, time: Some(time), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + let mut v = vec![]; + out.shapes.iter().for_each(|c| texts(&c.shape, &mut v)); + v +} + +/// Where the button `label` was drawn: the last text that reads it (the heading reads Print too). +fn button(texts: &[(String, Rect)], label: &str) -> Pos2 { + texts.iter().rev().find(|(t, _)| t.trim() == label).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")).1.center() +} + +/// A press and release of the primary button at `pos`. +fn click(pos: Pos2) -> Vec { + let press = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + vec![egui::Event::PointerMoved(pos), press(true), press(false)] +} + +/// A press of `key` with no modifiers. +fn key(key: egui::Key) -> Vec { + let event = |pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + vec![event(true), event(false)] +} + +/// Draws the open question from `time` until it settles, then clicks its `label` button once +/// [`PRINT_ENABLE_DELAY_SECS`] have passed since it was first drawn. +fn click_after_delay(app: &mut VectorcraftApp, time: f64, label: &str) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + frame(app, &ctx, time, vec![]); + frame(app, &ctx, time + 0.1, vec![]); + let later = time + PRINT_ENABLE_DELAY_SECS + 0.1; + let pos = button(&frame(app, &ctx, later, vec![]), label); + frame(app, &ctx, later + 0.1, click(pos)); +} + /// The job is sent after the run's changes are kept, once, and only when the person at the -/// keyboard approves it: Print from a control request or synthetic input is refused. +/// keyboard clicks Print: Print from a control request or synthetic input is refused, as a confirm +/// without the click is. #[test] -fn a_scripts_print_job_is_sent_only_when_the_person_approves_it() { +fn a_scripts_print_job_is_sent_only_when_the_person_clicks_print() { let (mut app, sent, _) = print_app(true); run(&mut app, PRINT_TO_LAB); assert_eq!(objects(&app), 1, "the run's changes are kept"); @@ -97,9 +148,10 @@ fn a_scripts_print_job_is_sent_only_when_the_person_approves_it() { app.synthetic_frame = true; assert_eq!(dialogs::confirm(&mut app).unwrap_err(), PRINT_BY_PERSON); app.synthetic_frame = false; + assert_eq!(dialogs::confirm(&mut app).unwrap_err(), PRINT_BY_CLICK); assert_eq!(open_kind(&app), Some(PRINT_KIND), "the question stays open"); assert!(sent.borrow().is_empty()); - dialogs::confirm(&mut app).unwrap(); + click_after_delay(&mut app, 10.0, "Print"); assert_eq!(open_kind(&app), None); { let sent = sent.borrow(); @@ -115,6 +167,87 @@ fn a_scripts_print_job_is_sent_only_when_the_person_approves_it() { assert_eq!(open_kind(&app), None); } +/// Enter does not print, and Print takes no click until [`PRINT_ENABLE_DELAY_SECS`] after the +/// question was first drawn; a click after that prints. +#[test] +fn enter_or_an_early_click_does_not_print() { + let (mut app, sent, _) = print_app(true); + run(&mut app, PRINT_TO_LAB); + assert_eq!(open_kind(&app), Some(PRINT_KIND)); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 10.0, vec![]); + let pos = button(&frame(&mut app, &ctx, 10.1, vec![]), "Print"); + for (time, events) in [(10.2, click(pos)), (10.3, key(egui::Key::Enter)), (10.4, key(egui::Key::Enter))] { + frame(&mut app, &ctx, time, events); + assert_eq!(open_kind(&app), Some(PRINT_KIND), "at {time}"); + } + let later = 10.0 + PRINT_ENABLE_DELAY_SECS + 0.1; + for (time, events) in [(later, key(egui::Key::Enter)), (later + 0.1, key(egui::Key::Enter))] { + frame(&mut app, &ctx, time, events); + assert_eq!(open_kind(&app), Some(PRINT_KIND), "Enter at {time}"); + } + // Tab gives Print the keyboard focus: Enter on it does not print either. + frame(&mut app, &ctx, later + 0.15, key(egui::Key::Tab)); + frame(&mut app, &ctx, later + 0.16, key(egui::Key::Enter)); + assert_eq!(open_kind(&app), Some(PRINT_KIND), "Enter on the focused button"); + assert!(sent.borrow().is_empty(), "nothing is sent"); + frame(&mut app, &ctx, later + 0.2, click(pos)); + assert_eq!(open_kind(&app), None); + assert_eq!(sent.borrow().len(), 1); +} + +/// Space on Print, once Tab gave it the keyboard focus after [`PRINT_ENABLE_DELAY_SECS`], prints: +/// a keyboard user can approve the jobs without a mouse. +#[test] +fn space_on_the_focused_print_button_prints() { + let (mut app, sent, _) = print_app(true); + run(&mut app, PRINT_TO_LAB); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 10.0, vec![]); + let later = 10.0 + PRINT_ENABLE_DELAY_SECS + 0.1; + frame(&mut app, &ctx, later, vec![]); + frame(&mut app, &ctx, later + 0.1, key(egui::Key::Tab)); + frame(&mut app, &ctx, later + 0.2, key(egui::Key::Space)); + assert_eq!(open_kind(&app), None); + assert_eq!(sent.borrow().len(), 1); +} + +/// While a text field has the keyboard when the run ends, the question waits, and nothing is sent; +/// it opens at the first poll after the field lets the keyboard go. +#[test] +fn the_print_question_waits_while_a_text_field_has_the_keyboard() { + let (mut app, sent, _) = print_app(true); + let ctx = egui::Context::default(); + let id = egui::Id::unique("script-print-typing"); + let mut text = String::new(); + let mut draw = |time: f64, focus: bool| { + let raw = egui::RawInput { time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut text).id(id)); + if focus { + r.request_focus(); + } + }); + out.textures_delta.clear(); + }; + draw(1.0, true); + draw(1.1, false); + assert!(ctx.text_edit_focused()); + app.ui_ctx = Some(ctx.clone()); + run(&mut app, PRINT_TO_LAB); + for _ in 0..3 { + script_runs::poll(&mut app); + } + assert_eq!(open_kind(&app), None, "the question waits"); + assert!(app.session.script_prints_waiting(), "the job waits"); + ctx.memory_mut(|m| m.surrender_focus(id)); + script_runs::poll(&mut app); + assert_eq!(open_kind(&app), Some(PRINT_KIND)); + assert!(sent.borrow().is_empty()); +} + /// Cancel, from anyone, drops the jobs and keeps the run's changes. #[test] fn cancel_drops_a_scripts_print_jobs_and_keeps_its_changes() { @@ -130,6 +263,23 @@ fn cancel_drops_a_scripts_print_jobs_and_keeps_its_changes() { assert_eq!(open_kind(&app), None, "the question does not come back"); assert!(sent.borrow().is_empty()); assert_eq!(objects(&app), 1); + // The Cancel button, at once or later, does the same. + run(&mut app, PRINT_TO_LAB); + assert_eq!(open_kind(&app), Some(PRINT_KIND)); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 10.0, vec![]); + let pos = button(&frame(&mut app, &ctx, 10.1, vec![]), "Cancel"); + frame(&mut app, &ctx, 10.2, click(pos)); + assert_eq!(open_kind(&app), None); + assert!(!app.session.script_prints_waiting()); + assert_eq!(app.ui.status, PRINTS_DROPPED); + run(&mut app, PRINT_TO_LAB); + click_after_delay(&mut app, 20.0, "Cancel"); + assert_eq!(open_kind(&app), None); + assert!(!app.session.script_prints_waiting()); + assert!(sent.borrow().is_empty()); + assert_eq!(objects(&app), 3); } /// A run that fails asks nothing and sends nothing; a printer that went away before Print is @@ -144,9 +294,8 @@ fn a_failed_run_or_a_printer_that_went_away_sends_nothing() { run(&mut app, &format!("app.activeDocument.print(); {PRINT_TO_LAB}")); assert_eq!(open_kind(&app), Some(PRINT_KIND)); names.borrow_mut().retain(|n| n != "Lab"); - let e = dialogs::confirm(&mut app).unwrap_err(); - assert_eq!(e, "The printer Lab is no longer installed: the script's print jobs were not sent"); - assert_eq!(app.ui.status, e); + click_after_delay(&mut app, 10.0, "Print"); + assert_eq!(app.ui.status, "The printer Lab is no longer installed: the script's print jobs were not sent"); assert!(sent.borrow().is_empty(), "neither job is sent"); assert_eq!(open_kind(&app), None); } diff --git a/docs/mcp.md b/docs/mcp.md index 7ef86b320c..20850904c9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2756,9 +2756,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot app listed for the run, or `print` throws `PrintOptions.printerName names no installed printer`; with no default printer it throws `There is no default printer`. `print` composes the job as a print-ready PDF when it is called and sends nothing while the run goes on. When the run ends and its changes are kept, the app asks before it sends - the jobs (dialog kind `scriptPrint`, listing each job's document, printer and pages). Only the person at the - keyboard can choose Print: `ui.dialog.confirm` and synthetic input are refused, and the dialog stays open. Cancel, - Escape and `ui.dialog.cancel` drop the jobs and keep the run's changes. A run that fails or is stopped sends + the jobs (dialog kind `scriptPrint`, listing each job's document, printer and pages). The dialog does not open + while a text field or text being typed on the canvas has the keyboard; it opens once neither does. The jobs are + sent only after the person at the keyboard clicks its Print button, or presses Space once Tab has moved the focus to + it: the button takes no click or focus for the first second after the dialog appears (VectorCraft's own value), + Enter does not print, and `ui.dialog.confirm` and synthetic input are refused, and the dialog stays open. Cancel, Escape and `ui.dialog.cancel` drop the jobs and keep the + run's changes. A run that fails or is stopped sends nothing. Before it sends them, the app checks that each printer is still installed under that name, and sends none when one is not. A run prepares at most 4 jobs, together at most 100 pages, every copy counted, and 32 MiB, and none while an earlier run's jobs wait for an answer. A job for a printer is a PDF, so `postScriptLevel` with no diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f429917528..6edcfec716 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1030,7 +1030,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`. - - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard approves them, nothing is sent from a failed run, and the web, MCP and the command line cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. + - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print, which takes no click for the first second, nothing is sent from a failed run, and the web, MCP and the command line cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From a7beba792d9f71138709b8b73a7a9edc722d13cf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 00:20:44 -0800 Subject: [PATCH 06/72] Scripts: the script checker reports app.open as reading a file app.open(f) and app['open'](f) now count as file.read in the checker's features, as the script host's app.open reads the file it is given. A document has no open method, and a property or a variable named app is not the application object, so those calls stay unreported. --- crates/scriptcheck/src/analyze.rs | 5 +++++ crates/scriptcheck/src/analyze/features.rs | 23 +++++++++++++++++----- crates/scriptcheck/src/catalog.rs | 2 ++ crates/scriptcheck/src/tests.rs | 19 ++++++++++++++++++ 4 files changed, 44 insertions(+), 5 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 5d01cc8438..05d4dd4c8d 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -544,6 +544,8 @@ struct Analyzer<'s, 'a, 'l> { file: Option<&'a str>, /// The four significant tokens before this one, the latest first. h: [Option>; 4], + /// The significant token before the four in `h`. + h4: Option>, brackets: Brackets, /// Nesting too deep to follow was reported: it is reported once. deep: bool, @@ -626,6 +628,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { acc, file, h: [None; 4], + h4: None, brackets: Brackets::default(), deep: false, active: None, @@ -745,6 +748,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.features(&t); self.newer(&t); self.module_check(&t); + self.h4 = self.h[3]; self.h = [Some(t), self.h[0], self.h[1], self.h[2]]; } @@ -1522,6 +1526,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.var_depth = None; self.conds.clear(); self.h = [None; 4]; + self.h4 = None; self.acc.steps = self.acc.steps.saturating_add(1); let d = directives::parse(t.text); let Some(name) = d.known else { diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 7eb89a1fbe..699537d5b2 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -289,14 +289,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `(` after a name: a call. fn call(&mut self, line: Option) { let [h0, h1, h2, h3] = self.h; - // `doc['saveAs'](f)`: a document method named by a string literal in brackets. + // `doc['saveAs'](f)` and `app['open'](f)`: a method named by a string literal in brackets. if is(h0, "]") && is(h2, "[") && let Some(name) = h1.filter(|s| s.kind == T::Str) - && catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str()) { - self.acc.feature(FeatureId::FileWrite, line); - self.acc.outside(OutsideId::FilesWritten, line, None); + let name = unquote(name.text, 32); + if catalog::DOM_FILE_WRITES.contains(&name.as_str()) { + self.acc.feature(FeatureId::FileWrite, line); + self.acc.outside(OutsideId::FilesWritten, line, None); + } else if catalog::DOM_FILE_READS.contains(&name.as_str()) && self.app_receiver(h3, self.h4) { + self.acc.feature(FeatureId::FileRead, line); + } return; } let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return }; @@ -311,7 +315,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.acc.feature(FeatureId::ScriptuiDrawing, line); } else if catalog::INSTANCE_DIALOGS.contains(&n) { self.acc.feature(FeatureId::FileDialog, line); - } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { + } else if catalog::FOLDER_READS.contains(&n) + || (file && catalog::FILE_READS.contains(&n)) + || (catalog::DOM_FILE_READS.contains(&n) && self.app_receiver(h2, h3)) + { self.acc.feature(FeatureId::FileRead, line); } else if (file && catalog::FILE_WRITES.contains(&n)) || catalog::DOM_FILE_WRITES.contains(&n) { self.acc.feature(FeatureId::FileWrite, line); @@ -336,6 +343,12 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// Whether `receiver`, which `before` comes before, is the application object: the name `app` + /// that no `.` comes before and that the script has not declared as its own. + fn app_receiver(&self, receiver: Option>, before: Option>) -> bool { + word(receiver, catalog::DOM_ROOTS[0]) && !member_mark(before) && !self.shadowed.first().copied().unwrap_or(true) + } + /// Whether `receiver`, which `before` comes before, is a variable holding a File or Folder object /// (not a property of the same name), or a File or Folder object made in place or held in /// grouping parentheses ([`Sig::file`]). diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index a73dd557d6..62cd477330 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -76,6 +76,8 @@ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", " // Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "saveAs"]; +// Application methods that read the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Application/ +pub(crate) const DOM_FILE_READS: &[&str] = &["open"]; // Application methods that page doesn't list, named in public forum posts: // https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand, diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index e985fa3d0f..18cb5a42bb 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -558,6 +558,25 @@ fn save_as_and_export_file_in_brackets_write_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } +/// `app.open` reads the file it is given, called by name or with its name as a string literal in +/// brackets; a document has no `open` method, and a property or a variable named `app` is not the +/// application. +#[test] +fn app_open_reads_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var d = app.open(f);\n", + "app['open'](f);\n", + "app.activeDocument['open'](f);\n", + "x.app.open(f);\n", + "x.app['open'](f);\n", + )); + assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(&[2, 3][..])); + assert!(r.outside.is_empty()); + let r = report("var app = {};\napp.open(f);\napp['open'](f);\n"); + assert!(feature(&r, "file.read").is_none()); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] From a704798119d242fe6b47b22747d6b549b235c194 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 02:39:54 -0800 Subject: [PATCH 07/72] Scripts: printer jobs count pages from the art as it prints, and app['open'] gives a document - Document.print to a printer no longer counts pages with print.preview, which leaves out artboard backgrounds and placed files. It passes file.print a new maxPages param: file.print counts the pages of the art it prints and composes nothing when the job has more, answering {pages, format}. An artboard that holds only its background now prints with skipBlank, and a job turned away by the sheet limit is not composed. When the pages follow from the artboards alone, the count is checked before Print as Bitmap or a flattener preset prepares the art, after the level and the flattener preset are checked. - The printers a run lists keep the system's default printer when it comes after the first 256 (it takes the last place), and a repeated name keeps a later default mark without a second entry. - The script checker reads app['open'](f) as giving a document, as app.open(f) does, so a print of the variable that holds it counts as a file write. - The print job test checks the artwork in each prepared job, not only that the two jobs differ. Docs: docs/mcp.md (maxPages, the page count, the default printer), docs/roadmap.md M13 row. --- crates/engine/src/cmd/print.rs | 47 +++++++++++++---- crates/engine/src/script/dom/print.rs | 14 ++--- crates/engine/src/script/printing.rs | 24 +++++++-- crates/engine/src/tests/script_print.rs | 61 +++++++++++++++++++++- crates/scriptcheck/src/analyze.rs | 13 +++++ crates/scriptcheck/src/analyze/features.rs | 5 ++ crates/scriptcheck/src/tests.rs | 8 +-- docs/mcp.md | 10 ++-- docs/roadmap.md | 2 +- 9 files changed, 151 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 8c507db007..976a96d3f4 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -12,7 +12,7 @@ use vectorcraft_pdf::{PrintLayers, PrintOptions, PrintPreview, PrintSettings}; use super::fileio::pdf::{merge, pdf_error}; use super::fileio::{extension, write_or_return}; use super::flatten::has_transparent_tile_images; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param}; +use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param, u64_req}; const SETUP: &str = "print.setup"; @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Print", [], Some("Cmd+P"), - "{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy; with copiesPerSheet, a sheet holds as many copies of an artboard as fit) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device", + "{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), maxPages?: n (a whole number: the job is composed only when it prints at most n pages, copies counted; with more, nothing is composed or written and the reply is {pages, format}), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy; with copiesPerSheet, a sheet holds as many copies of an artboard as fit) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device", has_doc, print ), @@ -222,6 +222,11 @@ fn print(s: &mut Session, p: &Value) -> Result { super::fileio::check_not_lossy_overwrite(s.doc()?, path, p, PRINT)?; } let postscript = to_postscript(p)?; + let max_pages = match p.get("maxPages") { + None | Some(Value::Null) => None, + Some(_) => Some(u64_req(p, "maxPages", PRINT)?), + }; + let too_many = |pages: usize| max_pages.is_some_and(|m| pages as u64 > m); let doc = &s.doc()?.doc; let mut set = preset_or_saved(PRINT, s, doc, p)?; if postscript { @@ -244,6 +249,27 @@ fn print(s: &mut Session, p: &Value) -> Result { && !bitmap && super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)? .is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o)); + let level = match p.get("level").filter(|v| postscript && !v.is_null()) { + Some(v) => { + let t = super::fileio::dxf::text(v); + Level::from_id(&t).ok_or_else(|| bad(PRINT, format!("level `{t}`: 2 or 3")))? + } + None => Level::default(), + }; + // A job past `maxPages` is turned away before Print as Bitmap or a flattener preset prepares it, + // once the options are checked, when its pages follow from the artboards alone (composite, no + // `skipBlank`, artboards not ignored); the pages are counted again on the prepared art. + super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?; + let by_artboards = !set.skip_blank + && !matches!(set.artboards, vectorcraft_pdf::PrintArtboards::Ignore) + && set.output.mode == vectorcraft_pdf::OutputMode::Composite; + if max_pages.is_some() + && by_artboards + && let Ok(pv) = vectorcraft_pdf::preview(doc, &set) + && too_many(pv.pages) + { + return Ok(json!({ "pages": pv.pages, "format": if postscript { "postscript" } else { "pdf" } })); + } // Print as Bitmap and the flattener preset (Advanced) render and flatten it first. let prepared = super::printadvanced::prepare(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich")?; let path = str_param(p, "path"); @@ -251,7 +277,12 @@ fn print(s: &mut Session, p: &Value) -> Result { let which = set.print_layers; if !postscript { let printed = prepared.as_ref().unwrap_or(doc); - let typed = type_warnings(&full, which, &areas(&vectorcraft_pdf::preview(printed, &set).map_err(|e| pdf_error(PRINT, e))?)); + let laid_out = vectorcraft_pdf::preview(printed, &set).map_err(|e| pdf_error(PRINT, e))?; + // `maxPages` is checked on the art as it prints, before the job is composed. + if too_many(laid_out.pages) { + return Ok(json!({ "pages": laid_out.pages, "format": "pdf" })); + } + let typed = type_warnings(&full, which, &areas(&laid_out)); let mut r = vectorcraft_pdf::print(printed, &PrintOptions { settings: set, for_printer: bool_or(p, "forPrinter", false), ..Default::default() }) .map_err(|e| pdf_error(PRINT, e))?; @@ -260,13 +291,6 @@ fn print(s: &mut Session, p: &Value) -> Result { r.warnings.extend(r.setting_notes); return write_or_return(path, &r.bytes, json!({ "pages": r.pages, "format": "pdf", "warnings": r.warnings })); } - let level = match p.get("level").filter(|v| !v.is_null()) { - Some(v) => { - let t = super::fileio::dxf::text(v); - Level::from_id(&t).ok_or_else(|| bad(PRINT, format!("level `{t}`: 2 or 3")))? - } - None => Level::default(), - }; // What the job loses, then the notes on the options: a reply lists them in that order. let (mut warnings, mut setting_notes) = (vec![], vec![]); if !bitmap && (tile_images || doc.layers.iter().any(|l| l.shows_transparency())) { @@ -278,6 +302,9 @@ fn print(s: &mut Session, p: &Value) -> Result { let flatness = (!set.graphics.auto_flatness).then_some(set.graphics.flatness); let plan = vectorcraft_pdf::plan(prepared.as_ref().unwrap_or(doc), &PrintOptions { settings: set, postscript: true, ..Default::default() }) .map_err(|e| pdf_error(PRINT, e))?; + if too_many(plan.order.len()) { + return Ok(json!({ "pages": plan.order.len(), "format": "postscript" })); + } let pages: Vec = plan .sheets .iter() diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index 726610a665..d9a8f7ed0d 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -962,20 +962,16 @@ fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer { if for_printer { p.insert("forPrinter".into(), json!(true)); } - // The pages are counted from the layout before the job is composed. - let plan: serde_json::Map = - p.iter().filter(|(k, _)| matches!(k.as_str(), "preset" | "settings")).map(|(k, v)| (k.clone(), v.clone())).collect(); - let planned = on_doc(h, doc.uid, false, |h| unfenced(h, PREVIEW, || command_kept(h, PREVIEW, &Value::Object(plan))))?; - let pages = planned.get("pages").and_then(Value::as_u64).unwrap_or(0); - sheets_fit(sheets, pages)?; + // `file.print` counts the pages of the art as it prints and composes the job only when they fit. + p.insert("maxPages".into(), json!(MAX_SHEETS.saturating_sub(sheets))); let printed = on_doc(h, doc.uid, false, |h| unfenced(h, PRINT, || command_kept(h, PRINT, &Value::Object(p))))?; + let pages = printed.get("pages").and_then(Value::as_u64).unwrap_or(0); + sheets_fit(sheets, pages)?; let pdf = printed .get("dataBase64") .and_then(Value::as_str) .and_then(vectorcraft_format::base64_decode) .ok_or_else(|| HostError::Error("the print job has no data".into()))?; - let pages = printed.get("pages").and_then(Value::as_u64).unwrap_or(pages); - sheets_fit(sheets, pages)?; if bytes.saturating_add(pdf.len()) > MAX_JOB_BYTES { return Err(HostError::Range("a script's printer jobs can hold at most 32 MiB in a run".into())); } @@ -1078,8 +1074,6 @@ fn sheets_fit(sheets: u64, pages: u64) -> std::result::Result<(), HostError> { } const PRINT: &str = "file.print"; -/// Counts a job's pages without composing it. -const PREVIEW: &str = "print.preview"; /// Runs `run`, which runs `id`, a command scripts may not run through `vc.run`, for a member that /// checked its params: only `id` passes the fence, and only while `run` runs. diff --git a/crates/engine/src/script/printing.rs b/crates/engine/src/script/printing.rs index fd31e25a4c..f33a12113b 100644 --- a/crates/engine/src/script/printing.rs +++ b/crates/engine/src/script/printing.rs @@ -36,16 +36,32 @@ pub struct Printers { impl Printers { /// The printers of `list` (name, whether it is the default), in its order. A name that is - /// empty, longer than [`MAX_PRINTER_NAME_BYTES`], holds a control character or repeats an - /// earlier one is left out, and so is every printer after the first [`MAX_PRINTERS`]. + /// empty, longer than [`MAX_PRINTER_NAME_BYTES`] or holds a control character is left out, and + /// so is a name that repeats an earlier one, though its default mark is kept. Every printer + /// after the first [`MAX_PRINTERS`] is left out, except the default printer, which takes the + /// last place when it comes later. pub fn new(list: impl IntoIterator, for_printer: bool) -> Self { let mut names: Vec = Vec::new(); let mut default = None; for (name, is_default) in list { - if names.len() >= MAX_PRINTERS { + let full = names.len() >= MAX_PRINTERS; + if full && default.is_some() { break; } - if name.is_empty() || name.len() > MAX_PRINTER_NAME_BYTES || name.chars().any(char::is_control) || names.contains(&name) { + if name.is_empty() || name.len() > MAX_PRINTER_NAME_BYTES || name.chars().any(char::is_control) { + continue; + } + if let Some(i) = names.iter().position(|n| *n == name) { + if is_default && default.is_none() { + default = Some(i); + } + continue; + } + if full { + if is_default && let Some(last) = names.last_mut() { + *last = name; + default = Some(MAX_PRINTERS - 1); + } continue; } if is_default && default.is_none() { diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index ebdcf2683f..d8c8b04f71 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -164,6 +164,13 @@ fn printer_list_is_the_bounded_list_the_frontend_gave() { let snapshot = Printers::new(list, false); assert_eq!(snapshot.names().len(), MAX_PRINTERS); assert_eq!(snapshot.default_name(), Some("Printer 1")); + // A default listed after the first 256 takes the last place, and a repeated name keeps a later + // default mark without a second entry. + let late = Printers::new((0..300).map(|i| (format!("Q{i}"), i == 280)), false); + let names = late.names(); + assert_eq!((names.len(), late.default_name(), names[254].as_str(), names[255].as_str()), (MAX_PRINTERS, Some("Q280"), "Q254", "Q280")); + let repeat = Printers::new([("A".to_string(), false), ("B".to_string(), false), ("A".to_string(), true)], false); + assert_eq!((repeat.names(), repeat.default_name()), (&["A".to_string(), "B".to_string()][..], Some("A"))); s.script_printers = Some(snapshot); let out = logged( &mut s, @@ -222,7 +229,15 @@ fn print_to_a_printer_holds_the_job_until_the_run_ends() { assert_eq!((jobs[0].printer.as_str(), jobs[0].sheets, job_pages(&jobs[0])), (ODD_NAME, 4, 4), "two artboards, two copies"); assert_eq!((jobs[1].printer.as_str(), jobs[1].sheets, job_pages(&jobs[1])), ("Office", 2, 2), "the default printer"); assert!(jobs.iter().all(|j| j.title == title && j.pdf.starts_with(b"%PDF"))); - assert_ne!(jobs[0].pdf, jobs[1].pdf, "each job holds the document as it was when print was called"); + // Each job holds the document as it was when print was called: one copy of the second job has + // the rectangle the script added after the first job, and the first job's two copies do not. + let paths = |job: &PreparedPrint| { + let mut n = 0; + vectorcraft_pdf::import(&job.pdf).unwrap().walk(|c| n += usize::from(matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }))); + n + }; + assert_eq!(paths(&jobs[0]) % 2, 0, "two equal copies"); + assert_eq!(paths(&jobs[0]) / 2 + 1, paths(&jobs[1]), "the second job has the added rectangle"); assert!(s.take_script_prints().is_empty(), "a job is taken once"); let _ = std::fs::remove_dir_all(base); } @@ -279,7 +294,7 @@ fn print_to_a_printer_refuses_what_it_cannot_send() { failure(&mut s, &base, "var o = new PrintOptions(); o.jobOptions.copies = 999; app.activeDocument.print(o);"); let report = s.script_report().unwrap(); let ran: Vec<&str> = report["slowestCommands"].as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).collect(); - assert_eq!(ran, ["print.preview"], "{report}"); + assert_eq!(ran, ["file.print"], "{report}"); s.script_printers = Some(Printers::new([("Office".to_string(), false)], false)); let e = failure(&mut s, &base, "app.activeDocument.print();"); assert!(e.contains("There is no default printer: set PrintOptions.printerName"), "{e}"); @@ -308,6 +323,48 @@ fn print_to_a_printer_refuses_what_it_cannot_send() { let _ = std::fs::remove_dir_all(base); } +/// The pages of a job for a printer are counted from the art as it prints, artboard backgrounds +/// included, as `file.print` lays it out: an artboard that holds only its background prints with +/// `skipBlank`, and counts toward the sheet limit. +#[test] +fn print_to_a_printer_counts_the_pages_of_the_art_as_it_prints() { + let base = folder("backgrounds"); + let mut s = session(&base); + s.execute("artboard.setProps", &json!({"index": 1, "color": "#ff0000"})).unwrap(); + s.execute("print.setup", &json!({"settings": {"skipBlank": true, "artboards": "range", "range": "2"}})).unwrap(); + s.script_printers = Some(printers()); + logged(&mut s, &base, "app.activeDocument.print();"); + let jobs = s.take_script_prints(); + assert_eq!(jobs.iter().map(|j| (j.sheets, job_pages(j))).collect::>(), [(1, 1)], "the background prints"); + s.execute("print.setup", &json!({"settings": {"artboards": "all"}})).unwrap(); + s.script_printers = Some(printers()); + let e = failure(&mut s, &base, "var o = new PrintOptions(); o.jobOptions.copies = 51; app.activeDocument.print(o);"); + assert!(e.contains("this job has 102"), "both artboards print: {e}"); + assert!(!s.script_prints_waiting()); + let _ = std::fs::remove_dir_all(base); +} + +/// `file.print`'s `maxPages` composes nothing for a longer job, and only after the other params are +/// checked. +#[test] +fn file_print_max_pages_composes_only_what_fits() { + let base = folder("max-pages"); + let mut s = session(&base); + let r = s.execute("file.print", &json!({"maxPages": 5, "settings": {"copies": 3}})).unwrap(); + assert_eq!((&r["pages"], r.get("dataBase64").is_none()), (&json!(6), true), "{r}"); + let r = s.execute("file.print", &json!({"maxPages": 6, "settings": {"copies": 3}})).unwrap(); + assert_eq!((&r["pages"], r["dataBase64"].is_string()), (&json!(6), true)); + for bad in [ + json!({"maxPages": 0, "format": "postscript", "level": 1}), + json!({"maxPages": 0, "settings": {"advanced": {"flattenerPreset": "nope"}}}), + json!({"maxPages": -1}), + json!({"maxPages": "2"}), + ] { + assert!(s.execute("file.print", &bad).is_err(), "{bad}"); + } + let _ = std::fs::remove_dir_all(base); +} + /// Bad values throw when they are assigned, and nothing prints. #[test] fn print_options_refuse_bad_values() { diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 05d4dd4c8d..785eccb00e 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -452,6 +452,19 @@ impl Chain { self.last_change = false; self.append(if call { "()" } else { "[]" }, cap); } + + /// The call that ends the chain is of the member `name`, which a string literal in brackets + /// named: `[]()` becomes `.name()`. + fn name_call(&mut self, name: &str, cap: usize) { + if self.cut || !self.path.ends_with("[]()") { + return; + } + self.path.truncate(self.path.len() - 4); + self.chars = self.chars.saturating_sub(4); + for s in [".", name, "()"] { + self.append(s, cap); + } + } } /// A function body being read: the bracket depth inside it, and what each name declared in it diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 61baa3791a..7f85f7ce72 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -307,6 +307,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.acc.outside(OutsideId::FilesWritten, line, None); } else if catalog::DOM_FILE_READS.contains(&name.as_str()) && self.app_receiver(h3, self.h4) { self.acc.feature(FeatureId::FileRead, line); + // `app['open'](f)` gives a document, as `app.open(f)` does. + let (depth, cap) = (self.depth(), self.acc.limits.echo); + if let Some(c) = self.suspended.last_mut().filter(|c| c.wait.saturating_add(1) == depth) { + c.name_call(&name, cap); + } } return; } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 954f36ff52..9fc93821fa 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -578,8 +578,8 @@ fn app_open_reads_a_file() { } /// A document's `print` writes the file its options' `jobOptions.file` names, called with a dot or -/// with its name in brackets, on a document (also one `add`, `addDocument` or `addDocumentNoUI` -/// returns) or a variable that holds one; reading the method without +/// with its name in brackets, on a document (also one `add`, `addDocument`, `addDocumentNoUI` or +/// `app.open`, with or without brackets, returns) or a variable that holds one; reading the method without /// calling it, and a `print` method of another object, do not. #[test] fn print_writes_a_file() { @@ -598,8 +598,10 @@ fn print_writes_a_file() { "app.documents.addDocument('Print', s, false).print(o);\n", "documents.addDocumentNoUI('Print').print(o);\n", "app.documents.addDocumentNoUI('Print').print(o);\n", + "var g = app['open'](new File(p)); g.print(o);\n", + "var h = app['activeDocument'](new File(p)); h.print(o);\n", )); - let lines = &[2, 3, 5, 9, 10, 11, 12, 13, 14][..]; + let lines = &[2, 3, 5, 9, 10, 11, 12, 13, 14, 15][..]; assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines)); assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", lines)]); } diff --git a/docs/mcp.md b/docs/mcp.md index a57bb2b8c0..0c9c2722c4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2775,11 +2775,13 @@ app through the global object `vc`, and writes to the Script Console and runs ot run's changes. A run that fails or is stopped sends nothing. Before it sends them, the app checks that each printer is still installed under that name, and sends none when one is not. A run prepares at most 4 jobs, together at most 100 pages, every copy counted, and 32 MiB, and - none while an earlier run's jobs wait for an answer. A job for a printer is a PDF, so `postScriptLevel` with no + none while an earlier run's jobs wait for an answer. The pages are counted from the art as it prints, artboard + backgrounds and placed files included, before the job is composed. A job for a printer is a PDF, so `postScriptLevel` with no file throws. Where the app lists no printers for scripts (the web build, and MCP or the command line without the app), `print` with no file throws `Printing to a printer is not available here`. `app.printerList` gives a `Printer` for each printer the app listed for the run, at most 256, leaving out names longer than 512 bytes or with a control - character (https://ai-scripting.docsforadobe.dev/jsobjref/Application/, + character; when the system's default printer comes after the first 256, it takes the last place + (https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Printer/). Its `name` is read-only and its `printerInfo` throws an error that says it is not available yet. With no document open, `app.printerList` throws `Application.printerList needs an open document`, as the Printer help page describes, and where the app lists no printers for scripts it @@ -11292,7 +11294,9 @@ bleed, composite or separations output, graphics and colour management options o `transform` from the document onto the page (pt, y down), the document `area` it prints, its `trim` box on the page and, with copies per sheet, each copy's artboard on the page (`copies`), plus `tiles`, the `inks` of a separation and `warnings`. `file.print {settings?, path?}` writes the job as a print-ready PDF (one page per -sheet, tile, ink and copy); headless it answers `dataBase64`. In the app, `file.print` with no params opens the Print +sheet, tile, ink and copy); headless it answers `dataBase64`. With `maxPages`, the job is composed only when it +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. diff --git a/docs/roadmap.md b/docs/roadmap.md index 3ddf3459a4..750cff7e5a 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -196,7 +196,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; in the app, `Document.print` prints to an installed printer once the person approves the job, and `app.printerList` lists the printers (`printerInfo` remains); the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | From 25f3f4d24f624e160740c235b91fc4553832c834 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:53:31 -0800 Subject: [PATCH 08/72] Print: file.print turns down a null maxPages instead of printing without a limit --- crates/engine/src/cmd/print.rs | 2 +- crates/engine/src/tests/script_print.rs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 94c9b6a3fd..5d37ec4e9c 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -223,7 +223,7 @@ fn print(s: &mut Session, p: &Value) -> Result { } let postscript = to_postscript(p)?; let max_pages = match p.get("maxPages") { - None | Some(Value::Null) => None, + None => None, Some(_) => Some(u64_req(p, "maxPages", PRINT)?), }; let too_many = |pages: usize| max_pages.is_some_and(|m| pages as u64 > m); diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index d8c8b04f71..6fcf309feb 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -359,6 +359,7 @@ fn file_print_max_pages_composes_only_what_fits() { json!({"maxPages": 0, "settings": {"advanced": {"flattenerPreset": "nope"}}}), json!({"maxPages": -1}), json!({"maxPages": "2"}), + json!({"maxPages": null}), ] { assert!(s.execute("file.print", &bad).is_err(), "{bad}"); } From 241d1af923edfd1799cbec983832df35569cdf63 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 19:21:39 -0800 Subject: [PATCH 09/72] Scripts: the print question refuses Enter on a focused Print and stays open for a click On the craft UI framework a focused footer button takes Enter as a click, and the framework's key stage takes Enter out of egui's events. The question now reads Enter from the held keys and the pass's raw events, and keeps itself open when it refuses one, so a later click or Space still prints. The tests click and press keys in frames of their own, as a person does, and also send an Enter pressed and let go within one frame. --- crates/ui-egui/src/dialogs/script_run.rs | 13 +++++- crates/ui-egui/src/tests/script_print.rs | 51 ++++++++++++++++-------- 2 files changed, 45 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 19e69fd6e4..9d5010f048 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -42,6 +42,7 @@ use std::path::Path; use craft::host::{PickRequest, Picked}; +use craft::keymap::Key; use craft::theme::variant::Tone; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Outcome as _, Show as _}; @@ -49,6 +50,7 @@ use craft::ui::dialog::{ DialogHost, DialogId, DialogResult, DialogStack, FieldRefusal, Prompt, PromptChoice, StackDialog, StandardPrompt, dialog_id, }; use craft::ui::display::Text; +use craft::ui::runtime::keys; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::text::TextField; use egui::Ui; @@ -793,11 +795,18 @@ impl StackDialog for ScriptPrint { /// is not the dialog's default: Enter never prints, also on the focused button. fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let now = ui.input(|i| i.time); + // A focused button takes Enter as a click: an Enter held, or pressed in this pass and let go in it too, refuses Print. + let pressed = |e: &egui::Event| matches!(e, egui::Event::Key { key: egui::Key::Enter, pressed: true, .. }); + let enter = keys::held(ui.ctx()).contains(&Key::Enter) || ui.input(|i| i.raw.events.iter().any(pressed)); let wait = (*self.shown_at.get_or_insert(now) + PRINT_ENABLE_DELAY_SECS - now).max(0.0); if wait > 0.0 { ui.ctx().request_repaint_after_secs(wait as f32); } - let buttons = [FooterButton::new(tl!("Print"), DialogRole::Other).enabled(wait <= 0.0), FooterButton::new(tl!("Cancel"), DialogRole::Cancel)]; + // Print pressed with Enter is refused and leaves the question open. + let buttons = [ + FooterButton::new(tl!("Print"), DialogRole::Other).enabled(wait <= 0.0).stays_open(enter), + FooterButton::new(tl!("Cancel"), DialogRole::Cancel), + ]; let jobs = &self.jobs; let prompt = Prompt::new(tl!("Print"), tl!("The script asks to print these jobs. Its changes to the documents are kept whether or not you print.")) @@ -819,7 +828,7 @@ impl StackDialog for ScriptPrint { }); }); match prompt.show(ui).picked? { - 0 if wait <= 0.0 && !ui.input(|i| i.key_pressed(egui::Key::Enter)) => Some(DialogResult::Ok(PrintAnswer { print: true })), + 0 if wait <= 0.0 && !enter => Some(DialogResult::Ok(PrintAnswer { print: true })), 0 => None, _ => Some(DialogResult::Cancel), } diff --git a/crates/ui-egui/src/tests/script_print.rs b/crates/ui-egui/src/tests/script_print.rs index 1941ebb0c9..46c6ccc867 100644 --- a/crates/ui-egui/src/tests/script_print.rs +++ b/crates/ui-egui/src/tests/script_print.rs @@ -103,16 +103,21 @@ fn button(texts: &[(String, Rect)], label: &str) -> Pos2 { texts.iter().rev().find(|(t, _)| t.trim() == label).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")).1.center() } -/// A press and release of the primary button at `pos`. -fn click(pos: Pos2) -> Vec { +/// A click of the primary button at `pos` from `time`: hover, press and release in frames of their +/// own, as a person's click comes. +fn click(app: &mut VectorcraftApp, time: f64, pos: Pos2) { let press = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - vec![egui::Event::PointerMoved(pos), press(true), press(false)] + for (i, event) in [egui::Event::PointerMoved(pos), press(true), press(false)].into_iter().enumerate() { + frame(app, time + 0.01 * i as f64, vec![event]); + } } -/// A press and release of `key` with no modifiers. -fn key(key: egui::Key) -> Vec { +/// A press of `key` with no modifiers at `time`, let go in a frame of its own, as a person lets go +/// of it. +fn key(app: &mut VectorcraftApp, time: f64, key: egui::Key) { let event = |pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; - vec![event(true), event(false)] + frame(app, time, vec![event(true)]); + frame(app, time + 0.01, vec![event(false)]); } /// Draws the open question from `time` until it settles, then clicks its `label` button once @@ -122,7 +127,7 @@ fn click_after_delay(app: &mut VectorcraftApp, time: f64, label: &str) { frame(app, time + 0.1, vec![]); let later = time + PRINT_ENABLE_DELAY_SECS + 0.1; let pos = button(&frame(app, later, vec![]), label); - frame(app, later + 0.1, click(pos)); + click(app, later + 0.1, pos); } /// The job is sent after the run's changes are kept, once, and only when the person at the @@ -178,22 +183,31 @@ fn enter_or_an_early_click_does_not_print() { run(&mut app, PRINT_TO_LAB); assert!(asking(&app)); frame(&mut app, 10.0, vec![]); + frame(&mut app, 10.05, vec![]); let pos = button(&frame(&mut app, 10.1, vec![]), "Print"); - for (time, events) in [(10.2, click(pos)), (10.3, key(egui::Key::Enter)), (10.4, key(egui::Key::Enter))] { - frame(&mut app, time, events); + click(&mut app, 10.2, pos); + assert!(asking(&app), "an early click"); + for time in [10.3, 10.4] { + key(&mut app, time, egui::Key::Enter); assert!(asking(&app), "at {time}"); } let later = 10.0 + PRINT_ENABLE_DELAY_SECS + 0.1; - for (time, events) in [(later, key(egui::Key::Enter)), (later + 0.1, key(egui::Key::Enter))] { - frame(&mut app, time, events); + for time in [later, later + 0.1] { + key(&mut app, time, egui::Key::Enter); assert!(asking(&app), "Enter at {time}"); } // Tab gives a button the keyboard focus: Enter on it does not print either. - frame(&mut app, later + 0.15, key(egui::Key::Tab)); - frame(&mut app, later + 0.16, key(egui::Key::Enter)); + key(&mut app, later + 0.15, egui::Key::Tab); + key(&mut app, later + 0.17, egui::Key::Enter); assert!(asking(&app), "Enter on the focused button"); + // Nor does an Enter pressed and let go within one frame. + let enter = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + frame(&mut app, later + 0.185, vec![enter(true), enter(false)]); + assert!(asking(&app), "Enter pressed and let go in one frame"); assert!(sent.borrow().is_empty(), "nothing is sent"); - frame(&mut app, later + 0.2, click(pos)); + // The question has settled where it stays; Print is clicked there. + let pos = button(&frame(&mut app, later + 0.19, vec![]), "Print"); + click(&mut app, later + 0.2, pos); assert!(!asking(&app)); assert_eq!(sent.borrow().len(), 1); } @@ -256,11 +270,14 @@ fn cancel_drops_a_scripts_print_jobs_and_keeps_its_changes() { assert!(asking(&app)); frame(&mut app, 10.0, vec![]); let pos = button(&frame(&mut app, 10.1, vec![]), "Cancel"); - frame(&mut app, 10.2, click(pos)); + click(&mut app, 10.2, pos); assert!(!asking(&app)); assert!(!app.session.script_prints_waiting()); assert_eq!(app.ui.status, PRINTS_DROPPED); + // The app draws on: the closed question's layer is gone by the next frame. + frame(&mut app, 10.3, vec![]); run(&mut app, PRINT_TO_LAB); + assert!(asking(&app)); click_after_delay(&mut app, 20.0, "Cancel"); assert!(!asking(&app)); assert!(!app.session.script_prints_waiting()); @@ -319,8 +336,8 @@ fn space_on_the_focused_print_button_prints() { frame(&mut app, 10.0, vec![]); let later = 10.0 + PRINT_ENABLE_DELAY_SECS + 0.1; frame(&mut app, later, vec![]); - frame(&mut app, later + 0.1, key(egui::Key::Tab)); - frame(&mut app, later + 0.2, key(egui::Key::Space)); + key(&mut app, later + 0.1, egui::Key::Tab); + key(&mut app, later + 0.2, egui::Key::Space); assert!(!asking(&app)); assert_eq!(sent.borrow().len(), 1); } From 5709055a97ac68510221d0dc92b5c4eef54d576c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:59:59 -0800 Subject: [PATCH 10/72] Scripts: the checker finds print on documents.index() and open through a variable that holds app `documents.index()` and `app.documents.index()` now count as chains that give a document, so `app.documents.index(0).print(o)` is listed as a file write. A document method named in brackets (`app.documents['index'](0)`) gives a document as its dotted form does. `app.open(f)` is found from the member chain, so `var a = app; a.open(f)` reads a file, while `x.app.open(f)` and an `app` the script declares still do not. Member chains hold at least 64 characters while they are read, and the report cuts the listed chains to the echo limit, so a short echo limit no longer hides these calls. --- crates/scriptcheck/src/analyze.rs | 12 +++++++- crates/scriptcheck/src/analyze/features.rs | 36 +++++++++++++++++++--- crates/scriptcheck/src/catalog.rs | 5 ++- crates/scriptcheck/src/report.rs | 5 +-- crates/scriptcheck/src/tests.rs | 30 ++++++++++++++---- 5 files changed, 73 insertions(+), 15 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 11361f733a..04ebe4b0f2 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -410,6 +410,10 @@ struct Chain { group: Option, } +/// Characters a member chain holds at least, more than the longest chain the checks compare +/// (`app.documents.addDocumentNoUI().print()` has 39). +const CHAIN_CHARS: usize = 64; + impl Chain { fn new(root: String, bare: bool, line: usize) -> Self { let (chars, cut) = (root.chars().count(), root.ends_with('…')); @@ -779,10 +783,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // ---------- member chains ---------- + /// The most characters a member chain holds while it is read: [`crate::Limits::echo`], and at least + /// [`CHAIN_CHARS`], so a short echo limit cuts only the chains the report lists. + fn chain_cap(&self) -> usize { + self.acc.limits.echo.max(CHAIN_CHARS) + } + /// Whether the active chain takes `t` (a `.`, a member's name, `[` or `(`); any other token ends /// it. fn continue_chain(&mut self, t: &Sig<'s>) -> bool { - let cap = self.acc.limits.echo; + let cap = self.chain_cap(); let Some(c) = self.active.as_mut() else { return false }; if c.after_dot { c.after_dot = false; diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 8e252c4dcf..b8a022d550 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -291,8 +291,31 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// set aside until its `)` is one of [`catalog::DOM_DOCUMENTS`] followed by `called`, the method /// as the chain writes it (`.print()`, or `[]()` when brackets name it). fn document_print(&self, called: &str) -> bool { + self.called_on(called).is_some_and(|receiver| catalog::DOM_DOCUMENTS.contains(&receiver)) + } + + /// Whether this `(` calls a method of the application object: `receiver`, which `before` comes + /// before, is the application object ([`Self::app_receiver`]), or the document-model member chain + /// the `(` has just set aside until its `)` is `app` followed by `called`. The chain starts at `app` + /// or at a variable that holds it, never at a property named `app` or at an `app` the script declared. + fn app_call(&self, called: &str, receiver: Option>, before: Option>) -> bool { + self.app_receiver(receiver, before) || self.called_on(called) == Some(catalog::DOM_ROOTS[0]) + } + + /// Whether the method `name`, which a string literal in brackets named, gives a document: the + /// member chain this `(` has just set aside, with `name` called on its receiver, is one of + /// [`catalog::DOM_DOCUMENTS`]. + fn gives_document(&self, name: &str) -> bool { + let named = + |receiver: &str, d: &str| d.strip_prefix(receiver).and_then(|m| m.strip_prefix('.')).and_then(|m| m.strip_suffix("()")) == Some(name); + self.called_on("[]()").is_some_and(|receiver| catalog::DOM_DOCUMENTS.iter().any(|d| named(receiver, d))) + } + + /// What the document-model member chain that this `(` has just set aside until its `)` holds before + /// `called`, when the chain ends with `called`. + fn called_on(&self, called: &str) -> Option<&str> { let chain = self.suspended.last().filter(|c| c.wait.saturating_add(1) == self.depth()); - chain.and_then(|c| c.path.strip_suffix(called)).is_some_and(|receiver| catalog::DOM_DOCUMENTS.contains(&receiver)) + chain.and_then(|c| c.path.strip_suffix(called)) } /// `(` after a name: a call. @@ -306,10 +329,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if catalog::DOM_FILE_WRITES.contains(&name.as_str()) || (name == catalog::DOM_PRINT && self.document_print("[]()")) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); - } else if catalog::DOM_FILE_READS.contains(&name.as_str()) && self.app_receiver(h3, self.h4) { + } else if catalog::DOM_FILE_READS.contains(&name.as_str()) && self.app_call("[]()", h3, self.h4) { self.acc.feature(FeatureId::FileRead, line); - // `app['open'](f)` gives a document, as `app.open(f)` does. - let (depth, cap) = (self.depth(), self.acc.limits.echo); + } + // `app['open'](f)` and `app.documents['index'](0)` give a document, as `app.open(f)` and + // `app.documents.index(0)` do. + if self.gives_document(&name) { + let (depth, cap) = (self.depth(), self.chain_cap()); if let Some(c) = self.suspended.last_mut().filter(|c| c.wait.saturating_add(1) == depth) { c.name_call(&name, cap); } @@ -330,7 +356,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.acc.feature(FeatureId::FileDialog, line); } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) - || (catalog::DOM_FILE_READS.contains(&n) && self.app_receiver(h2, h3)) + || (catalog::DOM_FILE_READS.contains(&n) && self.app_call(&format!(".{n}()"), h2, h3)) { self.acc.feature(FeatureId::FileRead, line); } else if (file && catalog::FILE_WRITES.contains(&n)) diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index e747bcca71..832990368d 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -86,7 +86,8 @@ pub(crate) const DOM_PRINT: &str = "print"; // The member chains that give a document, whole and as the chains are written (`[]` for an index, // `()` for a call): https://ai-scripting.docsforadobe.dev/jsobjref/Application/ (`activeDocument`, // `documents`, `open`) and https://ai-scripting.docsforadobe.dev/jsobjref/Documents/ (`add`, `addDocument`, -// `addDocumentNoUI`, `getByName`). +// `addDocumentNoUI`, `getByName`). `index` is not on that page; it comes from VectorCraft's own binding of +// the collection (`crates/engine/src/script/dom.rs`), which returns the document at a position or with a name. pub(crate) const DOM_DOCUMENTS: &[&str] = &[ "activeDocument", "app.activeDocument", @@ -100,6 +101,8 @@ pub(crate) const DOM_DOCUMENTS: &[&str] = &[ "app.documents.addDocumentNoUI()", "documents.getByName()", "app.documents.getByName()", + "documents.index()", + "app.documents.index()", "app.open()", ]; diff --git a/crates/scriptcheck/src/report.rs b/crates/scriptcheck/src/report.rs index b21feb20e6..6142045a3e 100644 --- a/crates/scriptcheck/src/report.rs +++ b/crates/scriptcheck/src/report.rs @@ -342,10 +342,11 @@ impl<'l> Acc<'l> { } pub fn member(&mut self, path: &str) { - if let Some(n) = self.members.get_mut(path) { + let key = self.echoed(path); + if let Some(n) = self.members.get_mut(&*key) { *n = n.saturating_add(1); } else if self.room(self.members.len()) { - self.members.insert(path.to_string(), 1); + self.members.insert(key.into_owned(), 1); } } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index bb63f00918..1be9aeddbf 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -559,8 +559,8 @@ fn save_as_and_export_file_in_brackets_write_a_file() { } /// `app.open` reads the file it is given, called by name or with its name as a string literal in -/// brackets; a document has no `open` method, and a property or a variable named `app` is not the -/// application. +/// brackets, also through a variable that holds the application; a document has no `open` method, and +/// a property or a variable named `app` is not the application. #[test] fn app_open_reads_a_file() { let r = report(concat!( @@ -570,16 +570,28 @@ fn app_open_reads_a_file() { "app.activeDocument['open'](f);\n", "x.app.open(f);\n", "x.app['open'](f);\n", + "var a = app; a.open(f);\n", + "a['open'](f);\n", + "var b = x.app; b.open(f); b['open'](f);\n", )); - assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(&[2, 3][..])); + assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(&[2, 3, 7, 8][..])); assert!(r.outside.is_empty()); let r = report("var app = {};\napp.open(f);\napp['open'](f);\n"); assert!(feature(&r, "file.read").is_none()); + // A short echo limit cuts the member chains the report lists, not what the check finds. + let short = Limits { echo: 4, ..Limits::default() }; + let src = + "app.open(f);\napp['open'](f);\nvar a = app; a.open(f);\nvar d = app['open'](f); d.print(o);\napp.documents.addDocumentNoUI('P').print(o);\n"; + let r = check("t.jsx", src.as_bytes(), None, &short); + assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(&[1, 2, 3, 4][..])); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5][..])); + assert!(!r.members.is_empty()); + assert!(r.members.iter().all(|m| m.name.chars().count() <= short.echo)); } /// A document's `print` writes the file its options' `jobOptions.file` names, called with a dot or -/// with its name in brackets, on a document (also one `add`, `addDocument`, `addDocumentNoUI` or -/// `app.open`, with or without brackets, returns) or a variable that holds one; reading the method without +/// with its name in brackets, on a document (also one `add`, `addDocument`, `addDocumentNoUI`, `getByName`, +/// `index` or `app.open`, with or without brackets, returns) or a variable that holds one; reading the method without /// calling it, and a `print` method of another object, do not. #[test] fn print_writes_a_file() { @@ -600,8 +612,14 @@ fn print_writes_a_file() { "app.documents.addDocumentNoUI('Print').print(o);\n", "var g = app['open'](new File(p)); g.print(o);\n", "var h = app['activeDocument'](new File(p)); h.print(o);\n", + "app.documents.index(0).print(o);\n", + "documents.index('Print')['print'](o);\n", + "var i = app.documents.index(1); i.print(o);\n", + "app.documents['index'](0).print(o);\n", + "var j = documents['getByName']('Print'); j['print'](o);\n", + "app.documents['length'](0).print(o);\n", )); - let lines = &[2, 3, 5, 9, 10, 11, 12, 13, 14, 15][..]; + let lines = &[2, 3, 5, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21][..]; assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines)); assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", lines)]); } From 3fdd0b206d9637d88f81b329f9792e73950f9c63 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 04:10:59 -0800 Subject: [PATCH 11/72] Scripts: app.open refuses a PDFFileOptions property it does not know A property of `app.open`'s options record other than `pageToOpen` and `pDFCropToBox` that holds a value now throws an error naming it, so a misspelled `pDFCropTobox` no longer opens the file with other settings. `parent`, `typename` and properties left undefined are still ignored. --- crates/engine/src/script/dom/save_open.rs | 7 +++++-- crates/engine/src/tests/script_save_open.rs | 1 + docs/mcp.md | 3 ++- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index b6a5743f51..f973aa31f0 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -30,7 +30,8 @@ //! other value; a property the help pages do not list is left out. With `pDFPreset` named, a //! `PDFSaveOptions` option still at a new object's default keeps the preset's value. //! - `app.open(file, documentColorSpace?, options?)` takes `options` as a `PDFFileOptions` record: -//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. +//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. Any other property +//! that holds a value, except `parent` and `typename`, throws an error. //! - `app.userInteractionLevel` starts at `UserInteractionLevel.DISPLAYALERTS` in each run. The //! commands a script runs never show a dialog, so the level does not change what they do, and it //! never allows a file the script's grants do not. @@ -686,7 +687,9 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { }; p.insert("cropTo".into(), json!(crop)); } - _ => {} + "parent" | "typename" => {} + _ if matches!(v, Data::Undefined) => {} + other => return Err(HostError::Error(format!("PDFFileOptions has no property {other}"))), } } } diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 8518f14365..67be990c00 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -481,6 +481,7 @@ fn bad_arguments_are_refused_with_an_error() { (format!("app.open({f}, undefined, {{pageToOpen: 0}});"), "from 1"), (format!("app.open({f}, undefined, {{pDFCropToBox: 'art'}});"), "PDFBoxType"), (format!("app.open({f}, undefined, 5);"), "PDFFileOptions"), + (format!("app.open({f}, undefined, {{pDFCropTobox: PDFBoxType.PDFMEDIABOX}});"), "no property pDFCropTobox"), ("app.userInteractionLevel = 'quiet';".into(), "UserInteractionLevel"), (format!("app.open({});", quoted(&dir.join("x.svg"))), "open needs a File"), ]; diff --git a/docs/mcp.md b/docs/mcp.md index 11fbdcbc09..494b964d71 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2739,7 +2739,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and `includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with - `pageToOpen` and `pDFCropToBox`. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of + `pageToOpen` and `pDFCropToBox`; any other property that holds a value, except `parent` and `typename`, throws an + error. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, `EPSPostScriptLevelEnum`, `PDFOverprint` and `UserInteractionLevel` hold strings such as `"ExportType.PNG24"`. VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the From dbf10b856e8f3340009096737ab1f34916c7bc17 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:35:34 +0530 Subject: [PATCH 12/72] Fix locked item and group import from Illustrator files (#9176) --- crates/eps/src/import/ai/read/ops.rs | 5 +- crates/eps/src/import/native.rs | 2 +- crates/eps/src/import/native/layers.rs | 94 +++++++++++++++++- crates/eps/src/import/native/slots.rs | 3 + crates/eps/src/import/tests_native.rs | 130 +++++++++++++++++++++++++ crates/pdf/src/import_scan.rs | 65 +++++++++++-- crates/pdf/src/pages.rs | 67 +++++++++++-- crates/pdf/src/tests/import_layers.rs | 105 ++++++++++++++++++++ crates/pdf/tests/import_layers.rs | 53 ++++++++++ 9 files changed, 505 insertions(+), 19 deletions(-) create mode 100644 crates/pdf/tests/import_layers.rs diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 65875c5a52..f267de09fb 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -352,7 +352,7 @@ impl<'a> Reader<'a> { } } "Xw" => self.gs.hidden = Self::nums(&vals).last() == Some(&1.0), - "A" => self.gs.locked = Self::nums(&vals).last() == Some(&1.0), + "A" => self.gs.locked = Self::nums(&vals).last().is_some_and(|&v| v != 0.0), "XW" => self.state_marker(&vals, hidden), // Gradients. "Bd" => self.gradient_def = GradientDef::begin(&vals, &mut self.names), @@ -951,9 +951,12 @@ impl<'a> Reader<'a> { let Some(mut look) = f.children.pop() else { return }; let state = (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape); (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) = (1.0, BlendMode::Normal, false, Knockout::Neutral, false); + let (visible, locked) = (object.visible, object.locked); (object.opacity, object.blend, object.isolate, object.knockout_shape) = (1.0, BlendMode::Normal, false, false); let mut group = Node::group(self.doc.alloc_id(), vec![Arc::new(look), Arc::new(object)]); (group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = state; + group.visible = visible; + group.locked = locked; self.text_looks.insert(group.id); if let Some(f) = self.frames.last_mut() { f.children.push(group); diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index dad13c569f..3cd6105029 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -43,7 +43,7 @@ use super::ate::{Story, Texts}; mod build; pub(super) mod compare; -mod layers; +pub(super) mod layers; mod plan; mod slots; diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index d46da2b8ff..d74029e0f0 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -172,6 +172,8 @@ pub fn layered_ai_from( } // The PDF part, its pages placed and named as the editing data's artboards are, when the // layers can't be used (`why`). + let structure = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)); + let private_layers = structure.as_ref().ok().map(|s| s.doc.layers.clone()).unwrap_or_default(); let from_pdf_part = |mut visible: Document, mut warnings: Vec, why: &str| { let mut read = ai::Names::new(names); let mut board_names = ai::Names::new(names); @@ -179,6 +181,7 @@ pub fn layered_ai_from( if place_pages(&boards, active, &mut visible, unit) { read.absorb(board_names); } + apply_private_layer_locks(&mut visible.layers, &private_layers); let have = visible.patterns.len(); let own_palette = use_palette(&data, &mut visible, &mut read); use_brushes(&data, &mut visible, have, &mut warnings, &mut read); @@ -192,7 +195,7 @@ pub fn layered_ai_from( // The envelopes of type the page doesn't hold against layers that don't draw as it, and how many // envelopes of type the layers had. let (mut free, mut count) = (None, 0); - let built = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)).and_then(|structure| { + let built = structure.and_then(|structure| { count = structure.warped_type.envelope_count(); build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text) }); @@ -238,6 +241,95 @@ fn holds_type_envelope(nodes: &[Arc]) -> bool { }) } +/// Apply lock states from private data layers to visible PDF layers. +pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], private_layers: &[Arc]) { + if private_layers.is_empty() { + return; + } + let mut priv_layer_names = std::collections::HashMap::new(); + for p in private_layers { + if let Some(name) = p.name.as_deref() { + *priv_layer_names.entry(name).or_insert(0usize) += 1; + } + } + + let same_len = visible_layers.len() == private_layers.len(); + for (i, vis) in visible_layers.iter_mut().enumerate() { + let priv_node = if let Some(vis_name) = vis.name.as_deref() { + if priv_layer_names.get(vis_name).copied() == Some(1) { + private_layers.iter().find(|p| p.name.as_deref() == Some(vis_name)) + } else if same_len && private_layers[i].name.as_deref() == Some(vis_name) { + Some(&private_layers[i]) + } else { + None + } + } else if same_len { + Some(&private_layers[i]) + } else { + None + }; + + if let Some(p) = priv_node { + apply_node_locks(Arc::make_mut(vis), p); + } + } +} + +fn apply_node_locks(vis: &mut Node, priv_: &Node) { + if priv_.locked { + vis.locked = true; + } + if let (Some(vis_kids), Some(priv_kids)) = (vis.children_mut(), priv_.children()) { + let mut priv_name_counts = std::collections::HashMap::new(); + for p in priv_kids { + if let Some(name) = p.name.as_deref() { + *priv_name_counts.entry(name).or_insert(0usize) += 1; + } + } + let mut matched_priv = vec![false; priv_kids.len()]; + let mut matched_vis = vec![false; vis_kids.len()]; + + // Pass 1: resolve unique named matches first. + for (v_idx, v) in vis_kids.iter_mut().enumerate() { + if let Some(v_name) = v.name.as_deref() + && priv_name_counts.get(v_name).copied() == Some(1) + && let Some((p_idx, p)) = priv_kids.iter().enumerate().find(|(_, p)| p.name.as_deref() == Some(v_name)) + { + apply_node_locks(Arc::make_mut(v), p); + matched_priv[p_idx] = true; + matched_vis[v_idx] = true; + } + } + + // Pass 2: positional match for remaining children when counts match. + let same_len = vis_kids.len() == priv_kids.len(); + if same_len { + for (idx, v) in vis_kids.iter_mut().enumerate() { + if matched_vis[idx] { + continue; + } + if !matched_priv[idx] && (priv_kids[idx].name.is_none() || v.name == priv_kids[idx].name) { + apply_node_locks(Arc::make_mut(v), &priv_kids[idx]); + matched_priv[idx] = true; + matched_vis[idx] = true; + } + } + } + + // Pass 3: match remaining unmatched unnamed children. + for (v_idx, v) in vis_kids.iter_mut().enumerate() { + if matched_vis[v_idx] || v.name.is_some() { + continue; + } + if let Some((p_idx, p)) = priv_kids.iter().enumerate().find(|(i, p)| !matched_priv[*i] && p.name.is_none()) { + apply_node_locks(Arc::make_mut(v), p); + matched_priv[p_idx] = true; + matched_vis[v_idx] = true; + } + } + } +} + /// The `.ai` whose editing copy is `private` (as [`layered_ai`] takes it) from its layers alone, /// without its PDF part, whose pages (each its trim box in points, width and height) are `pages` /// and are in units of `unit` points (its first page's `UserUnit`): the document and the notes of diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index ebd6deef88..902811af45 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -342,6 +342,8 @@ pub(super) fn fill_slots( (p.opacity, p.blend, p.isolate, p.knockout, p.knockout_shape) = (state.0, state.1, state.2, state.3, shape); } else if transparent { let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); + group.visible = visible; + group.locked = locked; (group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = (state.0, state.1, state.2, state.3, shape); parts.push(Arc::new(group)); @@ -352,6 +354,7 @@ pub(super) fn fill_slots( if parts.len() > 1 { let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); group.visible = visible; + group.locked = locked; parts.push(Arc::new(group)); } for p in &mut parts { diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index f809141202..7118d08481 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8312,3 +8312,133 @@ fn trusted_editing_data_keeps_an_artboard_taller_than_its_pdf_page() { let (_, w, read) = crate::layered_ai(&private(&art), Document::new(12000.0, 14400.0), vec![], false, true, 1.0); assert!(!read, "the uncapped dimension must still match: {w:?}"); } + +/// A locked layer as the format writes it. +fn locked_layer(name: &str, body: &str) -> String { + format!("%AI5_BeginLayer\n1 1 0 1 0 0 1 0 79 128 255 0 50 0 Lb\n({name}) Ln\n{body}\nLB\n%AI5_EndLayer--\n") +} + +#[test] +fn ai_locked_layers_and_groups_preserve_locks() { + let art_locked_group = format!("1 A\nu\n{}\nU\n0 A", square(10, 10)); + let plain_layer = layer("Unlocked Layer", true, &square(0, 0)); + let locked_l = locked_layer("Locked Layer", &art_locked_group); + let n = native(&format!("{plain_layer}{locked_l}")); + let file = private(&n); + let (doc, notes, read) = crate::layered_ai(&file, pdf_part(10.0, 86.0), vec![], false, true, 1.0); + assert!(read, "{notes:?}"); + let unlocked = doc.layers.iter().find(|l| l.name.as_deref() == Some("Unlocked Layer")).unwrap(); + let locked = doc.layers.iter().find(|l| l.name.as_deref() == Some("Locked Layer")).unwrap(); + assert!(!unlocked.locked, "Unlocked Layer is not locked"); + assert!(locked.locked, "Locked Layer retains locked == true"); + let group = locked.children().and_then(|c| c.iter().find(|n| matches!(n.kind, NodeKind::Group { .. }))); + assert!(group.is_some_and(|g| g.locked), "group with 1 A retains locked == true"); +} + +#[test] +fn ai_fallback_to_pdf_part_preserves_private_stream_layer_and_group_locks() { + use std::sync::Arc; + let art_locked_group = format!("1 A\nu\n%_/ArtDictionary :\n%(Locked Subgroup) /String (AIArtName) ,\n%_;\n{}\nU\n0 A", square(10, 10)); + let locked_l = locked_layer("Map Layer", &art_locked_group); + let n = native(&locked_l); + let file = private(&n); + let mut pdf = Document::new(100.0, 100.0); + pdf.layers.clear(); + let mut vis_layer = Node::layer(pdf.alloc_id(), "Map Layer", LayerColor::Preset(0)); + vis_layer.locked = false; + let mut vis_group = Node::group(pdf.alloc_id(), vec![]); + vis_group.name = Some("Locked Subgroup".to_string()); + vis_group.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_group)); + } + pdf.layers.push(Arc::new(vis_layer)); + + let layers = crate::AiLayers::decode(&file); + let (doc, _notes, read) = crate::layered_ai_from(layers, pdf, vec![], false, false, 1.0, crate::NameEncoding::default()); + assert!(!read, "falls back to PDF part"); + let map_layer = doc.layers.iter().find(|l| l.name.as_deref() == Some("Map Layer")).unwrap(); + assert!(map_layer.locked, "Map Layer preserved locked == true from private stream metadata"); + let subgroup = map_layer.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("Locked Subgroup"))).unwrap(); + assert!(subgroup.locked, "Locked Subgroup preserved locked == true from private stream metadata"); +} + +#[test] +fn ai_duplicate_group_names_under_different_layers_preserve_individual_lock_states() { + use std::sync::Arc; + let art_locked_group = format!("1 A\nu\n%_/ArtDictionary :\n%(SharedGroup) /String (AIArtName) ,\n%_;\n{}\nU\n0 A", square(10, 10)); + let art_unlocked_group = format!("0 A\nu\n%_/ArtDictionary :\n%(SharedGroup) /String (AIArtName) ,\n%_;\n{}\nU\n0 A", square(10, 10)); + let layer_a = layer("Layer A", true, &art_locked_group); + let layer_b = layer("Layer B", true, &art_unlocked_group); + let n = native(&format!("{layer_a}{layer_b}")); + let file = private(&n); + + let mut pdf = Document::new(100.0, 100.0); + pdf.layers.clear(); + let mut vis_a = Node::layer(pdf.alloc_id(), "Layer A", LayerColor::Preset(0)); + let mut vis_grp_a = Node::group(pdf.alloc_id(), vec![]); + vis_grp_a.name = Some("SharedGroup".to_string()); + vis_grp_a.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_a.kind { + children.push(Arc::new(vis_grp_a)); + } + + let mut vis_b = Node::layer(pdf.alloc_id(), "Layer B", LayerColor::Preset(1)); + let mut vis_grp_b = Node::group(pdf.alloc_id(), vec![]); + vis_grp_b.name = Some("SharedGroup".to_string()); + vis_grp_b.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_b.kind { + children.push(Arc::new(vis_grp_b)); + } + pdf.layers.push(Arc::new(vis_a)); + pdf.layers.push(Arc::new(vis_b)); + + let layers = crate::AiLayers::decode(&file); + let (doc, _notes, read) = crate::layered_ai_from(layers, pdf, vec![], false, false, 1.0, crate::NameEncoding::default()); + assert!(!read, "falls back to PDF part"); + + let l_a = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer A")).unwrap(); + let l_b = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer B")).unwrap(); + let grp_a = l_a.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("SharedGroup"))).unwrap(); + let grp_b = l_b.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("SharedGroup"))).unwrap(); + + assert!(grp_a.locked, "Layer A's SharedGroup is locked"); + assert!(!grp_b.locked, "Layer B's SharedGroup remains unlocked"); +} + +#[test] +fn ai_reordered_mixed_named_and_unnamed_children_preserve_locks() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + let mut priv_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0)); + let mut priv_unnamed = Node::group(doc.alloc_id(), vec![]); + priv_unnamed.locked = false; + let mut priv_roads = Node::group(doc.alloc_id(), vec![]); + priv_roads.name = Some("Roads".to_string()); + priv_roads.locked = true; + if let NodeKind::Layer { children, .. } = &mut priv_layer.kind { + children.push(Arc::new(priv_unnamed)); + children.push(Arc::new(priv_roads)); + } + + let mut vis_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0)); + let mut vis_roads = Node::group(doc.alloc_id(), vec![]); + vis_roads.name = Some("Roads".to_string()); + vis_roads.locked = false; + let mut vis_unnamed = Node::group(doc.alloc_id(), vec![]); + vis_unnamed.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_roads)); + children.push(Arc::new(vis_unnamed)); + } + + let mut visible_layers = vec![Arc::new(vis_layer)]; + let private_layers = vec![Arc::new(priv_layer)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + let roads = visible_layers[0].children().unwrap()[0].clone(); + let unnamed = visible_layers[0].children().unwrap()[1].clone(); + assert_eq!(roads.name.as_deref(), Some("Roads")); + assert!(roads.locked, "Roads matched by unique name and preserved locked == true"); + assert!(!unnamed.locked, "unnamed child matched to unlocked private child"); +} diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index 6b812224e2..0b21aadce9 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -83,6 +83,8 @@ pub(crate) struct Ocgs { view_auto: HashSet, /// The groups placed in the layer order. placed: HashSet, + /// The groups that are locked in configuration or dictionary flags. + locked: HashSet, } impl Ocgs { @@ -95,9 +97,13 @@ impl Ocgs { }; let config = props.get::>(b"D").unwrap_or_default(); let refs = |d: &Dict<'_>, key: &[u8]| -> Vec { - d.get::>(key) - .map(|a| items(&a).filter_map(|i| i.as_obj_ref()).map(ObjectIdentifier::from).take(MAX_GROUPS).collect()) - .unwrap_or_default() + if let Some(a) = d.get::>(key) { + items(&a).filter_map(|i| i.as_obj_ref()).map(ObjectIdentifier::from).take(MAX_GROUPS).collect() + } else if let Some(r) = d.get_ref(key) { + vec![ObjectIdentifier::from(r)] + } else { + Vec::new() + } }; let all = refs(&props, b"OCGs"); if config.get::>(b"BaseState").is_some_and(|n| n.as_ref() == b"OFF") { @@ -111,10 +117,13 @@ impl Ocgs { for d in auto.iter().filter(|d| d.get::>(b"Event").is_some_and(|e| e.as_ref() == b"View")) { o.view_auto.extend(refs(d, b"OCGs")); } - let locked: HashSet<_> = refs(&config, b"Locked").into_iter().collect(); + let mut locked: HashSet<_> = refs(&config, b"Locked").into_iter().collect(); + locked.extend(refs(&props, b"Locked")); + o.locked = locked; for id in all { if let Some(d) = xref.get::>(id) { - o.add(id, &d, locked.contains(&id)); + let is_locked = o.is_locked(id, &d); + o.add(id, &d, is_locked); } } if let Some(order) = config.get::>(b"Order") { @@ -170,6 +179,7 @@ impl Ocgs { if let Some(i) = self.index.get(&id) { return *i; } + let locked = locked || self.is_locked(id, d); let name = d.get::>(b"Name").map(|s| text_string(s.as_bytes())).unwrap_or_default(); let print = usage(d, b"Print", b"PrintState") != Some(false); // A view state applies when the configuration says so on opening; an off one hides the @@ -186,6 +196,11 @@ impl Ocgs { self.list.len() - 1 } + /// Is group `id` (dictionary `d`) locked according to configuration or dictionary flags? + fn is_locked(&self, id: ObjectIdentifier, d: &Dict<'_>) -> bool { + self.locked.contains(&id) || is_ocg_dict_locked(d) + } + /// Does the interpreter leave out the art of some group (off in the default configuration)? pub fn skips_any(&self) -> bool { self.index.keys().any(|id| self.off.contains(id)) @@ -206,11 +221,49 @@ impl Ocgs { fn note(&mut self, id: ObjectIdentifier, d: &Dict<'_>) -> Option { match self.index.get(&id) { Some(i) => Some(*i), - None => (self.list.len() < MAX_GROUPS).then(|| self.add(id, d, false)), + None => { + let is_locked = self.is_locked(id, d); + (self.list.len() < MAX_GROUPS).then(|| self.add(id, d, is_locked)) + } } } } +/// Is group dictionary `d` flagged as locked (directly or in its `/Usage`)? +fn is_ocg_dict_locked(d: &Dict<'_>) -> bool { + if d.get::(b"Locked") == Some(true) + || d.get::>(b"Locked").is_some_and(|n| { + let b = n.as_ref(); + b.eq_ignore_ascii_case(b"true") || b.eq_ignore_ascii_case(b"locked") || b.eq_ignore_ascii_case(b"on") + }) + { + return true; + } + if let Some(usage) = d.get::>(b"Usage") { + if usage.get::(b"Locked") == Some(true) + || usage.get::>(b"Locked").is_some_and(|n| { + let b = n.as_ref(); + b.eq_ignore_ascii_case(b"true") || b.eq_ignore_ascii_case(b"locked") || b.eq_ignore_ascii_case(b"on") + }) + { + return true; + } + if let Some(user) = usage.get::>(b"User") + && (user.get::(b"Locked") == Some(true) + || user.get::>(b"Type").is_some_and(|n| n.as_ref().eq_ignore_ascii_case(b"locked")) + || user.get::>(b"User").is_some_and(|s| s.as_bytes().eq_ignore_ascii_case(b"locked"))) + { + return true; + } + if let Some(lock) = usage.get::>(b"Lock") + && lock.get::(b"Locked") != Some(false) + { + return true; + } + } + false +} + /// The state (`ON` → true, `OFF` → false) group `d`'s usage `category` gives in `key`. fn usage(d: &Dict<'_>, category: &[u8], key: &[u8]) -> Option { let state = d.get::>(b"Usage")?.get::>(category)?.get::>(key)?; diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 688964d8db..76d7b0fb33 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -539,11 +539,30 @@ fn private_data(pdf: &Pdf) -> Option> { /// [`private_data`], with why a private data stream can't be read ([`inflated`]). fn read_private_data(pdf: &Pdf) -> Result>, String> { - let Some(private) = pdf + let xref = pdf.xref(); + let page_private = pdf .pages() .first() - .and_then(|page| page.raw().get::>(b"PieceInfo")?.get::>(PRIVATE_DATA_OWNER)?.get::>(b"Private")) - else { + .and_then(|page| page.raw().get::>(b"PieceInfo")?.get::>(PRIVATE_DATA_OWNER)?.get::>(b"Private")); + let root_private = xref + .get::>(xref.root_id()) + .and_then(|root| root.get::>(b"PieceInfo")?.get::>(PRIVATE_DATA_OWNER)?.get::>(b"Private")); + let has_supported_data = |dict: &Dict<'_>| dict.contains_key(b"AIPrivateData1") || dict.contains_key(b"AIPDFPrivateData1"); + let private = match (page_private, root_private) { + (Some(page), Some(root)) => { + if has_supported_data(&page) { + Some(page) + } else if has_supported_data(&root) { + Some(root) + } else { + Some(page) + } + } + (Some(page), None) => Some(page), + (None, Some(root)) => Some(root), + (None, None) => None, + }; + let Some(private) = private else { return Ok(None); }; let key = if private.contains_key(b"AIPrivateData1") { "AIPrivateData" } else { "AIPDFPrivateData" }; @@ -564,7 +583,9 @@ pub fn has_illustrator_data(bytes: &[u8], password: Option<&str>) -> bool { /// [`has_illustrator_data`] of a parsed PDF. fn has_private_data_keys(pdf: &Pdf) -> bool { + let xref = pdf.xref(); pdf.pages().first().is_some_and(|p| piece_info_has(p, &[b"AIPrivateData", b"AIPDFPrivateData"])) + || xref.get::>(xref.root_id()).is_some_and(|root| dict_piece_info_has(&root, &[b"AIPrivateData", b"AIPDFPrivateData"])) } /// `stream` decoded, up to `most` bytes: the decoder is run here rather than by the PDF reader's @@ -627,15 +648,41 @@ pub(crate) fn states_art(page: &Page<'_>) -> bool { [&b"ArtBox"[..], b"TrimBox", b"BleedBox"].iter().any(|k| page.raw().get::<[f32; 4]>(*k).is_some()) } +/// Does dictionary `d`'s `PieceInfo` hold a key starting with one of `prefixes`, up to four dictionaries in? +fn dict_has_piece_info_prefix(d: &Dict<'_>, prefixes: &[&[u8]]) -> bool { + const MAX_VISITS: usize = 128; + fn walk(d: &Dict<'_>, prefixes: &[&[u8]], depth: u32, budget: &mut usize) -> bool { + if depth >= 4 || *budget == 0 { + return false; + } + for k in d.keys() { + if *budget == 0 { + return false; + } + *budget -= 1; + if prefixes.iter().any(|p| k.starts_with(p)) { + return true; + } + if let Some(sub) = d.get::>(k.as_ref()) + && walk(&sub, prefixes, depth + 1, budget) + { + return true; + } + } + false + } + let mut budget = MAX_VISITS; + walk(d, prefixes, 0, &mut budget) +} + /// Does `page`'s `PieceInfo` hold a key starting with one of `prefixes`, up to four dictionaries in? fn piece_info_has(page: &Page<'_>, prefixes: &[&[u8]]) -> bool { - fn walk(d: &Dict<'_>, prefixes: &[&[u8]], depth: u32) -> bool { - depth < 4 - && d.keys().any(|k| { - prefixes.iter().any(|p| k.starts_with(p)) || d.get::>(k.as_ref()).is_some_and(|sub| walk(&sub, prefixes, depth + 1)) - }) - } - page.raw().get::>(b"PieceInfo").is_some_and(|d| walk(&d, prefixes, 0)) + page.raw().get::>(b"PieceInfo").is_some_and(|d| dict_has_piece_info_prefix(&d, prefixes)) +} + +/// Does dictionary `d`'s `PieceInfo` hold a key starting with one of `prefixes`, up to four dictionaries in? +fn dict_piece_info_has(d: &Dict<'_>, prefixes: &[&[u8]]) -> bool { + d.get::>(b"PieceInfo").is_some_and(|p| dict_has_piece_info_prefix(&p, prefixes)) } #[cfg(test)] diff --git a/crates/pdf/src/tests/import_layers.rs b/crates/pdf/src/tests/import_layers.rs index c0f9dfc970..56492fe30a 100644 --- a/crates/pdf/src/tests/import_layers.rs +++ b/crates/pdf/src/tests/import_layers.rs @@ -469,3 +469,108 @@ fn art_deep_in_tags_inside_a_layer_reaches_it() { let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); assert_eq!(colors(shapes), [Color::rgb(1.0, 0.0, 0.0)]); } + +#[test] +fn ocg_dictionary_locked_flag_is_read() { + let (a, b) = (first_extra(1), first_extra(1) + 1); + let objs = ["<< /Type /OCG /Name (Shapes) /Locked true >>".to_string(), "<< /Type /OCG /Name (Plain) >>".to_string()]; + let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << /Order [{a} 0 R {b} 0 R] >> >> "); + let bytes = pdf_with_catalog(&[page([a, b])], &[&objs[0], &objs[1]], &catalog, None); + let d = import(&bytes).unwrap(); + let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); + let plain = d.layers.iter().find(|l| l.name.as_deref() == Some("Plain")).unwrap(); + assert!(shapes.locked, "Shapes has /Locked true in its dictionary"); + assert!(!plain.locked, "Plain is not locked"); +} + +#[test] +fn ocg_dictionary_usage_locked_is_read() { + let (a, b) = (first_extra(1), first_extra(1) + 1); + let objs = ["<< /Type /OCG /Name (Shapes) /Usage << /User << /Type /Locked >> >> >>".to_string(), "<< /Type /OCG /Name (Plain) >>".to_string()]; + let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << /Order [{a} 0 R {b} 0 R] >> >> "); + let bytes = pdf_with_catalog(&[page([a, b])], &[&objs[0], &objs[1]], &catalog, None); + let d = import(&bytes).unwrap(); + let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); + let plain = d.layers.iter().find(|l| l.name.as_deref() == Some("Plain")).unwrap(); + assert!(shapes.locked, "Shapes has /Usage << /User << /Type /Locked >> >>"); + assert!(!plain.locked, "Plain is not locked"); +} + +#[test] +fn oc_properties_root_locked_is_read_and_configs_locked_is_ignored() { + let (a, b) = (first_extra(1), first_extra(1) + 1); + let objs = ["<< /Type /OCG /Name (RootLocked) >>".to_string(), "<< /Type /OCG /Name (ConfigUnlocked) >>".to_string()]; + let catalog = format!( + "/OCProperties << /OCGs [{a} 0 R {b} 0 R] /Locked [{a} 0 R] /Configs [<< /Locked [{b} 0 R] >>] /D << /Order [{a} 0 R {b} 0 R] >> >> " + ); + let bytes = pdf_with_catalog(&[page([a, b])], &[&objs[0], &objs[1]], &catalog, None); + let d = import(&bytes).unwrap(); + let root_locked = d.layers.iter().find(|l| l.name.as_deref() == Some("RootLocked")).unwrap(); + let config_unlocked = d.layers.iter().find(|l| l.name.as_deref() == Some("ConfigUnlocked")).unwrap(); + assert!(root_locked.locked, "RootLocked is in /OCProperties /Locked"); + assert!(!config_unlocked.locked, "ConfigUnlocked is only in alternate /Configs /Locked, so stays unlocked"); +} + +#[test] +fn ocg_noted_from_content_stream_retains_lock() { + let (a, b) = (first_extra(1), first_extra(1) + 1); + let objs = ["<< /Type /OCG /Name (UnlistedLocked) /Locked true >>".to_string(), "<< /Type /OCG /Name (Listed) >>".to_string()]; + // /OCGs only lists {b} (Listed). {a} (UnlistedLocked) is not in /OCGs or /Order. + let catalog = format!("/OCProperties << /OCGs [{b} 0 R] /D << /Order [{b} 0 R] >> >> "); + let content = "/OC /MC0 BDC 1 0 0 rg 10 10 30 30 re f EMC /OC /MC1 BDC 0 1 0 rg 0 0 5 5 re f EMC"; + let p = PdfPage { resources: format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R >>"), ..PdfPage::new(100.0, 100.0, content) }; + let bytes = pdf_with_catalog(&[p], &[&objs[0], &objs[1]], &catalog, None); + let d = import(&bytes).unwrap(); + let unlisted = d.layers.iter().find(|l| l.name.as_deref() == Some("UnlistedLocked")).unwrap(); + let listed = d.layers.iter().find(|l| l.name.as_deref() == Some("Listed")).unwrap(); + assert!(unlisted.locked, "UnlistedLocked has /Locked true in its dictionary"); + assert!(!listed.locked, "Listed is not locked"); +} + +#[test] +fn ai_fixture_with_locked_group_and_locked_object_imports_with_locks_preserved() { + let (a, b, c, d) = (first_extra(1), first_extra(1) + 1, first_extra(1) + 2, first_extra(1) + 3); + let order_obj = first_extra(1) + 4; + let objs = [ + "<< /Type /OCG /Name (Layer1) >>".to_string(), + "<< /Type /OCG /Name (LockedGroup) /Locked true >>".to_string(), + "<< /Type /OCG /Name (UnlockedGroup) >>".to_string(), + "<< /Type /OCG /Name (LockedObject) /Locked true >>".to_string(), + ]; + let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R {c} 0 R {d} 0 R] /D << /Order {order_obj} 0 R >> >> "); + let order_body = format!("[{a} 0 R [{b} 0 R {c} 0 R]]"); + let content = "/OC /MC0 BDC 1 0 0 rg 10 10 20 20 re f EMC \ + /OC /MC1 BDC 0 1 0 rg 30 30 20 20 re f EMC \ + /OC /MC2 BDC 0 0 1 rg 50 50 20 20 re f EMC \ + /OC /MC3 BDC 1 1 0 rg 70 70 20 20 re f EMC \ + 0 0 0 rg 0 0 10 10 re f"; + let page = PdfPage { + resources: format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R /MC2 {c} 0 R /MC3 {d} 0 R >>"), + entries: "/PieceInfo << /Illustrator << /Private << /AIPrivateData1 7 /NumBlock 1 >> >> >>".into(), + ..PdfPage::new(100.0, 100.0, content) + }; + let bytes = pdf_with_catalog(&[page], &[&objs[0], &objs[1], &objs[2], &objs[3], &order_body], &catalog, None); + let doc = import(&bytes).unwrap(); + + let layer1 = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer1")).expect("Layer1 exists"); + assert!(!layer1.locked, "Layer1 is not locked"); + + let children = layer1.children().expect("Layer1 has children"); + let locked_group = children.iter().find(|n| n.name.as_deref() == Some("LockedGroup")).expect("LockedGroup exists"); + assert!(locked_group.locked, "LockedGroup has locked: true"); + + let unlocked_group = children.iter().find(|n| n.name.as_deref() == Some("UnlockedGroup")).expect("UnlockedGroup exists"); + assert!(!unlocked_group.locked, "UnlockedGroup has locked: false"); + + let locked_obj = doc.layers.iter().find(|l| l.name.as_deref() == Some("LockedObject")).expect("LockedObject exists"); + assert!(locked_obj.locked, "LockedObject has locked: true"); + + if let Some(page_layer) = doc.layers.iter().find(|l| l.name.as_deref() == Some("Page 1")) { + assert!(!page_layer.locked, "Page layer is not locked"); + if let Some(kids) = page_layer.children() { + for kid in kids { + assert!(!kid.locked, "Non-locked object in page layer remains unlocked"); + } + } + } +} diff --git a/crates/pdf/tests/import_layers.rs b/crates/pdf/tests/import_layers.rs new file mode 100644 index 0000000000..a82bb7a415 --- /dev/null +++ b/crates/pdf/tests/import_layers.rs @@ -0,0 +1,53 @@ +//! Synthetic regression verifying locked group and locked object import in AI fixtures. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use vectorcraft_pdf::import; +use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with_catalog}; + +#[test] +fn ai_fixture_with_locked_group_and_locked_object_imports_with_locks_preserved() { + let (a, b, c, d) = (first_extra(1), first_extra(1) + 1, first_extra(1) + 2, first_extra(1) + 3); + let order_obj = first_extra(1) + 4; + let objs = [ + "<< /Type /OCG /Name (Layer1) >>".to_string(), + "<< /Type /OCG /Name (LockedGroup) /Locked true >>".to_string(), + "<< /Type /OCG /Name (UnlockedGroup) >>".to_string(), + "<< /Type /OCG /Name (LockedObject) /Locked true >>".to_string(), + ]; + let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R {c} 0 R {d} 0 R] /D << /Order {order_obj} 0 R >> >> "); + let order_body = format!("[{a} 0 R [{b} 0 R {c} 0 R]]"); + let content = "/OC /MC0 BDC 1 0 0 rg 10 10 20 20 re f EMC \ + /OC /MC1 BDC 0 1 0 rg 30 30 20 20 re f EMC \ + /OC /MC2 BDC 0 0 1 rg 50 50 20 20 re f EMC \ + /OC /MC3 BDC 1 1 0 rg 70 70 20 20 re f EMC \ + 0 0 0 rg 0 0 10 10 re f"; + let page = PdfPage { + resources: format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R /MC2 {c} 0 R /MC3 {d} 0 R >>"), + entries: "/PieceInfo << /Illustrator << /Private << /AIPrivateData1 7 /NumBlock 1 >> >> >>".into(), + ..PdfPage::new(100.0, 100.0, content) + }; + let bytes = pdf_with_catalog(&[page], &[&objs[0], &objs[1], &objs[2], &objs[3], &order_body], &catalog, None); + let doc = import(&bytes).unwrap(); + + let layer1 = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer1")).expect("Layer1 exists"); + assert!(!layer1.locked, "Layer1 is not locked"); + + let children = layer1.children().expect("Layer1 has children"); + let locked_group = children.iter().find(|n| n.name.as_deref() == Some("LockedGroup")).expect("LockedGroup exists"); + assert!(locked_group.locked, "LockedGroup has locked: true"); + + let unlocked_group = children.iter().find(|n| n.name.as_deref() == Some("UnlockedGroup")).expect("UnlockedGroup exists"); + assert!(!unlocked_group.locked, "UnlockedGroup has locked: false"); + + let locked_obj = doc.layers.iter().find(|l| l.name.as_deref() == Some("LockedObject")).expect("LockedObject exists"); + assert!(locked_obj.locked, "LockedObject has locked: true"); + + if let Some(page_layer) = doc.layers.iter().find(|l| l.name.as_deref() == Some("Page 1")) { + assert!(!page_layer.locked, "Page layer is not locked"); + if let Some(kids) = page_layer.children() { + for kid in kids { + assert!(!kid.locked, "Non-locked object in page layer remains unlocked"); + } + } + } +} From 6c6c65b9e08bb178ba5649e5fc8a986758d0d2cf Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:45:06 +0530 Subject: [PATCH 13/72] Address CodeRabbit review feedback on layer and child lock matching --- crates/eps/src/import/native/layers.rs | 133 ++++++++++++++---------- crates/eps/src/import/tests_native.rs | 137 +++++++++++++++++++++++++ crates/pdf/src/pages.rs | 5 + 3 files changed, 222 insertions(+), 53 deletions(-) diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index d74029e0f0..fa64adbb67 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -243,36 +243,58 @@ fn holds_type_envelope(nodes: &[Arc]) -> bool { /// Apply lock states from private data layers to visible PDF layers. pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], private_layers: &[Arc]) { - if private_layers.is_empty() { + if private_layers.is_empty() || visible_layers.is_empty() { return; } - let mut priv_layer_names = std::collections::HashMap::new(); - for p in private_layers { + + // Index private layers: name -> (count, first_index) + let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); + for (i, p) in private_layers.iter().enumerate() { if let Some(name) = p.name.as_deref() { - *priv_layer_names.entry(name).or_insert(0usize) += 1; + let entry = priv_names.entry(name).or_insert((0, i)); + entry.0 += 1; } } - let same_len = visible_layers.len() == private_layers.len(); - for (i, vis) in visible_layers.iter_mut().enumerate() { - let priv_node = if let Some(vis_name) = vis.name.as_deref() { - if priv_layer_names.get(vis_name).copied() == Some(1) { - private_layers.iter().find(|p| p.name.as_deref() == Some(vis_name)) - } else if same_len && private_layers[i].name.as_deref() == Some(vis_name) { - Some(&private_layers[i]) - } else { - None - } - } else if same_len { - Some(&private_layers[i]) - } else { - None - }; - - if let Some(p) = priv_node { - apply_node_locks(Arc::make_mut(vis), p); + // Index visible layers: name -> count + let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for v in visible_layers.iter() { + if let Some(name) = v.name.as_deref() { + *vis_names.entry(name).or_insert(0) += 1; } } + + let mut matched_vis = vec![false; visible_layers.len()]; + let mut matched_priv = vec![false; private_layers.len()]; + let mut pairs = Vec::new(); + + // Pass 1: Unique named matches + for (v_idx, vis) in visible_layers.iter().enumerate() { + if let Some(name) = vis.name.as_deref() + && vis_names.get(name).copied() == Some(1) + && let Some(&(1, p_idx)) = priv_names.get(name) + && !matched_priv[p_idx] + { + matched_vis[v_idx] = true; + matched_priv[p_idx] = true; + pairs.push((v_idx, p_idx)); + } + } + + // Pass 2: Pair remaining unmatched layers in relative order when counts match + let unmatched_v: Vec = (0..visible_layers.len()).filter(|&i| !matched_vis[i]).collect(); + let unmatched_p: Vec = (0..private_layers.len()).filter(|&i| !matched_priv[i]).collect(); + if unmatched_v.len() == unmatched_p.len() { + for (&v_idx, &p_idx) in unmatched_v.iter().zip(unmatched_p.iter()) { + pairs.push((v_idx, p_idx)); + } + } else if unmatched_v.len() == 1 && unmatched_p.len() == 1 { + pairs.push((unmatched_v[0], unmatched_p[0])); + } + + for (v_idx, p_idx) in pairs { + apply_node_locks(Arc::make_mut(&mut visible_layers[v_idx]), &private_layers[p_idx]); + } } fn apply_node_locks(vis: &mut Node, priv_: &Node) { @@ -280,52 +302,57 @@ fn apply_node_locks(vis: &mut Node, priv_: &Node) { vis.locked = true; } if let (Some(vis_kids), Some(priv_kids)) = (vis.children_mut(), priv_.children()) { - let mut priv_name_counts = std::collections::HashMap::new(); - for p in priv_kids { + if vis_kids.is_empty() || priv_kids.is_empty() { + return; + } + + // Index private children: name -> (count, first_index) + let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); + for (i, p) in priv_kids.iter().enumerate() { if let Some(name) = p.name.as_deref() { - *priv_name_counts.entry(name).or_insert(0usize) += 1; + let entry = priv_names.entry(name).or_insert((0, i)); + entry.0 += 1; } } - let mut matched_priv = vec![false; priv_kids.len()]; + + // Index visible children: name -> count + let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for v in vis_kids.iter() { + if let Some(name) = v.name.as_deref() { + *vis_names.entry(name).or_insert(0) += 1; + } + } + let mut matched_vis = vec![false; vis_kids.len()]; + let mut matched_priv = vec![false; priv_kids.len()]; + let mut pairs = Vec::new(); // Pass 1: resolve unique named matches first. - for (v_idx, v) in vis_kids.iter_mut().enumerate() { + for (v_idx, v) in vis_kids.iter().enumerate() { if let Some(v_name) = v.name.as_deref() - && priv_name_counts.get(v_name).copied() == Some(1) - && let Some((p_idx, p)) = priv_kids.iter().enumerate().find(|(_, p)| p.name.as_deref() == Some(v_name)) + && vis_names.get(v_name).copied() == Some(1) + && let Some(&(1, p_idx)) = priv_names.get(v_name) + && !matched_priv[p_idx] { - apply_node_locks(Arc::make_mut(v), p); - matched_priv[p_idx] = true; matched_vis[v_idx] = true; + matched_priv[p_idx] = true; + pairs.push((v_idx, p_idx)); } } - // Pass 2: positional match for remaining children when counts match. - let same_len = vis_kids.len() == priv_kids.len(); - if same_len { - for (idx, v) in vis_kids.iter_mut().enumerate() { - if matched_vis[idx] { - continue; - } - if !matched_priv[idx] && (priv_kids[idx].name.is_none() || v.name == priv_kids[idx].name) { - apply_node_locks(Arc::make_mut(v), &priv_kids[idx]); - matched_priv[idx] = true; - matched_vis[idx] = true; - } + // Pass 2: pair remaining unmatched children in relative order when counts match. + let unmatched_v: Vec = (0..vis_kids.len()).filter(|&i| !matched_vis[i]).collect(); + let unmatched_p: Vec = (0..priv_kids.len()).filter(|&i| !matched_priv[i]).collect(); + if unmatched_v.len() == unmatched_p.len() { + for (&v_idx, &p_idx) in unmatched_v.iter().zip(unmatched_p.iter()) { + pairs.push((v_idx, p_idx)); } + } else if unmatched_v.len() == 1 && unmatched_p.len() == 1 { + pairs.push((unmatched_v[0], unmatched_p[0])); } - // Pass 3: match remaining unmatched unnamed children. - for (v_idx, v) in vis_kids.iter_mut().enumerate() { - if matched_vis[v_idx] || v.name.is_some() { - continue; - } - if let Some((p_idx, p)) = priv_kids.iter().enumerate().find(|(i, p)| !matched_priv[*i] && p.name.is_none()) { - apply_node_locks(Arc::make_mut(v), p); - matched_priv[p_idx] = true; - matched_vis[v_idx] = true; - } + for (v_idx, p_idx) in pairs { + apply_node_locks(Arc::make_mut(&mut vis_kids[v_idx]), &priv_kids[p_idx]); } } } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 7118d08481..8fc5e2541b 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8442,3 +8442,140 @@ fn ai_reordered_mixed_named_and_unnamed_children_preserve_locks() { assert!(roads.locked, "Roads matched by unique name and preserved locked == true"); assert!(!unnamed.locked, "unnamed child matched to unlocked private child"); } + +#[test] +fn ai_reordered_three_children_roads_triangle_circle_preserve_locks() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + // Private children: [Roads (unlocked), locked triangle (unnamed), unlocked circle (unnamed)] + let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut priv_roads = Node::group(doc.alloc_id(), vec![]); + priv_roads.name = Some("Roads".to_string()); + priv_roads.locked = false; + let mut priv_triangle = Node::group(doc.alloc_id(), vec![]); + priv_triangle.locked = true; + let mut priv_circle = Node::group(doc.alloc_id(), vec![]); + priv_circle.locked = false; + if let NodeKind::Layer { children, .. } = &mut priv_layer.kind { + children.push(Arc::new(priv_roads)); + children.push(Arc::new(priv_triangle)); + children.push(Arc::new(priv_circle)); + } + + // Visible children: [triangle (unnamed), circle (unnamed), Roads] + let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut vis_triangle = Node::group(doc.alloc_id(), vec![]); + vis_triangle.locked = false; + let mut vis_circle = Node::group(doc.alloc_id(), vec![]); + vis_circle.locked = false; + let mut vis_roads = Node::group(doc.alloc_id(), vec![]); + vis_roads.name = Some("Roads".to_string()); + vis_roads.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_triangle)); + children.push(Arc::new(vis_circle)); + children.push(Arc::new(vis_roads)); + } + + let mut visible_layers = vec![Arc::new(vis_layer)]; + let private_layers = vec![Arc::new(priv_layer)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + let vis_tri = visible_layers[0].children().unwrap()[0].clone(); + let vis_circ = visible_layers[0].children().unwrap()[1].clone(); + let vis_rd = visible_layers[0].children().unwrap()[2].clone(); + + assert!(vis_tri.locked, "triangle matched to locked private triangle in relative order"); + assert!(!vis_circ.locked, "circle matched to unlocked private circle in relative order"); + assert!(!vis_rd.locked, "Roads matched to unlocked private Roads by unique name"); +} + +#[test] +fn ai_fallback_with_generated_page_name_preserves_private_layer_lock() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + let mut priv_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0)); + priv_layer.locked = true; + let mut vis_layer = Node::layer(doc.alloc_id(), "Page 1", LayerColor::Preset(0)); + vis_layer.locked = false; + + let mut visible_layers = vec![Arc::new(vis_layer)]; + let private_layers = vec![Arc::new(priv_layer)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + assert_eq!(visible_layers[0].name.as_deref(), Some("Page 1")); + assert!(visible_layers[0].locked, "Page 1 layer matched to locked private layer Map positionally"); +} + +#[test] +fn ai_named_locked_private_child_pairs_with_unnamed_visible_child() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut priv_unnamed = Node::group(doc.alloc_id(), vec![]); + priv_unnamed.locked = false; + let mut priv_roads = Node::group(doc.alloc_id(), vec![]); + priv_roads.name = Some("Roads".to_string()); + priv_roads.locked = true; + if let NodeKind::Layer { children, .. } = &mut priv_layer.kind { + children.push(Arc::new(priv_unnamed)); + children.push(Arc::new(priv_roads)); + } + + let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut vis_first = Node::group(doc.alloc_id(), vec![]); + vis_first.locked = false; + let mut vis_second = Node::group(doc.alloc_id(), vec![]); + vis_second.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_first)); + children.push(Arc::new(vis_second)); + } + + let mut visible_layers = vec![Arc::new(vis_layer)]; + let private_layers = vec![Arc::new(priv_layer)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + let first = visible_layers[0].children().unwrap()[0].clone(); + let second = visible_layers[0].children().unwrap()[1].clone(); + assert!(!first.locked, "first unnamed visible group is unlocked"); + assert!(second.locked, "second unnamed visible group pairs positionally with locked Roads group"); +} + +#[test] +fn ai_duplicate_visible_name_does_not_lock_multiple_from_single_private_node() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut priv_roads = Node::group(doc.alloc_id(), vec![]); + priv_roads.name = Some("Roads".to_string()); + priv_roads.locked = true; + let mut priv_buildings = Node::group(doc.alloc_id(), vec![]); + priv_buildings.name = Some("Buildings".to_string()); + priv_buildings.locked = false; + if let NodeKind::Layer { children, .. } = &mut priv_layer.kind { + children.push(Arc::new(priv_roads)); + children.push(Arc::new(priv_buildings)); + } + + let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); + let mut vis_roads1 = Node::group(doc.alloc_id(), vec![]); + vis_roads1.name = Some("Roads".to_string()); + vis_roads1.locked = false; + let mut vis_roads2 = Node::group(doc.alloc_id(), vec![]); + vis_roads2.name = Some("Roads".to_string()); + vis_roads2.locked = false; + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_roads1)); + children.push(Arc::new(vis_roads2)); + } + + let mut visible_layers = vec![Arc::new(vis_layer)]; + let private_layers = vec![Arc::new(priv_layer)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + let r1 = visible_layers[0].children().unwrap()[0].clone(); + let r2 = visible_layers[0].children().unwrap()[1].clone(); + assert!(r1.locked, "first Roads group receives the lock from private Roads"); + assert!(!r2.locked, "second Roads group remains unlocked, avoiding duplicate private lock propagation"); +} diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 76d7b0fb33..f058913a76 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -650,6 +650,11 @@ pub(crate) fn states_art(page: &Page<'_>) -> bool { /// Does dictionary `d`'s `PieceInfo` hold a key starting with one of `prefixes`, up to four dictionaries in? fn dict_has_piece_info_prefix(d: &Dict<'_>, prefixes: &[&[u8]]) -> bool { + if let Some(priv_dict) = d.get::>(PRIVATE_DATA_OWNER).and_then(|i| i.get::>(b"Private")) + && prefixes.iter().any(|p| priv_dict.keys().any(|k| k.starts_with(p))) + { + return true; + } const MAX_VISITS: usize = 128; fn walk(d: &Dict<'_>, prefixes: &[&[u8]], depth: u32, budget: &mut usize) -> bool { if depth >= 4 || *budget == 0 { From 052276373b1a1a95d84abee45afd3a32b94584eb Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:36:46 +0530 Subject: [PATCH 14/72] Address review feedback on lock propagation, node cloning, and catalog private data --- crates/eps/src/import/ai/read/ops.rs | 1 + crates/eps/src/import/native/layers.rs | 129 ++++++++++++------------- crates/eps/src/import/native/slots.rs | 6 ++ crates/eps/src/import/tests_native.rs | 71 +++++++++++--- crates/pdf/src/import/entry.rs | 5 +- crates/pdf/src/pages.rs | 9 +- crates/pdf/tests/import_layers.rs | 25 +++++ 7 files changed, 158 insertions(+), 88 deletions(-) diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index f267de09fb..acde018009 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -953,6 +953,7 @@ impl<'a> Reader<'a> { (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) = (1.0, BlendMode::Normal, false, Knockout::Neutral, false); let (visible, locked) = (object.visible, object.locked); (object.opacity, object.blend, object.isolate, object.knockout_shape) = (1.0, BlendMode::Normal, false, false); + object.locked = false; let mut group = Node::group(self.doc.alloc_id(), vec![Arc::new(look), Arc::new(object)]); (group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = state; group.visible = visible; diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index fa64adbb67..1982fefd64 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -173,7 +173,8 @@ pub fn layered_ai_from( // The PDF part, its pages placed and named as the editing data's artboards are, when the // layers can't be used (`why`). let structure = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)); - let private_layers = structure.as_ref().ok().map(|s| s.doc.layers.clone()).unwrap_or_default(); + let private_layers: Vec = + structure.as_ref().ok().map(|s| s.doc.layers.iter().map(|l| LockTree::from_node(l)).collect()).unwrap_or_default(); let from_pdf_part = |mut visible: Document, mut warnings: Vec, why: &str| { let mut read = ai::Names::new(names); let mut board_names = ai::Names::new(names); @@ -241,13 +242,38 @@ fn holds_type_envelope(nodes: &[Arc]) -> bool { }) } +/// Lightweight lock metadata snapshot of a node hierarchy, preserving names and lock states +/// without holding `Arc` references to the artwork tree. +#[derive(Clone, Debug, Default)] +pub(crate) struct LockTree { + pub name: Option, + pub locked: bool, + pub children: Vec, +} + +impl LockTree { + pub fn from_node(node: &Node) -> Self { + Self { + name: node.name.clone(), + locked: node.locked, + children: node.children().map(|kids| kids.iter().map(|k| Self::from_node(k)).collect()).unwrap_or_default(), + } + } +} + /// Apply lock states from private data layers to visible PDF layers. -pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], private_layers: &[Arc]) { +pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], private_layers: &[LockTree]) { if private_layers.is_empty() || visible_layers.is_empty() { return; } - // Index private layers: name -> (count, first_index) + // A document with a single visible layer and a single private layer pairs them directly. + if visible_layers.len() == 1 && private_layers.len() == 1 { + apply_node_locks(Arc::make_mut(&mut visible_layers[0]), &private_layers[0]); + return; + } + + // Otherwise, match only layers with identifiable correspondence (matching unique names). let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); for (i, p) in private_layers.iter().enumerate() { if let Some(name) = p.name.as_deref() { @@ -256,7 +282,6 @@ pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], privat } } - // Index visible layers: name -> count let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); for v in visible_layers.iter() { if let Some(name) = v.name.as_deref() { @@ -264,96 +289,62 @@ pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], privat } } - let mut matched_vis = vec![false; visible_layers.len()]; - let mut matched_priv = vec![false; private_layers.len()]; let mut pairs = Vec::new(); - - // Pass 1: Unique named matches for (v_idx, vis) in visible_layers.iter().enumerate() { if let Some(name) = vis.name.as_deref() && vis_names.get(name).copied() == Some(1) && let Some(&(1, p_idx)) = priv_names.get(name) - && !matched_priv[p_idx] { - matched_vis[v_idx] = true; - matched_priv[p_idx] = true; pairs.push((v_idx, p_idx)); } } - - // Pass 2: Pair remaining unmatched layers in relative order when counts match - let unmatched_v: Vec = (0..visible_layers.len()).filter(|&i| !matched_vis[i]).collect(); - let unmatched_p: Vec = (0..private_layers.len()).filter(|&i| !matched_priv[i]).collect(); - if unmatched_v.len() == unmatched_p.len() { - for (&v_idx, &p_idx) in unmatched_v.iter().zip(unmatched_p.iter()) { - pairs.push((v_idx, p_idx)); - } - } else if unmatched_v.len() == 1 && unmatched_p.len() == 1 { - pairs.push((unmatched_v[0], unmatched_p[0])); - } + drop(vis_names); for (v_idx, p_idx) in pairs { apply_node_locks(Arc::make_mut(&mut visible_layers[v_idx]), &private_layers[p_idx]); } } -fn apply_node_locks(vis: &mut Node, priv_: &Node) { +fn apply_node_locks(vis: &mut Node, priv_: &LockTree) { if priv_.locked { vis.locked = true; } - if let (Some(vis_kids), Some(priv_kids)) = (vis.children_mut(), priv_.children()) { - if vis_kids.is_empty() || priv_kids.is_empty() { - return; - } + let Some(vis_kids) = vis.children_mut() else { return }; + if vis_kids.is_empty() || priv_.children.is_empty() { + return; + } - // Index private children: name -> (count, first_index) - let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); - for (i, p) in priv_kids.iter().enumerate() { - if let Some(name) = p.name.as_deref() { - let entry = priv_names.entry(name).or_insert((0, i)); - entry.0 += 1; - } + // Index private children: name -> (count, first_index) + let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); + for (i, p) in priv_.children.iter().enumerate() { + if let Some(name) = p.name.as_deref() { + let entry = priv_names.entry(name).or_insert((0, i)); + entry.0 += 1; } + } - // Index visible children: name -> count - let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); - for v in vis_kids.iter() { - if let Some(name) = v.name.as_deref() { - *vis_names.entry(name).or_insert(0) += 1; - } + // Index visible children: name -> count + let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for v in vis_kids.iter() { + if let Some(name) = v.name.as_deref() { + *vis_names.entry(name).or_insert(0) += 1; } + } - let mut matched_vis = vec![false; vis_kids.len()]; - let mut matched_priv = vec![false; priv_kids.len()]; - let mut pairs = Vec::new(); - - // Pass 1: resolve unique named matches first. - for (v_idx, v) in vis_kids.iter().enumerate() { - if let Some(v_name) = v.name.as_deref() - && vis_names.get(v_name).copied() == Some(1) - && let Some(&(1, p_idx)) = priv_names.get(v_name) - && !matched_priv[p_idx] - { - matched_vis[v_idx] = true; - matched_priv[p_idx] = true; - pairs.push((v_idx, p_idx)); - } + // Resolve unique named matches without positional blind pairing + let mut pairs = Vec::new(); + for (v_idx, v) in vis_kids.iter().enumerate() { + if let Some(v_name) = v.name.as_deref() + && vis_names.get(v_name).copied() == Some(1) + && let Some(&(1, p_idx)) = priv_names.get(v_name) + { + pairs.push((v_idx, p_idx)); } + } + drop(vis_names); - // Pass 2: pair remaining unmatched children in relative order when counts match. - let unmatched_v: Vec = (0..vis_kids.len()).filter(|&i| !matched_vis[i]).collect(); - let unmatched_p: Vec = (0..priv_kids.len()).filter(|&i| !matched_priv[i]).collect(); - if unmatched_v.len() == unmatched_p.len() { - for (&v_idx, &p_idx) in unmatched_v.iter().zip(unmatched_p.iter()) { - pairs.push((v_idx, p_idx)); - } - } else if unmatched_v.len() == 1 && unmatched_p.len() == 1 { - pairs.push((unmatched_v[0], unmatched_p[0])); - } - - for (v_idx, p_idx) in pairs { - apply_node_locks(Arc::make_mut(&mut vis_kids[v_idx]), &priv_kids[p_idx]); - } + for (v_idx, p_idx) in pairs { + apply_node_locks(Arc::make_mut(&mut vis_kids[v_idx]), &priv_.children[p_idx]); } } diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index 902811af45..414a2d321c 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -341,6 +341,9 @@ pub(super) fn fill_slots( let p = Arc::make_mut(p); (p.opacity, p.blend, p.isolate, p.knockout, p.knockout_shape) = (state.0, state.1, state.2, state.3, shape); } else if transparent { + for p in &mut parts { + Arc::make_mut(p).locked = false; + } let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); group.visible = visible; group.locked = locked; @@ -352,6 +355,9 @@ pub(super) fn fill_slots( // A wrap object stays one: the page's parts of it in a group, when there are several. if wrap.is_some() { if parts.len() > 1 { + for p in &mut parts { + Arc::make_mut(p).locked = false; + } let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); group.visible = visible; group.locked = locked; diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 8fc5e2541b..bc797c2e38 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8338,7 +8338,7 @@ fn ai_locked_layers_and_groups_preserve_locks() { #[test] fn ai_fallback_to_pdf_part_preserves_private_stream_layer_and_group_locks() { use std::sync::Arc; - let art_locked_group = format!("1 A\nu\n%_/ArtDictionary :\n%(Locked Subgroup) /String (AIArtName) ,\n%_;\n{}\nU\n0 A", square(10, 10)); + let art_locked_group = format!("1 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(Locked Subgroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10)); let locked_l = locked_layer("Map Layer", &art_locked_group); let n = native(&locked_l); let file = private(&n); @@ -8366,8 +8366,8 @@ fn ai_fallback_to_pdf_part_preserves_private_stream_layer_and_group_locks() { #[test] fn ai_duplicate_group_names_under_different_layers_preserve_individual_lock_states() { use std::sync::Arc; - let art_locked_group = format!("1 A\nu\n%_/ArtDictionary :\n%(SharedGroup) /String (AIArtName) ,\n%_;\n{}\nU\n0 A", square(10, 10)); - let art_unlocked_group = format!("0 A\nu\n%_/ArtDictionary :\n%(SharedGroup) /String (AIArtName) ,\n%_;\n{}\nU\n0 A", square(10, 10)); + let art_locked_group = format!("1 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(SharedGroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10)); + let art_unlocked_group = format!("0 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(SharedGroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10)); let layer_a = layer("Layer A", true, &art_locked_group); let layer_b = layer("Layer B", true, &art_unlocked_group); let n = native(&format!("{layer_a}{layer_b}")); @@ -8433,7 +8433,7 @@ fn ai_reordered_mixed_named_and_unnamed_children_preserve_locks() { } let mut visible_layers = vec![Arc::new(vis_layer)]; - let private_layers = vec![Arc::new(priv_layer)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); let roads = visible_layers[0].children().unwrap()[0].clone(); @@ -8478,15 +8478,15 @@ fn ai_reordered_three_children_roads_triangle_circle_preserve_locks() { } let mut visible_layers = vec![Arc::new(vis_layer)]; - let private_layers = vec![Arc::new(priv_layer)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); let vis_tri = visible_layers[0].children().unwrap()[0].clone(); let vis_circ = visible_layers[0].children().unwrap()[1].clone(); let vis_rd = visible_layers[0].children().unwrap()[2].clone(); - assert!(vis_tri.locked, "triangle matched to locked private triangle in relative order"); - assert!(!vis_circ.locked, "circle matched to unlocked private circle in relative order"); + assert!(!vis_tri.locked, "unnamed triangle does not pair blindly with private triangle"); + assert!(!vis_circ.locked, "unnamed circle remains unlocked"); assert!(!vis_rd.locked, "Roads matched to unlocked private Roads by unique name"); } @@ -8500,15 +8500,15 @@ fn ai_fallback_with_generated_page_name_preserves_private_layer_lock() { vis_layer.locked = false; let mut visible_layers = vec![Arc::new(vis_layer)]; - let private_layers = vec![Arc::new(priv_layer)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); assert_eq!(visible_layers[0].name.as_deref(), Some("Page 1")); - assert!(visible_layers[0].locked, "Page 1 layer matched to locked private layer Map positionally"); + assert!(visible_layers[0].locked, "single-layer document pairs visible and private layers"); } #[test] -fn ai_named_locked_private_child_pairs_with_unnamed_visible_child() { +fn ai_unnamed_visible_child_does_not_pair_with_private_node() { use std::sync::Arc; let mut doc = Document::new(100.0, 100.0); let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0)); @@ -8533,13 +8533,33 @@ fn ai_named_locked_private_child_pairs_with_unnamed_visible_child() { } let mut visible_layers = vec![Arc::new(vis_layer)]; - let private_layers = vec![Arc::new(priv_layer)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); let first = visible_layers[0].children().unwrap()[0].clone(); let second = visible_layers[0].children().unwrap()[1].clone(); assert!(!first.locked, "first unnamed visible group is unlocked"); - assert!(second.locked, "second unnamed visible group pairs positionally with locked Roads group"); + assert!(!second.locked, "second unnamed visible group does not pair positionally with locked Roads group"); +} + +#[test] +fn ai_multi_page_unlayered_pdf_does_not_blindly_pair_with_private_layers() { + use std::sync::Arc; + let mut doc = Document::new(100.0, 100.0); + let mut priv_1 = Node::layer(doc.alloc_id(), "Layer 1", LayerColor::Preset(0)); + priv_1.locked = true; + let mut priv_2 = Node::layer(doc.alloc_id(), "Layer 2", LayerColor::Preset(0)); + priv_2.locked = false; + + let vis_1 = Node::layer(doc.alloc_id(), "Page 1", LayerColor::Preset(0)); + let vis_2 = Node::layer(doc.alloc_id(), "Page 2", LayerColor::Preset(0)); + + let mut visible_layers = vec![Arc::new(vis_1), Arc::new(vis_2)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_1), super::native::layers::LockTree::from_node(&priv_2)]; + super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); + + assert!(!visible_layers[0].locked, "Page 1 does not pair with private Layer 1"); + assert!(!visible_layers[1].locked, "Page 2 does not pair with private Layer 2"); } #[test] @@ -8571,11 +8591,32 @@ fn ai_duplicate_visible_name_does_not_lock_multiple_from_single_private_node() { } let mut visible_layers = vec![Arc::new(vis_layer)]; - let private_layers = vec![Arc::new(priv_layer)]; + let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); let r1 = visible_layers[0].children().unwrap()[0].clone(); let r2 = visible_layers[0].children().unwrap()[1].clone(); - assert!(r1.locked, "first Roads group receives the lock from private Roads"); - assert!(!r2.locked, "second Roads group remains unlocked, avoiding duplicate private lock propagation"); + assert!(!r1.locked, "ambiguous duplicate visible name does not receive private lock"); + assert!(!r2.locked, "second duplicate visible name remains unlocked"); +} + +#[test] +fn ai_wrapped_group_places_lock_only_on_wrapper_group_not_children() { + let text = "1 A\n0 0.5 0 0 0 Xy\n(Styled Text) 10 50 Tt\n0 A"; + let art = native(&layer("Live", true, text)); + let (doc, _notes, read) = crate::layered_ai(&private(&art), pdf_two_squares(), vec![], false, true, 1.0); + assert!(read); + for layer in &doc.layers { + if let Some(kids) = layer.children() { + for kid in kids { + if kid.locked + && let Some(subkids) = kid.children() + { + for sub in subkids { + assert!(!sub.locked, "inner child of locked wrapper group must not be locked"); + } + } + } + } + } } diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 07197309b2..943f10d4b4 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -312,7 +312,8 @@ fn read_opened( b.taken = taken; b.warnings = notes; b.intent_cmyk = crate::import_image::output_intent_cmyk(pdf); - b.colors.uncalibrated_rgb = opts.uncalibrated_rgb && picked.iter().filter_map(|&n| pages.get(n)).any(crate::pages::has_private_data); + let doc_ai = crate::pages::has_private_data_doc(pdf); + b.colors.uncalibrated_rgb = opts.uncalibrated_rgb && (doc_ai || picked.iter().filter_map(|&n| pages.get(n)).any(crate::pages::has_private_data)); let cache = InterpreterCache::new(); let mut x = 0.0; // Where the next page's art may begin (a `.ai` page's art reaches past its artboard). @@ -364,7 +365,7 @@ fn read_opened( } let mut parts = b.end_page(); // A PDF-compatible `.ai` (the editor's private data next to the PDF art). - let ai = crate::pages::has_private_data(page); + let ai = doc_ai || crate::pages::has_private_data(page); if ai { drop_page_fill(&mut parts, xf.transform_rect_bbox(crate::pages::page_box(page, CropTo::Crop))); b.warn(OFF_ARTBOARD_NOTE); diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index f058913a76..57516b2de4 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -634,10 +634,15 @@ fn inflated(stream: &Stream<'_>, most: usize) -> Result, String> { Ok(out) } -/// Does `page` carry an editor's private data (`PieceInfo` keys starting with `AIPrivateData`)? +/// Does `page` carry an editor's private data (`PieceInfo` keys starting with `AIPrivateData` or `AIPDFPrivateData`)? /// A file saved without PDF compatibility keeps its art there and shows a placeholder page. pub(crate) fn has_private_data(page: &Page<'_>) -> bool { - piece_info_has(page, &[b"AIPrivateData"]) + piece_info_has(page, &[b"AIPrivateData", b"AIPDFPrivateData"]) +} + +/// Does `pdf` carry an editor's private data at page or document catalog level? +pub(crate) fn has_private_data_doc(pdf: &Pdf) -> bool { + has_private_data_keys(pdf) } /// Does `page` state where its art is: an art, trim or bleed box (ISO 32000-1 §14.11.2, the diff --git a/crates/pdf/tests/import_layers.rs b/crates/pdf/tests/import_layers.rs index a82bb7a415..429897fdcd 100644 --- a/crates/pdf/tests/import_layers.rs +++ b/crates/pdf/tests/import_layers.rs @@ -51,3 +51,28 @@ fn ai_fixture_with_locked_group_and_locked_object_imports_with_locks_preserved() } } } + +#[test] +fn catalog_level_piece_info_with_aipdfprivatedata_detects_ai_data_and_preserves_locks() { + let (a, b) = (first_extra(1), first_extra(1) + 1); + let order_obj = first_extra(1) + 2; + let objs = ["<< /Type /OCG /Name (Layer1) >>".to_string(), "<< /Type /OCG /Name (LockedGroup) /Locked true >>".to_string()]; + let catalog = format!( + "/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << /Order {order_obj} 0 R >> >> \ + /PieceInfo << /Illustrator << /Private << /AIPDFPrivateData1 7 /NumBlock 1 >> >> >>" + ); + let order_body = format!("[{a} 0 R [{b} 0 R]]"); + let content = "/OC /MC0 BDC 1 0 0 rg 10 10 20 20 re f EMC \ + /OC /MC1 BDC 0 1 0 rg 30 30 20 20 re f EMC \ + 0 0 0 rg 0 0 10 10 re f"; + let page = PdfPage { resources: format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R >>"), ..PdfPage::new(100.0, 100.0, content) }; + let bytes = pdf_with_catalog(&[page], &[&objs[0], &objs[1], &order_body], &catalog, None); + let doc = import(&bytes).unwrap(); + + let layer1 = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer1")).expect("Layer1 exists"); + assert!(!layer1.locked, "Layer1 is not locked"); + + let children = layer1.children().expect("Layer1 has children"); + let locked_group = children.iter().find(|n| n.name.as_deref() == Some("LockedGroup")).expect("LockedGroup exists"); + assert!(locked_group.locked, "LockedGroup has locked: true"); +} From 820610232b04af72a5aefbde5158b5d9100b7c7a Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:55:17 +0530 Subject: [PATCH 15/72] Fix catalog-level private data check to match only AIPrivateData --- crates/pdf/src/pages.rs | 9 +++++---- crates/pdf/tests/import_layers.rs | 4 ++-- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 57516b2de4..79a1b68a5d 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -634,15 +634,16 @@ fn inflated(stream: &Stream<'_>, most: usize) -> Result, String> { Ok(out) } -/// Does `page` carry an editor's private data (`PieceInfo` keys starting with `AIPrivateData` or `AIPDFPrivateData`)? +/// Does `page` carry an editor's private data (`PieceInfo` keys starting with `AIPrivateData`)? /// A file saved without PDF compatibility keeps its art there and shows a placeholder page. pub(crate) fn has_private_data(page: &Page<'_>) -> bool { - piece_info_has(page, &[b"AIPrivateData", b"AIPDFPrivateData"]) + piece_info_has(page, &[b"AIPrivateData"]) } -/// Does `pdf` carry an editor's private data at page or document catalog level? +/// Does `pdf` carry an editor's private data in its root document catalog (`AIPrivateData`)? pub(crate) fn has_private_data_doc(pdf: &Pdf) -> bool { - has_private_data_keys(pdf) + let xref = pdf.xref(); + xref.get::>(xref.root_id()).is_some_and(|root| dict_piece_info_has(&root, &[b"AIPrivateData"])) } /// Does `page` state where its art is: an art, trim or bleed box (ISO 32000-1 §14.11.2, the diff --git a/crates/pdf/tests/import_layers.rs b/crates/pdf/tests/import_layers.rs index 429897fdcd..a5ad8182c0 100644 --- a/crates/pdf/tests/import_layers.rs +++ b/crates/pdf/tests/import_layers.rs @@ -53,13 +53,13 @@ fn ai_fixture_with_locked_group_and_locked_object_imports_with_locks_preserved() } #[test] -fn catalog_level_piece_info_with_aipdfprivatedata_detects_ai_data_and_preserves_locks() { +fn catalog_level_piece_info_with_aiprivatedata_detects_ai_data_and_preserves_locks() { let (a, b) = (first_extra(1), first_extra(1) + 1); let order_obj = first_extra(1) + 2; let objs = ["<< /Type /OCG /Name (Layer1) >>".to_string(), "<< /Type /OCG /Name (LockedGroup) /Locked true >>".to_string()]; let catalog = format!( "/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << /Order {order_obj} 0 R >> >> \ - /PieceInfo << /Illustrator << /Private << /AIPDFPrivateData1 7 /NumBlock 1 >> >> >>" + /PieceInfo << /Illustrator << /Private << /AIPrivateData1 7 /NumBlock 1 >> >> >>" ); let order_body = format!("[{a} 0 R [{b} 0 R]]"); let content = "/OC /MC0 BDC 1 0 0 rg 10 10 20 20 re f EMC \ From bfcac4829f34b5092c6c2582f86d38e163ee3916 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:03:43 +0530 Subject: [PATCH 16/72] Narrow lock handling to spec and deduplicate name matching --- crates/eps/src/import/native/layers.rs | 88 ++++++++------------- crates/pdf/src/import/entry.rs | 5 +- crates/pdf/src/import_scan.rs | 65 ++------------- crates/pdf/src/pages.rs | 78 +++--------------- crates/pdf/src/tests/import_layers.rs | 105 ------------------------- crates/pdf/tests/import_layers.rs | 78 ------------------ 6 files changed, 49 insertions(+), 370 deletions(-) delete mode 100644 crates/pdf/tests/import_layers.rs diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index 1982fefd64..6a123242fd 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -261,6 +261,35 @@ impl LockTree { } } +/// Match unique names between visible nodes and private lock trees. +fn unique_name_pairs>(vis_nodes: &[T], priv_nodes: &[LockTree]) -> Vec<(usize, usize)> { + let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); + for (i, p) in priv_nodes.iter().enumerate() { + if let Some(name) = p.name.as_deref() { + let entry = priv_names.entry(name).or_insert((0, i)); + entry.0 += 1; + } + } + + let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for v in vis_nodes.iter() { + if let Some(name) = v.name.as_deref() { + *vis_names.entry(name).or_insert(0) += 1; + } + } + + let mut pairs = Vec::new(); + for (v_idx, vis) in vis_nodes.iter().enumerate() { + if let Some(name) = vis.name.as_deref() + && vis_names.get(name).copied() == Some(1) + && let Some(&(1, p_idx)) = priv_names.get(name) + { + pairs.push((v_idx, p_idx)); + } + } + pairs +} + /// Apply lock states from private data layers to visible PDF layers. pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], private_layers: &[LockTree]) { if private_layers.is_empty() || visible_layers.is_empty() { @@ -274,33 +303,7 @@ pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], privat } // Otherwise, match only layers with identifiable correspondence (matching unique names). - let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); - for (i, p) in private_layers.iter().enumerate() { - if let Some(name) = p.name.as_deref() { - let entry = priv_names.entry(name).or_insert((0, i)); - entry.0 += 1; - } - } - - let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); - for v in visible_layers.iter() { - if let Some(name) = v.name.as_deref() { - *vis_names.entry(name).or_insert(0) += 1; - } - } - - let mut pairs = Vec::new(); - for (v_idx, vis) in visible_layers.iter().enumerate() { - if let Some(name) = vis.name.as_deref() - && vis_names.get(name).copied() == Some(1) - && let Some(&(1, p_idx)) = priv_names.get(name) - { - pairs.push((v_idx, p_idx)); - } - } - drop(vis_names); - - for (v_idx, p_idx) in pairs { + for (v_idx, p_idx) in unique_name_pairs(visible_layers, private_layers) { apply_node_locks(Arc::make_mut(&mut visible_layers[v_idx]), &private_layers[p_idx]); } } @@ -314,36 +317,7 @@ fn apply_node_locks(vis: &mut Node, priv_: &LockTree) { return; } - // Index private children: name -> (count, first_index) - let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new(); - for (i, p) in priv_.children.iter().enumerate() { - if let Some(name) = p.name.as_deref() { - let entry = priv_names.entry(name).or_insert((0, i)); - entry.0 += 1; - } - } - - // Index visible children: name -> count - let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); - for v in vis_kids.iter() { - if let Some(name) = v.name.as_deref() { - *vis_names.entry(name).or_insert(0) += 1; - } - } - - // Resolve unique named matches without positional blind pairing - let mut pairs = Vec::new(); - for (v_idx, v) in vis_kids.iter().enumerate() { - if let Some(v_name) = v.name.as_deref() - && vis_names.get(v_name).copied() == Some(1) - && let Some(&(1, p_idx)) = priv_names.get(v_name) - { - pairs.push((v_idx, p_idx)); - } - } - drop(vis_names); - - for (v_idx, p_idx) in pairs { + for (v_idx, p_idx) in unique_name_pairs(vis_kids.as_slice(), &priv_.children) { apply_node_locks(Arc::make_mut(&mut vis_kids[v_idx]), &priv_.children[p_idx]); } } diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 943f10d4b4..07197309b2 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -312,8 +312,7 @@ fn read_opened( b.taken = taken; b.warnings = notes; b.intent_cmyk = crate::import_image::output_intent_cmyk(pdf); - let doc_ai = crate::pages::has_private_data_doc(pdf); - b.colors.uncalibrated_rgb = opts.uncalibrated_rgb && (doc_ai || picked.iter().filter_map(|&n| pages.get(n)).any(crate::pages::has_private_data)); + b.colors.uncalibrated_rgb = opts.uncalibrated_rgb && picked.iter().filter_map(|&n| pages.get(n)).any(crate::pages::has_private_data); let cache = InterpreterCache::new(); let mut x = 0.0; // Where the next page's art may begin (a `.ai` page's art reaches past its artboard). @@ -365,7 +364,7 @@ fn read_opened( } let mut parts = b.end_page(); // A PDF-compatible `.ai` (the editor's private data next to the PDF art). - let ai = doc_ai || crate::pages::has_private_data(page); + let ai = crate::pages::has_private_data(page); if ai { drop_page_fill(&mut parts, xf.transform_rect_bbox(crate::pages::page_box(page, CropTo::Crop))); b.warn(OFF_ARTBOARD_NOTE); diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index 0b21aadce9..6b812224e2 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -83,8 +83,6 @@ pub(crate) struct Ocgs { view_auto: HashSet, /// The groups placed in the layer order. placed: HashSet, - /// The groups that are locked in configuration or dictionary flags. - locked: HashSet, } impl Ocgs { @@ -97,13 +95,9 @@ impl Ocgs { }; let config = props.get::>(b"D").unwrap_or_default(); let refs = |d: &Dict<'_>, key: &[u8]| -> Vec { - if let Some(a) = d.get::>(key) { - items(&a).filter_map(|i| i.as_obj_ref()).map(ObjectIdentifier::from).take(MAX_GROUPS).collect() - } else if let Some(r) = d.get_ref(key) { - vec![ObjectIdentifier::from(r)] - } else { - Vec::new() - } + d.get::>(key) + .map(|a| items(&a).filter_map(|i| i.as_obj_ref()).map(ObjectIdentifier::from).take(MAX_GROUPS).collect()) + .unwrap_or_default() }; let all = refs(&props, b"OCGs"); if config.get::>(b"BaseState").is_some_and(|n| n.as_ref() == b"OFF") { @@ -117,13 +111,10 @@ impl Ocgs { for d in auto.iter().filter(|d| d.get::>(b"Event").is_some_and(|e| e.as_ref() == b"View")) { o.view_auto.extend(refs(d, b"OCGs")); } - let mut locked: HashSet<_> = refs(&config, b"Locked").into_iter().collect(); - locked.extend(refs(&props, b"Locked")); - o.locked = locked; + let locked: HashSet<_> = refs(&config, b"Locked").into_iter().collect(); for id in all { if let Some(d) = xref.get::>(id) { - let is_locked = o.is_locked(id, &d); - o.add(id, &d, is_locked); + o.add(id, &d, locked.contains(&id)); } } if let Some(order) = config.get::>(b"Order") { @@ -179,7 +170,6 @@ impl Ocgs { if let Some(i) = self.index.get(&id) { return *i; } - let locked = locked || self.is_locked(id, d); let name = d.get::>(b"Name").map(|s| text_string(s.as_bytes())).unwrap_or_default(); let print = usage(d, b"Print", b"PrintState") != Some(false); // A view state applies when the configuration says so on opening; an off one hides the @@ -196,11 +186,6 @@ impl Ocgs { self.list.len() - 1 } - /// Is group `id` (dictionary `d`) locked according to configuration or dictionary flags? - fn is_locked(&self, id: ObjectIdentifier, d: &Dict<'_>) -> bool { - self.locked.contains(&id) || is_ocg_dict_locked(d) - } - /// Does the interpreter leave out the art of some group (off in the default configuration)? pub fn skips_any(&self) -> bool { self.index.keys().any(|id| self.off.contains(id)) @@ -221,49 +206,11 @@ impl Ocgs { fn note(&mut self, id: ObjectIdentifier, d: &Dict<'_>) -> Option { match self.index.get(&id) { Some(i) => Some(*i), - None => { - let is_locked = self.is_locked(id, d); - (self.list.len() < MAX_GROUPS).then(|| self.add(id, d, is_locked)) - } + None => (self.list.len() < MAX_GROUPS).then(|| self.add(id, d, false)), } } } -/// Is group dictionary `d` flagged as locked (directly or in its `/Usage`)? -fn is_ocg_dict_locked(d: &Dict<'_>) -> bool { - if d.get::(b"Locked") == Some(true) - || d.get::>(b"Locked").is_some_and(|n| { - let b = n.as_ref(); - b.eq_ignore_ascii_case(b"true") || b.eq_ignore_ascii_case(b"locked") || b.eq_ignore_ascii_case(b"on") - }) - { - return true; - } - if let Some(usage) = d.get::>(b"Usage") { - if usage.get::(b"Locked") == Some(true) - || usage.get::>(b"Locked").is_some_and(|n| { - let b = n.as_ref(); - b.eq_ignore_ascii_case(b"true") || b.eq_ignore_ascii_case(b"locked") || b.eq_ignore_ascii_case(b"on") - }) - { - return true; - } - if let Some(user) = usage.get::>(b"User") - && (user.get::(b"Locked") == Some(true) - || user.get::>(b"Type").is_some_and(|n| n.as_ref().eq_ignore_ascii_case(b"locked")) - || user.get::>(b"User").is_some_and(|s| s.as_bytes().eq_ignore_ascii_case(b"locked"))) - { - return true; - } - if let Some(lock) = usage.get::>(b"Lock") - && lock.get::(b"Locked") != Some(false) - { - return true; - } - } - false -} - /// The state (`ON` → true, `OFF` → false) group `d`'s usage `category` gives in `key`. fn usage(d: &Dict<'_>, category: &[u8], key: &[u8]) -> Option { let state = d.get::>(b"Usage")?.get::>(category)?.get::>(key)?; diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 79a1b68a5d..688964d8db 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -539,30 +539,11 @@ fn private_data(pdf: &Pdf) -> Option> { /// [`private_data`], with why a private data stream can't be read ([`inflated`]). fn read_private_data(pdf: &Pdf) -> Result>, String> { - let xref = pdf.xref(); - let page_private = pdf + let Some(private) = pdf .pages() .first() - .and_then(|page| page.raw().get::>(b"PieceInfo")?.get::>(PRIVATE_DATA_OWNER)?.get::>(b"Private")); - let root_private = xref - .get::>(xref.root_id()) - .and_then(|root| root.get::>(b"PieceInfo")?.get::>(PRIVATE_DATA_OWNER)?.get::>(b"Private")); - let has_supported_data = |dict: &Dict<'_>| dict.contains_key(b"AIPrivateData1") || dict.contains_key(b"AIPDFPrivateData1"); - let private = match (page_private, root_private) { - (Some(page), Some(root)) => { - if has_supported_data(&page) { - Some(page) - } else if has_supported_data(&root) { - Some(root) - } else { - Some(page) - } - } - (Some(page), None) => Some(page), - (None, Some(root)) => Some(root), - (None, None) => None, - }; - let Some(private) = private else { + .and_then(|page| page.raw().get::>(b"PieceInfo")?.get::>(PRIVATE_DATA_OWNER)?.get::>(b"Private")) + else { return Ok(None); }; let key = if private.contains_key(b"AIPrivateData1") { "AIPrivateData" } else { "AIPDFPrivateData" }; @@ -583,9 +564,7 @@ pub fn has_illustrator_data(bytes: &[u8], password: Option<&str>) -> bool { /// [`has_illustrator_data`] of a parsed PDF. fn has_private_data_keys(pdf: &Pdf) -> bool { - let xref = pdf.xref(); pdf.pages().first().is_some_and(|p| piece_info_has(p, &[b"AIPrivateData", b"AIPDFPrivateData"])) - || xref.get::>(xref.root_id()).is_some_and(|root| dict_piece_info_has(&root, &[b"AIPrivateData", b"AIPDFPrivateData"])) } /// `stream` decoded, up to `most` bytes: the decoder is run here rather than by the PDF reader's @@ -640,12 +619,6 @@ pub(crate) fn has_private_data(page: &Page<'_>) -> bool { piece_info_has(page, &[b"AIPrivateData"]) } -/// Does `pdf` carry an editor's private data in its root document catalog (`AIPrivateData`)? -pub(crate) fn has_private_data_doc(pdf: &Pdf) -> bool { - let xref = pdf.xref(); - xref.get::>(xref.root_id()).is_some_and(|root| dict_piece_info_has(&root, &[b"AIPrivateData"])) -} - /// Does `page` state where its art is: an art, trim or bleed box (ISO 32000-1 §14.11.2, the /// extent of the page's meaningful content and of the finished page)? A page written from an /// artboard has them; the notice a file saved without its PDF part shows instead of its art is @@ -654,46 +627,15 @@ pub(crate) fn states_art(page: &Page<'_>) -> bool { [&b"ArtBox"[..], b"TrimBox", b"BleedBox"].iter().any(|k| page.raw().get::<[f32; 4]>(*k).is_some()) } -/// Does dictionary `d`'s `PieceInfo` hold a key starting with one of `prefixes`, up to four dictionaries in? -fn dict_has_piece_info_prefix(d: &Dict<'_>, prefixes: &[&[u8]]) -> bool { - if let Some(priv_dict) = d.get::>(PRIVATE_DATA_OWNER).and_then(|i| i.get::>(b"Private")) - && prefixes.iter().any(|p| priv_dict.keys().any(|k| k.starts_with(p))) - { - return true; - } - const MAX_VISITS: usize = 128; - fn walk(d: &Dict<'_>, prefixes: &[&[u8]], depth: u32, budget: &mut usize) -> bool { - if depth >= 4 || *budget == 0 { - return false; - } - for k in d.keys() { - if *budget == 0 { - return false; - } - *budget -= 1; - if prefixes.iter().any(|p| k.starts_with(p)) { - return true; - } - if let Some(sub) = d.get::>(k.as_ref()) - && walk(&sub, prefixes, depth + 1, budget) - { - return true; - } - } - false - } - let mut budget = MAX_VISITS; - walk(d, prefixes, 0, &mut budget) -} - /// Does `page`'s `PieceInfo` hold a key starting with one of `prefixes`, up to four dictionaries in? fn piece_info_has(page: &Page<'_>, prefixes: &[&[u8]]) -> bool { - page.raw().get::>(b"PieceInfo").is_some_and(|d| dict_has_piece_info_prefix(&d, prefixes)) -} - -/// Does dictionary `d`'s `PieceInfo` hold a key starting with one of `prefixes`, up to four dictionaries in? -fn dict_piece_info_has(d: &Dict<'_>, prefixes: &[&[u8]]) -> bool { - d.get::>(b"PieceInfo").is_some_and(|p| dict_has_piece_info_prefix(&p, prefixes)) + fn walk(d: &Dict<'_>, prefixes: &[&[u8]], depth: u32) -> bool { + depth < 4 + && d.keys().any(|k| { + prefixes.iter().any(|p| k.starts_with(p)) || d.get::>(k.as_ref()).is_some_and(|sub| walk(&sub, prefixes, depth + 1)) + }) + } + page.raw().get::>(b"PieceInfo").is_some_and(|d| walk(&d, prefixes, 0)) } #[cfg(test)] diff --git a/crates/pdf/src/tests/import_layers.rs b/crates/pdf/src/tests/import_layers.rs index 56492fe30a..c0f9dfc970 100644 --- a/crates/pdf/src/tests/import_layers.rs +++ b/crates/pdf/src/tests/import_layers.rs @@ -469,108 +469,3 @@ fn art_deep_in_tags_inside_a_layer_reaches_it() { let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); assert_eq!(colors(shapes), [Color::rgb(1.0, 0.0, 0.0)]); } - -#[test] -fn ocg_dictionary_locked_flag_is_read() { - let (a, b) = (first_extra(1), first_extra(1) + 1); - let objs = ["<< /Type /OCG /Name (Shapes) /Locked true >>".to_string(), "<< /Type /OCG /Name (Plain) >>".to_string()]; - let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << /Order [{a} 0 R {b} 0 R] >> >> "); - let bytes = pdf_with_catalog(&[page([a, b])], &[&objs[0], &objs[1]], &catalog, None); - let d = import(&bytes).unwrap(); - let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); - let plain = d.layers.iter().find(|l| l.name.as_deref() == Some("Plain")).unwrap(); - assert!(shapes.locked, "Shapes has /Locked true in its dictionary"); - assert!(!plain.locked, "Plain is not locked"); -} - -#[test] -fn ocg_dictionary_usage_locked_is_read() { - let (a, b) = (first_extra(1), first_extra(1) + 1); - let objs = ["<< /Type /OCG /Name (Shapes) /Usage << /User << /Type /Locked >> >> >>".to_string(), "<< /Type /OCG /Name (Plain) >>".to_string()]; - let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << /Order [{a} 0 R {b} 0 R] >> >> "); - let bytes = pdf_with_catalog(&[page([a, b])], &[&objs[0], &objs[1]], &catalog, None); - let d = import(&bytes).unwrap(); - let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); - let plain = d.layers.iter().find(|l| l.name.as_deref() == Some("Plain")).unwrap(); - assert!(shapes.locked, "Shapes has /Usage << /User << /Type /Locked >> >>"); - assert!(!plain.locked, "Plain is not locked"); -} - -#[test] -fn oc_properties_root_locked_is_read_and_configs_locked_is_ignored() { - let (a, b) = (first_extra(1), first_extra(1) + 1); - let objs = ["<< /Type /OCG /Name (RootLocked) >>".to_string(), "<< /Type /OCG /Name (ConfigUnlocked) >>".to_string()]; - let catalog = format!( - "/OCProperties << /OCGs [{a} 0 R {b} 0 R] /Locked [{a} 0 R] /Configs [<< /Locked [{b} 0 R] >>] /D << /Order [{a} 0 R {b} 0 R] >> >> " - ); - let bytes = pdf_with_catalog(&[page([a, b])], &[&objs[0], &objs[1]], &catalog, None); - let d = import(&bytes).unwrap(); - let root_locked = d.layers.iter().find(|l| l.name.as_deref() == Some("RootLocked")).unwrap(); - let config_unlocked = d.layers.iter().find(|l| l.name.as_deref() == Some("ConfigUnlocked")).unwrap(); - assert!(root_locked.locked, "RootLocked is in /OCProperties /Locked"); - assert!(!config_unlocked.locked, "ConfigUnlocked is only in alternate /Configs /Locked, so stays unlocked"); -} - -#[test] -fn ocg_noted_from_content_stream_retains_lock() { - let (a, b) = (first_extra(1), first_extra(1) + 1); - let objs = ["<< /Type /OCG /Name (UnlistedLocked) /Locked true >>".to_string(), "<< /Type /OCG /Name (Listed) >>".to_string()]; - // /OCGs only lists {b} (Listed). {a} (UnlistedLocked) is not in /OCGs or /Order. - let catalog = format!("/OCProperties << /OCGs [{b} 0 R] /D << /Order [{b} 0 R] >> >> "); - let content = "/OC /MC0 BDC 1 0 0 rg 10 10 30 30 re f EMC /OC /MC1 BDC 0 1 0 rg 0 0 5 5 re f EMC"; - let p = PdfPage { resources: format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R >>"), ..PdfPage::new(100.0, 100.0, content) }; - let bytes = pdf_with_catalog(&[p], &[&objs[0], &objs[1]], &catalog, None); - let d = import(&bytes).unwrap(); - let unlisted = d.layers.iter().find(|l| l.name.as_deref() == Some("UnlistedLocked")).unwrap(); - let listed = d.layers.iter().find(|l| l.name.as_deref() == Some("Listed")).unwrap(); - assert!(unlisted.locked, "UnlistedLocked has /Locked true in its dictionary"); - assert!(!listed.locked, "Listed is not locked"); -} - -#[test] -fn ai_fixture_with_locked_group_and_locked_object_imports_with_locks_preserved() { - let (a, b, c, d) = (first_extra(1), first_extra(1) + 1, first_extra(1) + 2, first_extra(1) + 3); - let order_obj = first_extra(1) + 4; - let objs = [ - "<< /Type /OCG /Name (Layer1) >>".to_string(), - "<< /Type /OCG /Name (LockedGroup) /Locked true >>".to_string(), - "<< /Type /OCG /Name (UnlockedGroup) >>".to_string(), - "<< /Type /OCG /Name (LockedObject) /Locked true >>".to_string(), - ]; - let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R {c} 0 R {d} 0 R] /D << /Order {order_obj} 0 R >> >> "); - let order_body = format!("[{a} 0 R [{b} 0 R {c} 0 R]]"); - let content = "/OC /MC0 BDC 1 0 0 rg 10 10 20 20 re f EMC \ - /OC /MC1 BDC 0 1 0 rg 30 30 20 20 re f EMC \ - /OC /MC2 BDC 0 0 1 rg 50 50 20 20 re f EMC \ - /OC /MC3 BDC 1 1 0 rg 70 70 20 20 re f EMC \ - 0 0 0 rg 0 0 10 10 re f"; - let page = PdfPage { - resources: format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R /MC2 {c} 0 R /MC3 {d} 0 R >>"), - entries: "/PieceInfo << /Illustrator << /Private << /AIPrivateData1 7 /NumBlock 1 >> >> >>".into(), - ..PdfPage::new(100.0, 100.0, content) - }; - let bytes = pdf_with_catalog(&[page], &[&objs[0], &objs[1], &objs[2], &objs[3], &order_body], &catalog, None); - let doc = import(&bytes).unwrap(); - - let layer1 = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer1")).expect("Layer1 exists"); - assert!(!layer1.locked, "Layer1 is not locked"); - - let children = layer1.children().expect("Layer1 has children"); - let locked_group = children.iter().find(|n| n.name.as_deref() == Some("LockedGroup")).expect("LockedGroup exists"); - assert!(locked_group.locked, "LockedGroup has locked: true"); - - let unlocked_group = children.iter().find(|n| n.name.as_deref() == Some("UnlockedGroup")).expect("UnlockedGroup exists"); - assert!(!unlocked_group.locked, "UnlockedGroup has locked: false"); - - let locked_obj = doc.layers.iter().find(|l| l.name.as_deref() == Some("LockedObject")).expect("LockedObject exists"); - assert!(locked_obj.locked, "LockedObject has locked: true"); - - if let Some(page_layer) = doc.layers.iter().find(|l| l.name.as_deref() == Some("Page 1")) { - assert!(!page_layer.locked, "Page layer is not locked"); - if let Some(kids) = page_layer.children() { - for kid in kids { - assert!(!kid.locked, "Non-locked object in page layer remains unlocked"); - } - } - } -} diff --git a/crates/pdf/tests/import_layers.rs b/crates/pdf/tests/import_layers.rs deleted file mode 100644 index a5ad8182c0..0000000000 --- a/crates/pdf/tests/import_layers.rs +++ /dev/null @@ -1,78 +0,0 @@ -//! Synthetic regression verifying locked group and locked object import in AI fixtures. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - -use vectorcraft_pdf::import; -use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with_catalog}; - -#[test] -fn ai_fixture_with_locked_group_and_locked_object_imports_with_locks_preserved() { - let (a, b, c, d) = (first_extra(1), first_extra(1) + 1, first_extra(1) + 2, first_extra(1) + 3); - let order_obj = first_extra(1) + 4; - let objs = [ - "<< /Type /OCG /Name (Layer1) >>".to_string(), - "<< /Type /OCG /Name (LockedGroup) /Locked true >>".to_string(), - "<< /Type /OCG /Name (UnlockedGroup) >>".to_string(), - "<< /Type /OCG /Name (LockedObject) /Locked true >>".to_string(), - ]; - let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R {c} 0 R {d} 0 R] /D << /Order {order_obj} 0 R >> >> "); - let order_body = format!("[{a} 0 R [{b} 0 R {c} 0 R]]"); - let content = "/OC /MC0 BDC 1 0 0 rg 10 10 20 20 re f EMC \ - /OC /MC1 BDC 0 1 0 rg 30 30 20 20 re f EMC \ - /OC /MC2 BDC 0 0 1 rg 50 50 20 20 re f EMC \ - /OC /MC3 BDC 1 1 0 rg 70 70 20 20 re f EMC \ - 0 0 0 rg 0 0 10 10 re f"; - let page = PdfPage { - resources: format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R /MC2 {c} 0 R /MC3 {d} 0 R >>"), - entries: "/PieceInfo << /Illustrator << /Private << /AIPrivateData1 7 /NumBlock 1 >> >> >>".into(), - ..PdfPage::new(100.0, 100.0, content) - }; - let bytes = pdf_with_catalog(&[page], &[&objs[0], &objs[1], &objs[2], &objs[3], &order_body], &catalog, None); - let doc = import(&bytes).unwrap(); - - let layer1 = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer1")).expect("Layer1 exists"); - assert!(!layer1.locked, "Layer1 is not locked"); - - let children = layer1.children().expect("Layer1 has children"); - let locked_group = children.iter().find(|n| n.name.as_deref() == Some("LockedGroup")).expect("LockedGroup exists"); - assert!(locked_group.locked, "LockedGroup has locked: true"); - - let unlocked_group = children.iter().find(|n| n.name.as_deref() == Some("UnlockedGroup")).expect("UnlockedGroup exists"); - assert!(!unlocked_group.locked, "UnlockedGroup has locked: false"); - - let locked_obj = doc.layers.iter().find(|l| l.name.as_deref() == Some("LockedObject")).expect("LockedObject exists"); - assert!(locked_obj.locked, "LockedObject has locked: true"); - - if let Some(page_layer) = doc.layers.iter().find(|l| l.name.as_deref() == Some("Page 1")) { - assert!(!page_layer.locked, "Page layer is not locked"); - if let Some(kids) = page_layer.children() { - for kid in kids { - assert!(!kid.locked, "Non-locked object in page layer remains unlocked"); - } - } - } -} - -#[test] -fn catalog_level_piece_info_with_aiprivatedata_detects_ai_data_and_preserves_locks() { - let (a, b) = (first_extra(1), first_extra(1) + 1); - let order_obj = first_extra(1) + 2; - let objs = ["<< /Type /OCG /Name (Layer1) >>".to_string(), "<< /Type /OCG /Name (LockedGroup) /Locked true >>".to_string()]; - let catalog = format!( - "/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << /Order {order_obj} 0 R >> >> \ - /PieceInfo << /Illustrator << /Private << /AIPrivateData1 7 /NumBlock 1 >> >> >>" - ); - let order_body = format!("[{a} 0 R [{b} 0 R]]"); - let content = "/OC /MC0 BDC 1 0 0 rg 10 10 20 20 re f EMC \ - /OC /MC1 BDC 0 1 0 rg 30 30 20 20 re f EMC \ - 0 0 0 rg 0 0 10 10 re f"; - let page = PdfPage { resources: format!("/Properties << /MC0 {a} 0 R /MC1 {b} 0 R >>"), ..PdfPage::new(100.0, 100.0, content) }; - let bytes = pdf_with_catalog(&[page], &[&objs[0], &objs[1], &order_body], &catalog, None); - let doc = import(&bytes).unwrap(); - - let layer1 = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer1")).expect("Layer1 exists"); - assert!(!layer1.locked, "Layer1 is not locked"); - - let children = layer1.children().expect("Layer1 has children"); - let locked_group = children.iter().find(|n| n.name.as_deref() == Some("LockedGroup")).expect("LockedGroup exists"); - assert!(locked_group.locked, "LockedGroup has locked: true"); -} From a6e47e9d1e761e9c8d3c63f4cae1a78c693b7be2 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:36:52 +0530 Subject: [PATCH 17/72] Trigger CI re-run From 0359cc0b93b3e11ab08e583f7b238786e6eacbfa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:21:27 -0800 Subject: [PATCH 18/72] Scripts: a document named in brackets counts for print's file write The script check now reads a string literal in index brackets as the member it names when the document chains list that member as a property, so app['activeDocument'].print(o) and app['documents'][0].print(o) report a file write. Other names in the brackets, such as app['preferences'], keep the index and do not give a document. --- crates/scriptcheck/src/analyze.rs | 33 +++++++++++++++++++++++++++++++ crates/scriptcheck/src/tests.rs | 19 ++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 04ebe4b0f2..a3d0f92fb2 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -463,6 +463,29 @@ impl Chain { self.append(if call { "()" } else { "[]" }, cap); } + /// The index that ends the chain is of the member `name`, which a string literal in brackets + /// named: `[]` becomes `.name` when one of [`catalog::DOM_DOCUMENTS`] reads that member as a + /// property (`app['activeDocument']`, `app['documents'][0]`). Any other name keeps the index. + fn name_index(&mut self, name: &str, cap: usize) { + let Some(base) = self.path.strip_suffix("[]").filter(|_| !self.cut) else { return }; + let property = |d: &&str| { + d.strip_prefix(base) + .and_then(|m| m.strip_prefix('.')) + .and_then(|m| m.strip_prefix(name)) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('.') || rest.starts_with('[')) + }; + let ident = !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$'); + if !ident || !catalog::DOM_DOCUMENTS.iter().any(property) { + return; + } + self.path.truncate(self.path.len() - 2); + self.chars = self.chars.saturating_sub(2); + self.last_change = false; + for s in [".", name] { + self.append(s, cap); + } + } + /// The call that ends the chain is of the member `name`, which a string literal in brackets /// named: `[]()` becomes `.name()`. fn name_call(&mut self, name: &str, cap: usize) { @@ -1177,6 +1200,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } if self.suspended.last().is_some_and(|c| c.wait == self.depth()) { self.active = self.suspended.pop(); + // `app['activeDocument']`: a string literal in the brackets names a member. + if t.text == "]" + && is(self.h[1], "[") + && let Some(name) = self.h[0].filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32)) + { + let cap = self.chain_cap(); + if let Some(c) = self.active.as_mut() { + c.name_index(&name, cap); + } + } } self.close_scopes(); let grouped = self.close_parens(t); diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 8c08f27104..7c88a6dbe3 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -624,6 +624,25 @@ fn print_writes_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", lines)]); } +/// A string literal in brackets that names `activeDocument` or `documents` reads that property, so the +/// `print` of the document it gives writes a file; any other name in the brackets, a name that is not +/// a property's, and a computed name do not give a document. +#[test] +fn print_on_a_document_named_in_brackets_writes_a_file() { + let r = report(concat!( + "var o = new PrintOptions(); o.jobOptions.file = new File(p);\n", + "app['activeDocument'].print(o);\n", + "app[\"documents\"][0].print(o);\n", + "var d = app['documents'][1]; d.print(o);\n", + "app['documents']['add']().print(o);\n", + "app['preferences'].print(o); app['activeDocuments'].print(o); app['documents[]'].print(o);\n", + "app['documents'].print(o); app[k].print(o); x.app['activeDocument'].print(o);\n", + )); + let lines = &[2, 3, 4, 5][..]; + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines)); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", lines)]); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] From afe9a98c689b0e30805974a2afb9c0b51672531a Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:12:35 +0530 Subject: [PATCH 19/72] Preserve single-owner hidden state on wrapper groups and add regressions --- crates/eps/src/import/ai/read/ops.rs | 1 + crates/eps/src/import/ai/tests.rs | 29 ++++++++++++++++ crates/eps/src/import/native/slots.rs | 50 +++++++++++++++++++++++++-- crates/eps/src/import/tests_native.rs | 21 ----------- 4 files changed, 78 insertions(+), 23 deletions(-) diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index acde018009..7ac992d089 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -953,6 +953,7 @@ impl<'a> Reader<'a> { (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) = (1.0, BlendMode::Normal, false, Knockout::Neutral, false); let (visible, locked) = (object.visible, object.locked); (object.opacity, object.blend, object.isolate, object.knockout_shape) = (1.0, BlendMode::Normal, false, false); + object.visible = true; object.locked = false; let mut group = Node::group(self.doc.alloc_id(), vec![Arc::new(look), Arc::new(object)]); (group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = state; diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 1fcf87e7a0..0cf34dd15f 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -12029,6 +12029,35 @@ fn type_with_an_art_brush_keeps_its_drawn_look() { assert_eq!(brushed, 0, "{:?}", r.warnings); } +/// A hidden styled text wrapper group inherits hidden state while its inner text and look retain +/// intrinsic visibility, so showing the group makes the inner artwork visible. +#[test] +fn hidden_styled_text_look_wrapper_group_showing_reveals_inner_text() { + let own: String = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n7 /StoryIndex ,\n;\n".lines().map(|l| format!("%_{l}\n")).collect(); + let object = format!( + "0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n{RED}{}f\nU\n0 0.5 0 0 0 Xy\n0 0 Xd\n6 () XW\n1 Xw\n1 A\n{own}1 (Inked) XW\n0 Xw\n0 A\n", + rect_path(20.0, 18.0, 100.0, 62.0) + ); + let def = format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", RIBBON)); + let r = read_ok(&format!("{def}{}{}", art_style("Ribbon", 1.0, &STRETCHED, ""), layer(&object))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "wrapper group created: {a:#?}"); + let group = &a[0]; + assert!(!group.visible, "wrapper group must inherit hidden state"); + assert!(group.locked, "wrapper group must inherit locked state"); + let children = group.children().expect("must be a group of look and text"); + assert_eq!(children.len(), 2); + for child in children { + assert!(child.visible, "inner child must retain intrinsic visibility"); + assert!(!child.locked, "inner child must not be locked"); + } + let mut shown = (**group).clone(); + shown.visible = true; + for child in shown.children().unwrap() { + assert!(child.visible, "inner child remains visible when parent group is shown"); + } +} + /// Each copy a Scatter brush places is its section's art turned over before the copy's rotation: /// the side of the section with y up goes down the page with the rotation at 0° to the page, and /// to the right of the path's direction when the rotation follows the path. A rotation turns the diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index 414a2d321c..d67c8e3ef5 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -342,7 +342,9 @@ pub(super) fn fill_slots( (p.opacity, p.blend, p.isolate, p.knockout, p.knockout_shape) = (state.0, state.1, state.2, state.3, shape); } else if transparent { for p in &mut parts { - Arc::make_mut(p).locked = false; + let p = Arc::make_mut(p); + p.visible = true; + p.locked = false; } let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); group.visible = visible; @@ -356,7 +358,9 @@ pub(super) fn fill_slots( if wrap.is_some() { if parts.len() > 1 { for p in &mut parts { - Arc::make_mut(p).locked = false; + let p = Arc::make_mut(p); + p.visible = true; + p.locked = false; } let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); group.visible = visible; @@ -706,4 +710,46 @@ mod tests { let inner = nodes[0].children().unwrap()[0].id; assert_eq!(filled.get(&slot), Some(&Filled { text: vec![inner], objects: vec![nodes[0].id, nodes[1].id] })); } + + /// A transparent slot wrapper group inherits hidden state while its inner children retain + /// intrinsic visibility, so showing the group makes the inner artwork visible. + #[test] + fn transparent_slot_wrapper_group_showing_reveals_inner_art() { + let mut doc = Document::new(100.0, 100.0); + let mut slot = Node::group(doc.alloc_id(), vec![]); + slot.name = Some("\u{0}text0:0".into()); + slot.visible = false; + slot.locked = true; + slot.opacity = 0.5; // see_through(n) == true -> transparent == true + + let part = |doc: &mut Document, x: f64| { + let t = vectorcraft_doc::TextObject::point(Point::new(x, 50.0), "Part", Default::default()); + Arc::new(Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)))) + }; + let parts = vec![part(&mut doc, 10.0), part(&mut doc, 60.0)]; + let mut nodes = vec![Arc::new(slot)]; + let mut content = vec![Content::Page(parts)].into_iter(); + let (mut empty, mut made, mut filled) = (0, vec![], std::collections::HashMap::new()); + fill_slots(&mut doc, &mut nodes, &mut content, &Default::default(), &mut empty, &mut made, &mut vec![], &mut filled); + + assert_eq!(nodes.len(), 1); + let group = &nodes[0]; + assert!(!group.visible, "wrapper group must inherit hidden state (visible = false)"); + assert!(group.locked, "wrapper group must inherit locked state"); + + let children = group.children().expect("must be a group of parts"); + assert_eq!(children.len(), 2); + for child in children { + assert!(child.visible, "inner child must retain intrinsic visibility (visible = true)"); + assert!(!child.locked, "inner child must not remain locked"); + } + + // Showing the group updates only the group node's visible field: + let mut shown = (**group).clone(); + shown.visible = true; + assert!(shown.visible); + for child in shown.children().unwrap() { + assert!(child.visible, "inner child is visible when parent group is shown"); + } + } } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index bc797c2e38..ca7844d69f 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8599,24 +8599,3 @@ fn ai_duplicate_visible_name_does_not_lock_multiple_from_single_private_node() { assert!(!r1.locked, "ambiguous duplicate visible name does not receive private lock"); assert!(!r2.locked, "second duplicate visible name remains unlocked"); } - -#[test] -fn ai_wrapped_group_places_lock_only_on_wrapper_group_not_children() { - let text = "1 A\n0 0.5 0 0 0 Xy\n(Styled Text) 10 50 Tt\n0 A"; - let art = native(&layer("Live", true, text)); - let (doc, _notes, read) = crate::layered_ai(&private(&art), pdf_two_squares(), vec![], false, true, 1.0); - assert!(read); - for layer in &doc.layers { - if let Some(kids) = layer.children() { - for kid in kids { - if kid.locked - && let Some(subkids) = kid.children() - { - for sub in subkids { - assert!(!sub.locked, "inner child of locked wrapper group must not be locked"); - } - } - } - } - } -} From af4266f4e3bc0ba713e6f739a2fd167c140d077f Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:42:10 +0530 Subject: [PATCH 20/72] Preserve intrinsic child visibility in slot wrapper groups without overwriting --- crates/eps/src/import/native/slots.rs | 99 +++++++++++++++++++-------- 1 file changed, 72 insertions(+), 27 deletions(-) diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index d67c8e3ef5..eb8959c9d4 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -307,12 +307,6 @@ pub(super) fn fill_slots( .iter() .map(|p| { let mut p = reid(doc, p); - if !visible { - Arc::make_mut(&mut p).visible = false; - } - if locked { - Arc::make_mut(&mut p).locked = true; - } if let Some(name) = name.filter(|_| matches!(p.kind, NodeKind::Text(_))) { Arc::make_mut(&mut p).name = Some(name.clone()); } @@ -321,6 +315,7 @@ pub(super) fn fill_slots( .collect(); let mut text = vec![]; text_ids(&parts, &mut text); + let mut wrapped = false; // When the page draws each of them with no transparency, the slot's, or the slot's // combined with that of the objects around it, the slot's takes its place: on the one // part, or on a group of several when the slot has transparency. Otherwise every part @@ -341,36 +336,39 @@ pub(super) fn fill_slots( let p = Arc::make_mut(p); (p.opacity, p.blend, p.isolate, p.knockout, p.knockout_shape) = (state.0, state.1, state.2, state.3, shape); } else if transparent { - for p in &mut parts { - let p = Arc::make_mut(p); - p.visible = true; - p.locked = false; - } let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); group.visible = visible; group.locked = locked; (group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = (state.0, state.1, state.2, state.3, shape); parts.push(Arc::new(group)); + wrapped = true; } } // A wrap object stays one: the page's parts of it in a group, when there are several. if wrap.is_some() { if parts.len() > 1 { - for p in &mut parts { - let p = Arc::make_mut(p); - p.visible = true; - p.locked = false; - } let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts)); group.visible = visible; group.locked = locked; parts.push(Arc::new(group)); + wrapped = true; } for p in &mut parts { Arc::make_mut(p).extras_mut().wrap = wrap; } } + if !wrapped { + for p in &mut parts { + let p = Arc::make_mut(p); + if !visible { + p.visible = false; + } + if locked { + p.locked = true; + } + } + } // One text object with the slot's appearance and transparency keeps its graphic style. if let ([p], Some(a)) = (parts.as_mut_slice(), styled.as_ref()) && linked.is_some() @@ -712,7 +710,8 @@ mod tests { } /// A transparent slot wrapper group inherits hidden state while its inner children retain - /// intrinsic visibility, so showing the group makes the inner artwork visible. + /// their original visibility (both visible and intrinsically hidden), so showing the group + /// reveals only the intrinsically visible artwork. #[test] fn transparent_slot_wrapper_group_showing_reveals_inner_art() { let mut doc = Document::new(100.0, 100.0); @@ -722,11 +721,14 @@ mod tests { slot.locked = true; slot.opacity = 0.5; // see_through(n) == true -> transparent == true - let part = |doc: &mut Document, x: f64| { + let part = |doc: &mut Document, x: f64, visible: bool| { let t = vectorcraft_doc::TextObject::point(Point::new(x, 50.0), "Part", Default::default()); - Arc::new(Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)))) + let mut node = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + node.visible = visible; + Arc::new(node) }; - let parts = vec![part(&mut doc, 10.0), part(&mut doc, 60.0)]; + // Page run contains both a visible child and an intrinsically hidden child: + let parts = vec![part(&mut doc, 10.0, true), part(&mut doc, 60.0, false)]; let mut nodes = vec![Arc::new(slot)]; let mut content = vec![Content::Page(parts)].into_iter(); let (mut empty, mut made, mut filled) = (0, vec![], std::collections::HashMap::new()); @@ -739,17 +741,60 @@ mod tests { let children = group.children().expect("must be a group of parts"); assert_eq!(children.len(), 2); - for child in children { - assert!(child.visible, "inner child must retain intrinsic visibility (visible = true)"); - assert!(!child.locked, "inner child must not remain locked"); - } + assert!(children[0].visible, "intrinsically visible child retains visible = true"); + assert!(!children[0].locked, "inner child must not be locked"); + assert!(!children[1].visible, "intrinsically hidden child retains visible = false"); + assert!(!children[1].locked, "inner child must not be locked"); // Showing the group updates only the group node's visible field: let mut shown = (**group).clone(); shown.visible = true; assert!(shown.visible); - for child in shown.children().unwrap() { - assert!(child.visible, "inner child is visible when parent group is shown"); - } + let shown_children = shown.children().unwrap(); + assert!(shown_children[0].visible, "intrinsically visible child is visible when parent group is shown"); + assert!(!shown_children[1].visible, "intrinsically hidden child remains hidden when parent group is shown"); + } + + /// A wrap slot wrapper group inherits hidden and locked states without overwriting children's + /// original visibility flags when a page run contains both visible and intrinsically hidden children. + #[test] + fn wrap_slot_wrapper_group_preserves_child_visibility_and_showing_reveals_art() { + let mut doc = Document::new(100.0, 100.0); + let mut slot = Node::group(doc.alloc_id(), vec![]); + slot.name = Some("\u{0}text0:0".into()); + slot.visible = false; + slot.locked = true; + let wrap = vectorcraft_doc::TextWrap { offset: 3.0, invert: true }; + slot.extras_mut().wrap = Some(wrap); + + let part = |doc: &mut Document, x: f64, visible: bool| { + let t = vectorcraft_doc::TextObject::point(Point::new(x, 50.0), "Part", Default::default()); + let mut node = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + node.visible = visible; + Arc::new(node) + }; + let parts = vec![part(&mut doc, 10.0, true), part(&mut doc, 60.0, false)]; + let mut nodes = vec![Arc::new(slot)]; + let mut content = vec![Content::Page(parts)].into_iter(); + let (mut empty, mut made, mut filled) = (0, vec![], std::collections::HashMap::new()); + fill_slots(&mut doc, &mut nodes, &mut content, &Default::default(), &mut empty, &mut made, &mut vec![], &mut filled); + + assert_eq!(nodes.len(), 1); + let group = &nodes[0]; + assert!(!group.visible, "wrap wrapper group must inherit hidden state"); + assert!(group.locked, "wrap wrapper group must inherit locked state"); + + let children = group.children().expect("must be a group of parts"); + assert_eq!(children.len(), 2); + assert!(children[0].visible, "intrinsically visible child retains visible = true"); + assert!(!children[0].locked, "inner child must not be locked"); + assert!(!children[1].visible, "intrinsically hidden child retains visible = false"); + assert!(!children[1].locked, "inner child must not be locked"); + + let mut shown = (**group).clone(); + shown.visible = true; + let shown_children = shown.children().unwrap(); + assert!(shown_children[0].visible, "intrinsically visible child is visible when parent group is shown"); + assert!(!shown_children[1].visible, "intrinsically hidden child remains hidden when parent group is shown"); } } From a0455ff1176e0729119d9400601ed5bb65c271b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 22:40:41 -0800 Subject: [PATCH 21/72] Tests: the plugin script-gate test sets ScriptGate's held files ScriptGate has a `held` field for the files a script holds open for writing. A plugin test that main added builds a ScriptGate without it, so the engine's tests did not compile after merging main. The test holds no files open, so `held` is empty. --- crates/engine/src/tests/plugins.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 1ae16ec6a8..c6da92ac55 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2202,6 +2202,7 @@ fn a_script_loads_no_plugin_from_outside_its_folder_through_a_name_that_is_not_t read: ScriptScope::of_folder(&inside), write: ScriptScope::default(), documents: vec![], + held: vec![], linked: Default::default(), also: None, }; From 5220051f74cb95868543ba09bb606bf1c05e0182 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 21:05:43 -0800 Subject: [PATCH 22/72] Scripts: a print option with no upper limit reports no maximum in reflect PrintJobOptions.bitmapResolution declared f64::MAX as its maximum, which JavaScript prints as 1.7976931348623157e+308 while the declaration test formats it in full, so reflect_of_every_class_equals_its_declaration failed after main's reflect check met the print option classes. --- crates/engine/src/script/dom/print.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index efcb2b6aa1..55c9c87e28 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -1142,7 +1142,8 @@ pub(super) fn document_members(l: &Link) -> Vec { fn field_info(field: &Field) -> MemberInfo { match field.kind { Kind::Bool => typed("boolean"), - Kind::Number(min, max) => MemberInfo { min: Some(min), max: Some(max), ..typed("number") }, + // A field with no upper limit, such as `bitmapResolution`, reports no maximum. + Kind::Number(min, max) => MemberInfo { min: Some(min), max: (max < f64::MAX).then_some(max), ..typed("number") }, #[allow(clippy::cast_precision_loss)] Kind::Whole(min, max) => MemberInfo { min: Some(min as f64), max: Some(max as f64), ..typed("number") }, Kind::Text => typed("string"), From 9334f11ddf389c855e7e86c8844a06c9f486ad61 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 07:23:57 -0800 Subject: [PATCH 23/72] Color Effects: Randomize Fill Colors gives each selected filled path its own random fill MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Object › Plug-ins › Color Effects › Randomize Fill Colors… gives each selected filled path and compound path, and each one inside the selected groups and clipping groups, a fill color of its own, picked at random from a seed, as one undo step (none when no fill changes). - addon.color.randomFill {scheme?, swatch?, min?, max?, seed?, ids?}: "color" picks red, green and blue at random in the document's color mode, "tint" picks a linked tint of a global or spot swatch, and "gray" picks a gray, the tints and grays between min and max percent. - Unfilled paths, clipping paths (compound ones included), hidden and locked objects and the objects in hidden or locked groups and layers, type, images, symbol instances, blends and envelopes keep their fills. A compound path's member given by id colors the compound path, and an object reached twice is colored once. - Bad params are refused: an unknown scheme, min or max with "color", swatch without "tint", a percent outside 0 to 100, min above max, a missing or process swatch, and a seed that is not a whole number. - The dialog has Colors, Swatch (the document's global and spot swatches), Minimum, Maximum and Seed, with Preview; OK is off while the minimum is above the maximum or tints have no swatch. Docs: docs/mcp.md, ROADMAP, docs/target-app-parity.md, docs/ui-parity.md. --- ROADMAP.md | 1 + crates/engine/src/cmd/addons/color.rs | 13 +- .../src/cmd/addons/color/random_fill.rs | 145 ++++++++++ .../src/cmd/addons/color/random_fill/tests.rs | 261 ++++++++++++++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + .../engine/src/tests/ids_without_selection.rs | 1 + crates/engine/tests/command_sweep.rs | 3 + crates/ui-egui/src/addons/color.rs | 6 +- .../ui-egui/src/addons/color/random_fill.rs | 91 ++++++ .../src/addons/color/random_fill/tests.rs | 116 ++++++++ crates/ui-egui/src/addons/dialogs.rs | 1 + crates/ui-egui/src/addons/dialogs/tests.rs | 21 ++ docs/mcp.md | 25 ++ docs/target-app-parity.md | 5 + docs/ui-parity.md | 1 + 15 files changed, 688 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/cmd/addons/color/random_fill.rs create mode 100644 crates/engine/src/cmd/addons/color/random_fill/tests.rs create mode 100644 crates/ui-egui/src/addons/color/random_fill.rs create mode 100644 crates/ui-egui/src/addons/color/random_fill/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index d40c33e9e1..8e908b8e72 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -160,6 +160,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923). +- 2026-11-29: Randomize Fill Colors joins the Color Effects add-on (Object › Plug-ins › Color Effects): each selected filled path and compound path, inside groups too, gets a fill color of its own at random: any color, tints of a global or spot swatch, or grays between a minimum and a maximum percent, with a seed that repeats the result and Preview, as one undo step (`addon.color.randomFill`). - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index c12eb2fa64..8be52f6b8f 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -5,12 +5,14 @@ //! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest //! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend //! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply -//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across. Its panel and its submenu, +//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across, and Randomize Fill Colors +//! ([`random_fill`]) gives each filled path its own color at random. Its panel and its submenu, //! Object › Plug-ins › Color Effects, are the UI's. pub mod legend; mod nearest; mod print_fixes; +mod random_fill; #[cfg(test)] mod tests; @@ -92,6 +94,15 @@ pub fn specs() -> Vec { has_doc, |s, p| copy_paint(s, p, false) ), + cmd!( + "addon.color.randomFill", + "Randomize Fill Colors", + ["Object", "Plug-ins", "Color Effects"], + None, + "{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors), ids?: [id…] (default: the selection)} give each selected filled path and compound path, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Paths and compound paths with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers), type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}", + has_selection, + random_fill::run + ), ] .into_iter() .chain(legend::specs()) diff --git a/crates/engine/src/cmd/addons/color/random_fill.rs b/crates/engine/src/cmd/addons/color/random_fill.rs new file mode 100644 index 0000000000..dbab9cd4a2 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/random_fill.rs @@ -0,0 +1,145 @@ +//! Randomize Fill Colors (`addon.color.randomFill`, Object › Plug-ins › Color Effects › Randomize +//! Fill Colors…): each selected filled path and compound path, and each one inside the selected +//! groups, gets a fill color of its own, picked at random from a seed: any color, a tint of one +//! global or spot swatch, or a gray, as one undo step. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_color::recolor::Rng; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; + +use super::super::super::colorcmds::{edit_if_changed, keeping_series_paint}; +use super::super::super::graph::paint_targets; +use super::super::super::menucmds::whole_or; +use super::super::super::paint::swatch_solid; +use super::super::super::{bad, checked_ids_or_selection, number_or, text_param}; +use crate::{Result, Session}; + +const C: &str = "addon.color.randomFill"; +/// The schemes the colors are picked from (`scheme`). +pub const SCHEMES: [&str; 3] = ["color", "tint", "gray"]; + +/// How each color is picked. +enum Scheme { + /// Any color: red, green and blue each at random, in the document's color mode. + Color, + /// A tint of the swatch, from the least to the most (0..1). + Tint(String, f32, f32), + /// A gray, from the least black to the most (0..1). + Gray(f32, f32), +} + +/// The percentage `p` gives for `key` (`default` when left out) as a fraction. +fn percent(p: &Value, key: &str, default: f64) -> Result { + let v = number_or(p, key, default, C)?; + if (0.0..=100.0).contains(&v) { Ok((v / 100.0) as f32) } else { Err(bad(C, format!("`{key}` must be from 0 to 100"))) } +} + +/// The scheme `p` asks for, checked against the document's swatches. +fn scheme(s: &Session, p: &Value) -> Result { + let name = text_param(p, "scheme", C)?.unwrap_or("color"); + if !SCHEMES.contains(&name) { + return Err(bad(C, "`scheme` must be color, tint or gray")); + } + let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null()); + if name == "color" && (given("min") || given("max")) { + return Err(bad(C, "`min` and `max` go with scheme tint or gray")); + } + if name != "tint" && given("swatch") { + return Err(bad(C, "`swatch` goes with scheme tint")); + } + if name == "color" { + return Ok(Scheme::Color); + } + let (min, max) = (percent(p, "min", 0.0)?, percent(p, "max", 100.0)?); + if min > max { + return Err(bad(C, "`min` is greater than `max`")); + } + if name == "gray" { + return Ok(Scheme::Gray(min, max)); + } + let swatch = text_param(p, "swatch", C)?.ok_or_else(|| bad(C, "scheme tint needs a `swatch`: a global or spot color swatch"))?; + swatch_solid(&s.doc()?.doc, swatch, Some(1.0)).map_err(|e| bad(C, e))?; + Ok(Scheme::Tint(swatch.to_string(), min, max)) +} + +/// Whether the object `id` is left as it is: it, or a layer or group holding it, is hidden or +/// locked, or it is the clipping path of the group or layer holding it. +fn left_alone(d: &Document, id: NodeId) -> bool { + let Some(line) = d.ancestry(id) else { return true }; + let nodes: Vec<&Node> = line.iter().filter_map(|id| d.node(*id)).collect(); + if nodes.len() != line.len() || nodes.iter().any(|n| !n.visible || n.locked) { + return true; + } + matches!(nodes.as_slice(), [.., parent, n] if parent.clips() && parent.children().and_then(|c| c.first()).is_some_and(|c| c.id == n.id)) +} + +/// Add to `out` `n` when it is a filled path or compound path that is shown and unlocked, or the +/// ones inside it when it is a group or a layer. A clipping path (the first object of a clipping +/// group or clipped layer, a compound path included), a guide, type, images, symbol instances, +/// blends and envelopes are left as they are. +fn filled(n: &Node, out: &mut Vec) { + if !n.visible || n.locked { + return; + } + match &n.kind { + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { + for c in children.iter().skip(usize::from(n.clips())) { + filled(c, out); + } + } + NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. } if !n.appearance.fill_paint().is_none() => out.push(n.id), + _ => {} + } +} + +pub(super) fn run(s: &mut Session, p: &Value) -> Result { + let scheme = scheme(s, p)?; + let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); + let ids = checked_ids_or_selection(s, p, C)?; + if ids.is_empty() { + return Ok(json!({ "count": 0 })); + } + let model = s.doc()?.doc.color_mode.model(); + // A run that gives every object the fill it has records no undo step. + let count = edit_if_changed(s, "Randomize Fill Colors", |before, d| { + // A graph's series group stands for its marks, as for `paint.setFill`. + let roots = paint_targets(before, &ids); + let mut targets = vec![]; + for id in &roots { + let id = before + .parent_of(*id) + .filter(|parent| before.node(*parent).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))) + .unwrap_or(*id); + if left_alone(before, id) { + continue; + } + let Some(n) = before.node(id) else { continue }; + filled(n, &mut targets); + } + let mut seen = std::collections::HashSet::new(); + targets.retain(|id| seen.insert(*id)); + let count = keeping_series_paint(d, &roots, |d| { + let mut count = 0; + for id in &targets { + let paint = match &scheme { + Scheme::Color => Paint::solid(Color::rgb(rng.range(0.0, 1.0), rng.range(0.0, 1.0), rng.range(0.0, 1.0)).in_model(model)), + Scheme::Tint(swatch, lo, hi) => swatch_solid(d, swatch, Some(rng.range(*lo, *hi))).map_err(|e| bad(C, e))?, + Scheme::Gray(lo, hi) => Paint::solid(Color::gray(rng.range(*lo, *hi))), + }; + if let Some(n) = d.node_mut(*id) + && n.appearance.fill_paint() != paint + { + n.appearance.set_fill(paint); + count += 1; + } + } + Ok(count) + })?; + Ok((count, count > 0)) + })?; + Ok(json!({ "count": count })) +} diff --git a/crates/engine/src/cmd/addons/color/random_fill/tests.rs b/crates/engine/src/cmd/addons/color/random_fill/tests.rs new file mode 100644 index 0000000000..ca353e43d4 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/random_fill/tests.rs @@ -0,0 +1,261 @@ +//! Randomize Fill Colors: the colors each scheme gives, which objects take them, one undo step, and +//! bad params refused without a change. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{NodeId, NodeKind}; + +use crate::Session; + +const C: &str = "addon.color.randomFill"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap()) +} + +fn rects(s: &mut Session, n: usize) -> Vec { + (0..n).map(|i| rect(s, i as f64 * 10.0)).collect() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn fill(s: &Session, id: NodeId) -> Paint { + s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() +} + +fn fills(s: &Session, ids: &[NodeId]) -> Vec { + ids.iter().map(|id| fill(s, *id)).collect() +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn enabled(s: &Session, cmd: &str) -> bool { + s.commands().into_iter().find(|c| c.id == cmd).unwrap().enabled +} + +#[test] +fn each_object_gets_its_own_color_from_the_seed() { + let mut s = session(); + let ids = rects(&mut s, 12); + select(&mut s, &ids); + let before = fills(&s, &ids); + let n = steps(&s); + let r = s.execute(C, &json!({"seed": 7})).unwrap(); + assert_eq!(r["count"], json!(12)); + assert_eq!(steps(&s), n + 1, "one undo step"); + let first = fills(&s, &ids); + assert!(first.iter().all(|p| matches!(p, Paint::Solid { color: Color::Rgb { .. }, swatch: None, .. })), "{first:?}"); + assert!(first.windows(2).all(|w| w[0] != w[1]), "each its own: {first:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(fills(&s, &ids), before, "undone"); + // The same seed repeats them; another seed doesn't. + s.execute(C, &json!({"seed": 7})).unwrap(); + assert_eq!(fills(&s, &ids), first); + s.execute(C, &json!({"seed": 8})).unwrap(); + assert_ne!(fills(&s, &ids), first); +} + +#[test] +fn repeated_ids_take_one_color_from_the_seed() { + let mut s = session(); + let a = rect(&mut s, 0.0); + assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 7})).unwrap()["count"], json!(1)); + let once = fill(&s, a); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.execute(C, &json!({"ids": [a.0, a.0], "seed": 7})).unwrap()["count"], json!(1)); + assert_eq!(fill(&s, a), once); +} + +#[test] +fn a_cmyk_document_gets_cmyk_colors() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + let ids = rects(&mut s, 3); + select(&mut s, &ids); + s.execute(C, &json!({"scheme": "color"})).unwrap(); + assert!(fills(&s, &ids).iter().all(|p| matches!(p, Paint::Solid { color: Color::Cmyk { .. }, .. })), "{:?}", fills(&s, &ids)); +} + +#[test] +fn grays_and_tints_stay_within_the_range() { + let mut s = session(); + let ids = rects(&mut s, 20); + select(&mut s, &ids); + s.execute(C, &json!({"scheme": "gray", "min": 20, "max": 40, "seed": 3})).unwrap(); + let grays: Vec = fills(&s, &ids) + .into_iter() + .map(|p| match p { + Paint::Solid { color: Color::Gray { k }, swatch: None, .. } => k, + other => panic!("not a gray: {other:?}"), + }) + .collect(); + assert!(grays.iter().all(|k| (0.2..=0.4).contains(k)), "{grays:?}"); + assert!(grays.windows(2).any(|w| w[0] != w[1]), "{grays:?}"); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap(); + s.execute(C, &json!({"scheme": "tint", "swatch": "Ink", "min": 10, "max": 50, "seed": 3})).unwrap(); + for p in fills(&s, &ids) { + let Paint::Solid { swatch: Some(name), tint, .. } = p else { panic!("not linked: {p:?}") }; + assert_eq!(name, "Ink"); + assert!((0.1..=0.5).contains(&tint), "{tint}"); + } + // min = max gives every object that gray. + s.execute(C, &json!({"scheme": "gray", "min": 45, "max": 45})).unwrap(); + assert!(fills(&s, &ids).iter().all(|p| *p == Paint::solid(Color::gray(0.45)))); +} + +#[test] +fn groups_are_entered_and_unfilled_hidden_and_locked_objects_left_alone() { + let mut s = session(); + let [a, b, c, hidden, locked] = [0.0, 10.0, 20.0, 30.0, 40.0].map(|x| rect(&mut s, x)); + select(&mut s, &[a, b, c, hidden, locked]); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [c.0], "none": true})).unwrap(); + s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap(); + s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap(); + select(&mut s, &[g]); + let (before_hidden, before_locked) = (fill(&s, hidden), fill(&s, locked)); + assert!(!before_hidden.is_none() && !before_locked.is_none()); + let r = s.execute(C, &json!({"scheme": "gray", "min": 50, "max": 50})).unwrap(); + assert_eq!(r["count"], json!(2)); + let gray = Paint::solid(Color::gray(0.5)); + assert_eq!((fill(&s, a), fill(&s, b), fill(&s, c)), (gray.clone(), gray.clone(), Paint::None), "the unfilled one keeps None"); + assert_eq!(fill(&s, g), Paint::None, "the group gets no fill of its own"); + assert_eq!((fill(&s, hidden), fill(&s, locked)), (before_hidden, before_locked)); + // `ids` stand in for the selection; with nothing selected the menu item is off. + s.execute("select.none", &json!({})).unwrap(); + assert!(!enabled(&s, C)); + let d = rect(&mut s, 50.0); + s.execute("paint.setFill", &json!({"ids": [d.0], "color": "#336699"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute(C, &json!({"ids": [d.0], "scheme": "gray", "min": 10, "max": 10})).unwrap(); + assert_eq!(fill(&s, d), Paint::solid(Color::gray(0.1))); + assert_eq!(fill(&s, a), gray, "not among ids"); + // An object given by id inside a hidden or locked group keeps its fill. + for hide in [true, false] { + let e = rect(&mut s, 60.0); + s.execute("paint.setFill", &json!({"ids": [e.0], "color": "#336699"})).unwrap(); + select(&mut s, &[e]); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute(if hide { "object.hide" } else { "object.lock" }, &json!({"ids": [outer.0]})).unwrap(); + let kept = fill(&s, e); + assert_eq!(s.execute(C, &json!({"ids": [e.0], "scheme": "gray"})).unwrap()["count"], json!(0), "hidden group: {hide}"); + assert_eq!(fill(&s, e), kept); + } +} + +#[test] +fn a_compound_path_takes_one_color_and_a_clipping_path_none() { + let mut s = session(); + let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x)); + select(&mut s, &[a, b]); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + // The topmost becomes the clipping path. + let [art, mask] = [100.0, 102.0].map(|x| rect(&mut s, x)); + select(&mut s, &[art, mask]); + let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let is_clipping = |s: &Session, id: NodeId| matches!(s.doc().unwrap().doc.node(id).unwrap().kind, NodeKind::Path { clipping: true, .. }); + assert!(is_clipping(&s, mask) && !is_clipping(&s, art)); + // A clipping path given a fill still keeps it. + s.execute("paint.setFill", &json!({"ids": [mask.0], "color": "#00ff00"})).unwrap(); + let mask_fill = fill(&s, mask); + assert!(!mask_fill.is_none()); + select(&mut s, &[compound, clip]); + let r = s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap(); + assert_eq!(r["count"], json!(2), "the compound path and the clipped art"); + assert_eq!(fill(&s, compound), Paint::solid(Color::gray(0.3))); + assert_eq!(fill(&s, art), Paint::solid(Color::gray(0.3))); + assert_eq!(fill(&s, mask), mask_fill, "the clipping path keeps its fill"); + // Given by id, the clipping path keeps it too. + assert_eq!(s.execute(C, &json!({"ids": [mask.0], "scheme": "gray"})).unwrap()["count"], json!(0)); + assert_eq!(fill(&s, mask), mask_fill); +} + +#[test] +fn a_compound_member_given_by_id_colors_the_compound() { + let mut s = session(); + let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x)); + select(&mut s, &[a, b]); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let before = fill(&s, compound); + let members = fills(&s, &[a, b]); + assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 7})).unwrap()["count"], json!(1)); + assert_ne!(fill(&s, compound), before); + assert_eq!(fills(&s, &[a, b]), members); +} + +#[test] +fn a_compound_clipping_path_keeps_its_fill() { + let mut s = session(); + let art = rect(&mut s, 0.0); + let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x)); + select(&mut s, &[a, b]); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[art, compound]); + let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.node(clip).unwrap().children().unwrap()[0].id, compound, "the compound path clips"); + s.execute("paint.setFill", &json!({"ids": [compound.0], "color": "#00ff00"})).unwrap(); + let mask_fill = fill(&s, compound); + assert!(!mask_fill.is_none()); + select(&mut s, &[clip]); + assert_eq!(s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(1), "the clipped art only"); + assert_eq!(fill(&s, art), Paint::solid(Color::gray(0.3))); + assert_eq!(fill(&s, compound), mask_fill); +} + +#[test] +fn no_undo_step_when_no_fill_changes() { + let mut s = session(); + let ids = rects(&mut s, 2); + select(&mut s, &ids); + s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap(); + let n = steps(&s); + let r = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap(); + assert_eq!((r["count"].clone(), steps(&s)), (json!(0), n), "the same grays again"); + // Only unfilled objects: nothing to color. + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + let n = steps(&s); + assert_eq!(s.execute(C, &json!({})).unwrap()["count"], json!(0)); + assert_eq!(steps(&s), n); +} + +#[test] +fn bad_params_are_refused() { + let mut s = session(); + let a = rect(&mut s, 0.0); + select(&mut s, &[a]); + s.execute("swatch.new", &json!({"name": "Process", "color": "#336699"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap(); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let bad: [(Value, &str); 14] = [ + (json!({"scheme": "rainbow"}), "`scheme` must be color, tint or gray"), + (json!({"scheme": 3}), "`scheme` must be a string"), + (json!({"min": 10}), "`min` and `max` go with scheme tint or gray"), + (json!({"scheme": "gray", "swatch": "Ink"}), "`swatch` goes with scheme tint"), + (json!({"scheme": "gray", "min": -1}), "`min` must be from 0 to 100"), + (json!({"scheme": "gray", "max": 101}), "`max` must be from 0 to 100"), + (json!({"scheme": "gray", "min": 80, "max": 20}), "`min` is greater than `max`"), + (json!({"scheme": "gray", "max": "50"}), "`max` must be a number"), + (json!({"scheme": "tint"}), "scheme tint needs a `swatch`"), + (json!({"scheme": "tint", "swatch": "Nope"}), "no swatch `Nope`"), + (json!({"scheme": "tint", "swatch": "Process"}), "is a process colour"), + (json!({"seed": -1}), "`seed` must be a whole number"), + (json!({"seed": 1.5}), "`seed` must be a whole number"), + (json!({"ids": [999_999]}), "no such object id"), + ]; + for (p, want) in bad { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before, "the document is unchanged"); +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index c2699f219c..15ea58096a 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -28,6 +28,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.color.fillToStroke", "addon.color.filter", "addon.color.nearestSwatch", + "addon.color.randomFill", "addon.color.select", "addon.color.strokeToFill", "addon.color.swatchLegend", diff --git a/crates/engine/src/tests/ids_without_selection.rs b/crates/engine/src/tests/ids_without_selection.rs index 9a48655468..cc7e03114f 100644 --- a/crates/engine/src/tests/ids_without_selection.rs +++ b/crates/engine/src/tests/ids_without_selection.rs @@ -523,6 +523,7 @@ fn ids_null_takes_the_selection_in_every_command_that_falls_back_to_it() { ("addon.cleanup.deepUngroup", json!({}), rect), ("addon.cleanup.rejoin", json!({}), rect), ("addon.color.nearestSwatch", json!({}), rect), + ("addon.color.randomFill", json!({"seed": 1}), rect), ("addon.pathtools.cornerSet", json!({"radius": 2}), rect), ("addon.pathtools.cornerRemove", json!({}), rect), ("addon.pathtools.shape.convert", json!({}), rect), diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 462641b953..14fe379e6c 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -805,6 +805,9 @@ fn structured_junk() { ("addon.color.nearestSwatch", json!({"library": "spectrum-gradients", "fill": "x", "ids": [u64::MAX]})), ("addon.color.applyNearestSwatch", json!({"library": "web-safe-216", "fill": true, "stroke": true})), ("addon.color.applyNearestSwatch", json!({"library": "nope", "ids": "x", "stroke": 3})), + ("addon.color.randomFill", json!({"seed": u64::MAX})), + ("addon.color.randomFill", json!({"scheme": "gray", "min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})), + ("addon.color.randomFill", json!({"scheme": "tint", "swatch": "[Registration]", "min": 100, "max": 0, "seed": 1e308, "ids": []})), ("effect.apply", json!({"effect": "no.such.effect"})), ("effect.remove", json!({"index": 99})), ("effect.remove", json!({"indices": [0, 99, u64::MAX]})), diff --git a/crates/ui-egui/src/addons/color.rs b/crates/ui-egui/src/addons/color.rs index 6696e4b0d3..f9d86ab058 100644 --- a/crates/ui-egui/src/addons/color.rs +++ b/crates/ui-egui/src/addons/color.rs @@ -3,11 +3,12 @@ //! filter, into the colours themselves (`addon.color.filter`); below, under Inks, it opens Duotone's //! dialog and Print Ink Fixes' (`addon.color.printFixes`). The submenu applies the add-on's live //! effects, Duotone and Vector Halftone among them (Effect › Color Effects has them too), opens -//! Print Ink Fixes, Find Nearest Swatch ([`nearest`]) and Create Swatch Legend ([`legend`]) and -//! opens the panel. +//! Print Ink Fixes, Find Nearest Swatch ([`nearest`]), Create Swatch Legend ([`legend`]) and +//! Randomize Fill Colors ([`random_fill`]) and opens the panel. pub mod legend; pub mod nearest; +pub mod random_fill; use craft::imaging::ui::adjust::{AdjustContext, AdjustField, AdjustSliders}; use craft::menu::Node; @@ -116,6 +117,7 @@ pub fn menu() -> Vec { // Each selected object's stroke takes its own fill, or the other way (#5530). cp("Apply Fill to Stroke", "addon.color.fillToStroke", json!({})), cp("Apply Stroke to Fill", "addon.color.strokeToFill", json!({})), + c("Randomize Fill Colors…", random_fill::COMMAND), Sep, sub( "Select by Color Kind", diff --git a/crates/ui-egui/src/addons/color/random_fill.rs b/crates/ui-egui/src/addons/color/random_fill.rs new file mode 100644 index 0000000000..1ed59cb694 --- /dev/null +++ b/crates/ui-egui/src/addons/color/random_fill.rs @@ -0,0 +1,91 @@ +//! Randomize Fill Colors in the interface (Object › Plug-ins › Color Effects › Randomize Fill +//! Colors…): a dialog that picks the colors (any color, tints of a global or spot swatch, or +//! grays), the swatch, the minimum and maximum and the seed, previews on the canvas and runs +//! `addon.color.randomFill` on OK. + +use std::borrow::Cow; + +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind}; +use craft::ui::runtime::env::{Label, UnitKind}; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::addons::dialogs::Spec; +use crate::dialogs::form; + +/// The command OK runs, and the dialog's key. +pub const COMMAND: &str = "addon.color.randomFill"; +/// The seeds the dialog offers. +const SEEDS: u64 = 1_000_000; +/// The schemes the Colors choice offers: (`scheme`, label). +const SCHEMES: [(&str, &str); 3] = [("color", "Any Color"), ("tint", "Tints of a Swatch"), ("gray", "Grays")]; + +static SPEC: Spec = Spec { command: COMMAND, params, found: None }; + +fn percent(key: &str, label: &'static str, default: f64) -> Param { + Param::number(key, tl!(label), default, 1.0, 0).bounds(Some(0.0), Some(100.0)).unit(UnitKind::Percent).enabled_when_in("scheme", ["tint", "gray"]) +} + +/// The dialog's rows; the Swatch choice offers `swatches`. +fn rows(swatches: &[String]) -> Vec { + let schemes = SCHEMES.iter().map(|&(id, text)| (id.to_string(), tl!(text).into())).collect(); + let swatches: Vec<(String, Label)> = swatches.iter().map(|name| (name.clone(), name.clone().into())).collect(); + let first = swatches.first().map(|(id, _)| id.clone()); + vec![ + Param::new("scheme", tl!("Colors:"), ParamKind::choice(schemes, Some("color".into()))), + Param::new("swatch", tl!("Swatch:"), ParamKind::choice(swatches, first)).enabled_when("scheme", "tint"), + percent("min", "Minimum:", 0.0), + percent("max", "Maximum:", 100.0), + Param::new("seed", tl!("Seed:"), ParamKind::int(Some(0), Some(SEEDS as i64 - 1), 0)), + ] +} + +/// The command's params: the swatch only for tints, the minimum and maximum only for tints and grays. +fn params(fields: &DialogFields) -> Value { + let mut p = form::json_of(&rows(&[]), fields); + let scheme = fields.text("scheme").unwrap_or("color"); + if scheme != "tint" { + p.remove("swatch"); + } + if scheme == "color" { + p.remove("min"); + p.remove("max"); + } + Value::Object(p) +} + +/// Why OK is off, if it is: a minimum above the maximum, or tints with no swatch to take them from. +fn refusal(fields: &DialogFields) -> Option<&'static str> { + let scheme = fields.text("scheme").unwrap_or("color"); + if scheme == "tint" && fields.text("swatch").is_none_or(str::is_empty) { + return Some("Make a global or spot swatch first."); + } + let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0)); + (scheme != "color" && min > max).then_some("The minimum is above the maximum.") +} + +/// Opens the dialog on the active document: its global and spot swatches in the Swatch choice, and a new seed whenever +/// the document has changed, so running it again gives other colors while Preview and OK agree. +pub(crate) fn open(app: &mut VectorcraftApp) -> Result { + let st = app.session.active().ok_or("no document")?; + let swatches: Vec = st.doc.swatches_iter().filter(|w| st.doc.global_color(&w.name).is_some()).map(|w| w.name.clone()).collect(); + let mut opening = json!({ "scheme": "color", "min": 0, "max": 100, "seed": st.revision % SEEDS }); + if let (Some(first), Some(o)) = (swatches.first(), opening.as_object_mut()) { + o.insert("swatch".into(), json!(first)); + } + let rows = rows(&swatches); + let fields = form::fields_of(&rows, opening.as_object().ok_or("no params")?); + super::super::dialogs::open(app, &SPEC, fields, move |fields| { + let refused = refusal(fields); + let mut dialog = + ParamDialog::new(COMMAND, tl!("Randomize Fill Colors"), Cow::Owned(rows.clone())).previews(true).ok_enabled(refused.is_none()); + if let Some(reason) = refused { + dialog = dialog.ok_reason(tl!(reason).into()); + } + dialog.values(Bind::bound(fields)) + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/color/random_fill/tests.rs b/crates/ui-egui/src/addons/color/random_fill/tests.rs new file mode 100644 index 0000000000..c75a003b63 --- /dev/null +++ b/crates/ui-egui/src/addons/color/random_fill/tests.rs @@ -0,0 +1,116 @@ +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::Session; + +use crate::addons::dialogs::tests::{self as host, open_item}; +use crate::tests::panel_harness::Panel as Harness; +use crate::{VectorcraftApp, menus}; + +/// An app with a window, where its dialogs open, and two filled rectangles, both selected. +fn app() -> (VectorcraftApp, NodeId, NodeId) { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let mut rect = |x| NodeId(app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 10})).unwrap()["id"].as_u64().unwrap()); + let (a, b) = (rect(0), rect(100)); + app.run("select.all", json!({})).unwrap(); + (app, a, b) +} + +fn fill(app: &VectorcraftApp, id: NodeId) -> Paint { + app.session.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() +} + +fn open(app: &mut VectorcraftApp) { + open_item(app, "Color Effects", "Randomize Fill Colors…"); +} + +/// Replace a numeric field's text and commit by moving focus, without confirming the dialog. +fn type_number(panel: &mut Harness, label: &str, text: &str) { + panel.click(label); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); +} + +#[test] +fn the_menu_item_opens_the_dialog_on_its_command() { + let (mut app, a, b) = app(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Color Effects"] && e.label == "Randomize Fill Colors…").unwrap(); + assert_eq!(item.command.as_deref(), Some(super::COMMAND)); + open(&mut app); + let id = host::dialog_id(&app); + let opened = host::read(&app, id, |f| (f.text("scheme").map(str::to_owned), f.number("min"), f.number("max"))); + assert_eq!(opened, (Some("color".into()), Some(0.0), Some(100.0))); + // OK on the opening values: any color, each object its own. + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(matches!(fill(&app, a), Paint::Solid { color: Color::Rgb { .. }, swatch: None, .. }), "{:?}", fill(&app, a)); + assert_ne!(fill(&app, a), fill(&app, b)); +} + +#[test] +fn typed_grays_preview_run_on_ok_and_roll_back_on_cancel() { + let (app, a, b) = app(); + let original = fill(&app, a); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + open(&mut panel.app()); + let id = host::dialog_id(&panel.app()); + host::set(&panel.app(), id, "scheme", json!("gray")); + panel.frame(); + type_number(&mut panel, "Minimum", "80"); + type_number(&mut panel, "Maximum", "20"); + assert!(!panel.enabled("OK"), "a minimum above the maximum disables confirmation"); + type_number(&mut panel, "Maximum", "80"); + assert!(panel.enabled("OK")); + let undo = panel.app().session.doc().unwrap().history.undo.len(); + panel.click("OK"); + panel.frame(); + let gray = Paint::solid(Color::gray(0.8)); + { + let app = panel.app(); + assert_eq!((fill(&app, a), fill(&app, b)), (gray.clone(), gray.clone())); + let history = &app.session.doc().unwrap().history; + assert_eq!(history.undo.len(), undo + 1, "one undo step"); + assert_eq!(history.undo.last().unwrap().label, "Randomize Fill Colors"); + } + // Typed values preview at once; Cancel puts the fills back. + open(&mut panel.app()); + let id = host::dialog_id(&panel.app()); + host::set(&panel.app(), id, "scheme", json!("gray")); + host::set(&panel.app(), id, "preview", json!(true)); + panel.frame(); + type_number(&mut panel, "Minimum", "25"); + type_number(&mut panel, "Maximum", "25"); + assert_eq!(fill(&panel.app(), a), Paint::solid(Color::gray(0.25)), "previewed"); + panel.click("Cancel"); + panel.frame(); + let app = panel.app(); + assert_eq!((fill(&app, a), fill(&app, b)), (gray.clone(), gray)); + assert_ne!(fill(&app, a), original); +} + +#[test] +fn tints_need_a_swatch_and_take_the_first_one() { + let (mut app, a, _) = app(); + open(&mut app); + let id = host::dialog_id(&app); + host::set(&app, id, "scheme", json!("tint")); + assert!(!host::confirm(&app, id), "no global or spot swatch to tint"); + host::cancel(&app, id); + host::frame(&mut app); + app.run("swatch.new", json!({"name": "Process", "color": "#336699"})).unwrap(); + app.run("swatch.new", json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap(); + open(&mut app); + let id = host::dialog_id(&app); + assert_eq!(host::read(&app, id, |f| f.text("swatch").map(str::to_owned)), Some("Ink".into()), "process swatches are not offered"); + host::set(&app, id, "scheme", json!("tint")); + host::set(&app, id, "min", json!(30)); + host::set(&app, id, "max", json!(30)); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + let Paint::Solid { swatch, tint, .. } = fill(&app, a) else { panic!("not a solid fill") }; + assert_eq!((swatch.as_deref(), tint), (Some("Ink"), 0.3)); +} diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index e58443e259..a333d16f83 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -107,6 +107,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option typetools::open, color::legend::COMMAND => color::legend::open, color::nearest::COMMAND => color::nearest::open, + color::random_fill::COMMAND => color::random_fill::open, select::COMMAND => select::open, _ => return super::arrange::open(app, id), }; diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index 679a2e2e34..c0d1c572f2 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -87,6 +87,13 @@ fn select_two_rects(app: &mut VectorcraftApp) { app.run("select.all", json!({})).unwrap(); } +/// Two filled rectangles, both selected. +fn two_rects_filled() -> VectorcraftApp { + let mut app = two_rects(); + app.run("paint.setFill", json!({"color": "#336699"})).unwrap(); + app +} + fn two_drawings() -> VectorcraftApp { let mut app = two_rects(); app.run("file.new", json!({"width": 700, "height": 500})).unwrap(); @@ -222,6 +229,20 @@ fn rows() -> Vec { assert!(label.contains("#123456") && label.contains("C="), "{label}"); }, }, + Row { + group: "Color Effects", + label: "Randomize Fill Colors…", + setup: two_rects_filled, + refused: || vec![("scheme", json!("gray")), ("min", json!(80)), ("max", json!(20))], + values: || vec![("min", json!(40)), ("max", json!(60))], + check: |app| { + for i in 0..2 { + let fill = app.session.doc().unwrap().doc.layers[0].children().unwrap()[i].appearance.fill_paint(); + let Some(vectorcraft_color::Color::Gray { k }) = fill.color() else { panic!("not a gray: {fill:?}") }; + assert!((0.4..=0.6).contains(&k), "{k}"); + } + }, + }, ] } diff --git a/docs/mcp.md b/docs/mcp.md index d698534089..760c117e21 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17264,6 +17264,31 @@ on the object or on one of its fills or strokes; a group carrying one is selecte `grayImages` (images whose pixels are RGB, CMYK, or grayscale or 1-bit, read from the image's header). It returns the `count` selected. +`addon.color.randomFill {scheme?, swatch?, min?, max?, seed?, ids?}` (Object › Plug-ins › Color Effects › Randomize +Fill Colors…) gives each selected filled path and compound path, and each one inside the selected groups and clipping +groups, a top fill color of its own, picked at random and evenly, as one undo step (none when no fill changes): + +| `scheme` | Each fill becomes | +|---|---| +| `color` (the default) | A color with red, green and blue each at random, in the document's color mode | +| `tint` | A tint of `swatch`, a global or spot color swatch, linked to it, from `min` to `max` percent | +| `gray` | A gray from `min` to `max` percent black | + +`min` and `max` are 0 to 100 (0 and 100 when left out) and go with `tint` and `gray` only; `swatch` goes with `tint` +only and is needed there (a tint swatch gives tints of its base). The same `seed` (a whole number, 0 when left out), +objects and settings give the same colors. Paths and compound paths with no fill, clipping paths (a compound path that +clips included), hidden and locked objects and the objects in hidden or locked groups and layers, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill is replaced by +the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them +for its next redraw, so after the redraw every mark of the series has that one color. It returns the +`count` of objects whose fill changed. An unknown scheme, `min` or `max` with `color`, `swatch` without `tint`, a +percent outside 0 to 100, `min` above `max`, a missing or process swatch and a seed that is not a whole number are +errors, and the document is left as it was. The dialog's seed starts new whenever the document has changed, and its +Swatch choice lists the document's global and spot swatches. + +```json +{"name":"run_command","arguments":{"command":"addon.color.randomFill","params":{"scheme":"tint","swatch":"Ink","min":20,"max":80,"seed":7}}} +``` + ### Selection Tools Selection Tools is a built-in add-on: its commands are `addon.select.*`, and in the desktop app it lives in Object › diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 032041c2a1..7e33bb042f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3126,6 +3126,11 @@ tints, curves, multiplied inks, skip spot), `duotone_*` and `cmd::addons::color: params and RGB documents refused), and `the_duotone_dialog_has_a_row_per_tone_and_the_curve_of_one` and `print_ink_fixes_opens_its_options_and_runs_on_ok` in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Color Effects add-on. + +## Color Effects add-on: Randomize Fill Colors (2026-11-29) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Color Effects › Randomize Fill Colors… gives each selected filled path and compound path, and each one inside the selected groups and clipping groups, its own top fill color, picked at random and evenly: any color in the document's color mode, a linked tint of a global or spot swatch, or a gray, the tints and grays between a minimum and a maximum percent. A seed repeats a result exactly, and the dialog starts with a new one whenever the document has changed. Paths without a fill, clipping paths, hidden and locked objects, type, images, symbol instances, blends and envelopes keep their fills. One undo step, none when no fill changes; bad params are refused without a change. Tests: `cmd::addons::color::random_fill::tests` in `vectorcraft-engine` (each scheme and its range, the seed, groups, compound paths and clipping groups entered, unfilled, hidden and locked objects left alone, CMYK documents, one undo step or none, bad params refused), `addons::color::random_fill::tests` and the add-on dialog family test in `vectorcraft-ui-egui` (typed values preview, OK and Cancel, the Swatch choice), and `command_sweep`. Commands: `docs/mcp.md` › Color Effects add-on. + ## Arrange Tools add-on (2026-10-31) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools: Arrange in diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 453bda832d..a0d89dec66 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -595,6 +595,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Artwork Cleanup add-on text tools (VectorCraft addition): the panel's Text row, which the panel can hide, and Object › Plug-ins › Artwork Cleanup set the alignment of point type keeping its place, break type into lines (Shift-click: paragraphs), words or glyphs, split type at the cursor, reset a text transform (Alt-click: and its horizontal scale), combine point type, remove line or paragraph breaks and replace missing fonts, each one undo step | done | `addon.cleanup.*` text commands, `crates/ui-egui/src/addons/cleanup.rs` and its tests; a VectorCraft addition, so it is not scored | | Color Effects add-on (VectorCraft addition): live Exposure, Desaturate and Invert Colors in Effect › Color Effects and Object › Plug-ins › Color Effects; its panel picks a colour adjustment and its values and adds it as a live effect or applies it as a filter, into the colours, as one undo step; Select by Color Kind selects the objects that use spot colours, carry colour effects, or are RGB, CMYK or grayscale images; Vector Halftone draws an object as halftone dots live (the dots Object › Vector Halftone makes), which Expand Appearance and the exporters write as paths; Duotone prints each colour's tone with one to four inks (a tint of a spot tone's swatch, or the CMYK mix of several), live or as a filter, its dialog a row per tone and the picked tone's curve; Print Ink Fixes (a CMYK document's ink limit, white overprint removed, black overprint set) opens its options from the submenu and the panel's Inks | done | `addon.color.*`, `crates/ui-egui/src/addons/color.rs` and its tests; not a feature of the reference app, so it is not scored | | Color Effects add-on (VectorCraft addition): Object › Plug-ins › Color Effects › Find Nearest Swatch… picks a Library (Document Swatches, a built-in library, or a library or colour book the user saved or loaded) and Fill and Stroke, lists each colour of the selection with its three closest swatches (chip, name, ΔE 2000), and Apply gives each colour its nearest swatch (global and spot swatches linked; a library's swatches added to the document first), one undo step | done | #4923; `addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, `crates/engine/src/cmd/addons/color/nearest.rs`, `crates/ui-egui/src/addons/color/nearest.rs` and their tests; not a feature of the reference app, so it is not scored | +| Color Effects add-on (VectorCraft addition): Object › Plug-ins › Color Effects › Randomize Fill Colors… picks Colors (Any Color, Tints of a Swatch or Grays), a Swatch among the document's global and spot swatches, Minimum and Maximum (%) and a Seed, with Preview, and gives each selected filled path and compound path, inside groups too, its own fill color at random, one undo step | done | `addon.color.randomFill`, `crates/engine/src/cmd/addons/color/random_fill.rs`, `crates/ui-egui/src/addons/color/random_fill.rs` and their tests; a VectorCraft addition, so it is not scored | | Selection Tools add-on (VectorCraft addition): Object › Plug-ins › Selection Tools › Select by Artboards… lists every artboard (number, name, width × height in the document's units), filters them by name, chooses several (click, Shift-click for a range, Cmd/Ctrl-click to toggle; Select All / None act on the rows shown; a count of those chosen), fits a row's artboard in the window on double-click and makes it active, and on OK selects the objects overlapping, fully inside or fully outside the chosen artboards (Overlapping is All on Active Artboard's test) | done | #5525, #5548, #5549; `addon.select.byArtboards`, `crates/engine/src/cmd/addons/select.rs`, `crates/ui-egui/src/addons/select.rs` and their tests; not a feature of the reference app | | Selection Tools add-on (VectorCraft addition): Select Linked, Select Embedded, Select Missing and Select Modified in Object › Plug-ins › Selection Tools and the Links panel menu (off when no image has that status; Shift adds to the selection) select the images and placed documents with that link status, leaving out hidden, locked, template-layer and outside-isolation ones, which the status bar counts (e.g. "Selected 9 missing images; 3 more are hidden or locked"); Select by Link Status… lists them with name, status and format, searches by name, filters by status, picks with checkboxes and All / None, and selects with Zoom to Selection on by default | done | #5526; `addon.select.byLinkStatus`, `crates/engine/src/cmd/addons/select.rs`, `crates/ui-egui/src/addons/select/link_status.rs` and their tests; not a feature of the reference app | | Style panels: a double-click on a user character style's row opens its Character Style Options, and on a paragraph style's row opens the same Paragraph Style Options as the panel menu, with General, Basic Paragraph Formats, Tabs, Composition, Hyphenation, Justification and East Asian Composition Settings; the Character Style Options dialog keeps a fixed width, its sections scrolling when the window is shorter so OK and Cancel stay on screen | done | `ui.charStyleOptions`, `ui.paraStyleOptions` (`paraStyle.edit`); `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options`, `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`, `dialogs::para_style_options::tests::every_section_draws_its_fields`, `dialogs::para_style_options::tests::tabs_section_edits_the_style_stops` | From f94380622b405d3e4c40e934e24f2ca6fd3c6cb0 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Sun, 29 Nov 2026 21:07:31 +0530 Subject: [PATCH 24/72] Open .ai files with many made text objects through their layers (#9176) The reported file has 2106 text objects; its text document makes the type of all but 5. The import still counted every text object against each of the page's 2049 text objects (4.3 million pairs, past MAX_PAIRS), so it fell back to the PDF part, which has no groups or names to carry locks. Only the text objects whose type isn't made are matched with the page's words. The made ones are weighed only by where they lie, a box against a box, so they get their own limit, MAX_PLACE_PAIRS (4 x MAX_PAIRS). The reported file now opens through its layers with its 20 locked objects locked. The fallback's lock snapshot is now read only when the PDF part is used, and only when the layers could be read. The regression builds its own editing data and PDF part with the reported file's structure; nothing of the reported file is committed. --- crates/eps/src/import/native/build.rs | 10 ++++--- crates/eps/src/import/native/layers.rs | 16 ++++++---- crates/eps/src/import/native/slots.rs | 5 ++++ crates/eps/src/import/tests_native.rs | 41 ++++++++++++++++++++++++++ 4 files changed, 62 insertions(+), 10 deletions(-) diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 2cba146548..81c1181659 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -4,8 +4,8 @@ use super::compare::{ }; use super::plan::{made_only, make_slots, plan, readable_all}; use super::slots::{ - ART_LEFT_OUT, Content, DREW_DIFFERENTLY, Filled, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT, - collect_slots, extent, few, fill_slots, letters, text_objects, words, + ART_LEFT_OUT, Content, DREW_DIFFERENTLY, Filled, MAX_PAIRS, MAX_PLACE_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, + TYPE_LEFT_OUT, collect_slots, extent, few, fill_slots, letters, text_objects, words, }; use super::{ Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, VariableKind, Vec2, ai, @@ -1487,9 +1487,11 @@ fn slot_content( } // The page's type is matched with every text object whose type isn't made, and weighed against // where every made one draws: that has its limits (the slots of type that looks draw are within - // them, see `build_from`). + // them, see `build_from`). A file whose text document makes all but a few text objects is + // matched only with those few (#9176). let open = infos.iter().zip(&made).filter(|(i, m)| i.look.is_none() && m.is_none()).count(); - if open > MAX_SLOTS || infos.len().saturating_mul(pages[0].len()) > MAX_PAIRS { + let shown = pages[0].len(); + if open > MAX_SLOTS || open.saturating_mul(shown) > MAX_PAIRS || infos.len().saturating_mul(shown) > MAX_PLACE_PAIRS { return Err("it has too many text objects".into()); } let mut content = plan(infos, stories, made, template, to_doc, pages, notes); diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index 6a123242fd..21ab411985 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -172,17 +172,19 @@ pub fn layered_ai_from( } // The PDF part, its pages placed and named as the editing data's artboards are, when the // layers can't be used (`why`). - let structure = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)); - let private_layers: Vec = - structure.as_ref().ok().map(|s| s.doc.layers.iter().map(|l| LockTree::from_node(l)).collect()).unwrap_or_default(); - let from_pdf_part = |mut visible: Document, mut warnings: Vec, why: &str| { + let from_pdf_part = |mut visible: Document, mut warnings: Vec, why: &str, layers_read: bool| { let mut read = ai::Names::new(names); let mut board_names = ai::Names::new(names); let (boards, active) = ai::artboards(&data, &mut board_names); if place_pages(&boards, active, &mut visible, unit) { read.absorb(board_names); } - apply_private_layer_locks(&mut visible.layers, &private_layers); + // The editing data's locks, read again only here (and only when its layers could be read): + // the layers read below are spent on the editable document, which most files open as. + if let Some(layers) = layers_read.then(|| ai::read_over_page(&data, false, names).ok()).flatten() { + let private_layers: Vec = layers.doc.layers.iter().map(|l| LockTree::from_node(l)).collect(); + apply_private_layer_locks(&mut visible.layers, &private_layers); + } let have = visible.patterns.len(); let own_palette = use_palette(&data, &mut visible, &mut read); use_brushes(&data, &mut visible, have, &mut warnings, &mut read); @@ -196,6 +198,8 @@ pub fn layered_ai_from( // The envelopes of type the page doesn't hold against layers that don't draw as it, and how many // envelopes of type the layers had. let (mut free, mut count) = (None, 0); + let structure = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)); + let layers_read = structure.is_ok(); let built = structure.and_then(|structure| { count = structure.warped_type.envelope_count(); build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text) @@ -227,7 +231,7 @@ pub fn layered_ai_from( all.extend(notes.into_iter().filter(|n| !all.contains(n)).collect::>()); (done, all, true) } - Err(why) => from_pdf_part(visible, warnings, &why), + Err(why) => from_pdf_part(visible, warnings, &why, layers_read), } } diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index eb8959c9d4..f285cf4028 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -50,6 +50,11 @@ pub(crate) const MAX_TEXT: usize = 16 << 20; /// kept as outlines and a node of the page's type. pub(super) const MAX_PAIRS: usize = 4_000_000; +/// Most pairs of a text object whose type is made and a piece of the page's type weighed only by +/// where each lies (a box against a box, far cheaper than matching the page's type with a text +/// object's words, which [`MAX_PAIRS`] limits). +pub(super) const MAX_PLACE_PAIRS: usize = 4 * MAX_PAIRS; + /// `names` for a note: the first few, and how many more. pub(super) fn few(names: BTreeSet) -> String { const SHOWN: usize = 5; diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index ca7844d69f..b94b4aa7b1 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8599,3 +8599,44 @@ fn ai_duplicate_visible_name_does_not_lock_multiple_from_single_private_node() { assert!(!r1.locked, "ambiguous duplicate visible name does not receive private lock"); assert!(!r2.locked, "second duplicate visible name remains unlocked"); } + +/// #9176: a file with more text objects than the page's type can be matched with each, all but one +/// of them made from its text document, opens with its layers, and what is locked in it stays +/// locked. Only the one text object whose type isn't made is matched with the page's type; the made +/// ones are weighed by where they lie. (Our own minimized copy of the reported file's structure: +/// about two thousand text objects whose type the text document makes, a few it can't, and as many +/// pieces of type on the page, with locked groups.) +#[test] +fn a_file_with_many_made_text_objects_and_one_unread_keeps_its_layers_and_locks() { + // Every text object against every piece of the page's type is past `MAX_PAIRS` (four million). + let many = 2050; + let doc = + last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Odd\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0)])); + let locked_group = format!("1 A\nu\n{}\nU\n0 A\n", square(10, 10)); + let art = native_with_text(&layer("Map", true, &(locked_group + &text_object(0).repeat(many) + &text_object(1))), &doc); + // The PDF part: the square, the made type where the text document puts it, once per text object, + // and as many small pieces of type apart from one another, which the one text object whose type + // isn't made takes. + let mut page = pdf_part(10.0, 86.0); + let layer_id = page.layers[0].id; + let put = |page: &mut Document, at: (f64, f64), text: &str, size: f64| { + let style = vectorcraft_doc::CharStyle { size, ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(at.0, at.1), text, style); + let id = page.alloc_id(); + let end = page.layers[0].children().map_or(0, |c| c.len()); + page.insert(Some(layer_id), end, Node::new(id, NodeKind::Text(Box::new(text)))).unwrap(); + }; + for _ in 0..many { + put(&mut page, (58.5, 38.5), "Hi there", 14.0); + } + for k in 0..many { + // Down each column, so that no two pieces painted one after the other are on one line. + put(&mut page, (1.0 + (k / 46) as f64 * 2.1, 1.0 + (k % 46) as f64 * 2.1), "o", 1.0); + } + let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{w:?}"); + assert_eq!(names(&d), ["Map"], "{w:?}"); + let group = d.layers[0].children().and_then(|c| c.iter().find(|n| matches!(n.kind, NodeKind::Group { .. }))); + assert!(group.is_some_and(|g| g.locked), "the group locked in the file stays locked: {w:?}"); + assert!(all_texts(&d).iter().filter(|t| *t == "Hi there").count() >= many, "{w:?}"); +} From 2c807a0e9d4fd4d0126fe46bf29b5939eddb4c16 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 10:45:46 -0800 Subject: [PATCH 25/72] Color Effects: Randomize Fill Colors leaves art on a locked artboard alone Objects named in `ids` skipped the locked-artboard filter that the selection applies, so the command could recolor art on a locked artboard. The command now skips every target the locked artboards hold, checked once per run with `Document::locked_artboards`. New art made on a locked artboard that is still selected takes a color, as with other commands. The params text, docs/mcp.md and the ROADMAP entry state the rule. --- ROADMAP.md | 2 +- crates/engine/src/cmd/addons/color.rs | 2 +- crates/engine/src/cmd/addons/color/random_fill.rs | 6 ++++-- .../engine/src/cmd/addons/color/random_fill/tests.rs | 12 ++++++++++++ docs/mcp.md | 2 +- 5 files changed, 19 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 8e908b8e72..e00dedaaa6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -160,7 +160,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923). -- 2026-11-29: Randomize Fill Colors joins the Color Effects add-on (Object › Plug-ins › Color Effects): each selected filled path and compound path, inside groups too, gets a fill color of its own at random: any color, tints of a global or spot swatch, or grays between a minimum and a maximum percent, with a seed that repeats the result and Preview, as one undo step (`addon.color.randomFill`). +- 2026-11-29: Randomize Fill Colors joins the Color Effects add-on (Object › Plug-ins › Color Effects): each selected filled path and compound path, inside groups too, gets a fill color of its own at random: any color, tints of a global or spot swatch, or grays between a minimum and a maximum percent, with a seed that repeats the result and Preview, as one undo step (`addon.color.randomFill`); art on a locked artboard keeps its fill (also when `ids` names it), except new art made there while it is still selected. - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 8be52f6b8f..c991d75389 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Randomize Fill Colors", ["Object", "Plug-ins", "Color Effects"], None, - "{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors), ids?: [id…] (default: the selection)} give each selected filled path and compound path, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Paths and compound paths with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers), type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}", + "{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors), ids?: [id…] (default: the selection)} give each selected filled path and compound path, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Paths and compound paths with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}", has_selection, random_fill::run ), diff --git a/crates/engine/src/cmd/addons/color/random_fill.rs b/crates/engine/src/cmd/addons/color/random_fill.rs index dbab9cd4a2..f8ac3967b3 100644 --- a/crates/engine/src/cmd/addons/color/random_fill.rs +++ b/crates/engine/src/cmd/addons/color/random_fill.rs @@ -108,20 +108,22 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result { let count = edit_if_changed(s, "Randomize Fill Colors", |before, d| { // A graph's series group stands for its marks, as for `paint.setFill`. let roots = paint_targets(before, &ids); + // Art on a locked artboard is left as it is, as for the other commands that take `ids`. + let locks = before.locked_artboards(); let mut targets = vec![]; for id in &roots { let id = before .parent_of(*id) .filter(|parent| before.node(*parent).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))) .unwrap_or(*id); - if left_alone(before, id) { + if left_alone(before, id) || locks.holds_id(id) { continue; } let Some(n) = before.node(id) else { continue }; filled(n, &mut targets); } let mut seen = std::collections::HashSet::new(); - targets.retain(|id| seen.insert(*id)); + targets.retain(|id| seen.insert(*id) && !locks.holds_id(*id)); let count = keeping_series_paint(d, &roots, |d| { let mut count = 0; for id in &targets { diff --git a/crates/engine/src/cmd/addons/color/random_fill/tests.rs b/crates/engine/src/cmd/addons/color/random_fill/tests.rs index ca353e43d4..3253ce98ee 100644 --- a/crates/engine/src/cmd/addons/color/random_fill/tests.rs +++ b/crates/engine/src/cmd/addons/color/random_fill/tests.rs @@ -259,3 +259,15 @@ fn bad_params_are_refused() { assert_eq!(steps(&s), n); assert!(*s.doc().unwrap().doc == *before, "the document is unchanged"); } + +#[test] +fn art_on_a_locked_artboard_given_by_id_keeps_its_fill() { + let mut s = session(); + let a = rect(&mut s, 0.0); + let before = fill(&s, a); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let n = steps(&s); + assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 3})).unwrap()["count"], json!(0)); + assert_eq!(fill(&s, a), before); + assert_eq!(steps(&s), n); +} diff --git a/docs/mcp.md b/docs/mcp.md index 760c117e21..3b341caa6e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17277,7 +17277,7 @@ groups, a top fill color of its own, picked at random and evenly, as one undo st `min` and `max` are 0 to 100 (0 and 100 when left out) and go with `tint` and `gray` only; `swatch` goes with `tint` only and is needed there (a tint swatch gives tints of its base). The same `seed` (a whole number, 0 when left out), objects and settings give the same colors. Paths and compound paths with no fill, clipping paths (a compound path that -clips included), hidden and locked objects and the objects in hidden or locked groups and layers, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill is replaced by +clips included), hidden and locked objects and the objects in hidden or locked groups and layers or on a locked artboard (also when `ids` names them; new art made there while it is still selected takes a color), type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill is replaced by the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, so after the redraw every mark of the series has that one color. It returns the `count` of objects whose fill changed. An unknown scheme, `min` or `max` with `color`, `swatch` without `tint`, a From 9f6afc8403b07f6152bce456da25ca61a95d6b5a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:22:31 -0800 Subject: [PATCH 26/72] MCP: dialog params texts name the keys ui.inspect reports ui.inspect lists each open dialog with a key. The params text of these commands, and docs/mcp.md and docs/control-protocol.md, named a key that no open dialog reports: - Layer Options (ui.layerOptions, ui.newLayer): layerOptions, now ui.layerOptions. - The Layers panel's Panel Options: layersPanelOptions, now ui.layersPanelOptions. - The Navigator panel's Panel Options: navigatorPanelOptions, now ui.navigatorPanelOptions. - Document Raster Effects Settings (ui.rasterEffectsSettingsDialog): rasterEffectsSettings, now document.rasterEffectsSettings. - The PDF preset editor (ui.pdfPresetDialog): pdfPreset, now pdf-export. - Save for Web (file.saveForWeb): saveForWeb, now save-for-web. - The Actions panel's Reset Actions question (ui.actionSet.reset): resetActions, now actionsQuestion. Each command now has a test that opens the dialog and checks that its params text names the key ui.inspect lists. --- crates/mcp/src/ui_catalog.rs | 16 ++++++++-------- crates/ui-egui/src/dialogs/layer_options.rs | 16 ++++++++++++++++ .../ui-egui/src/dialogs/layers_panel_options.rs | 13 +++++++++++++ .../src/dialogs/navigator_panel_options.rs | 14 ++++++++++++++ crates/ui-egui/src/dialogs/raster_effects.rs | 14 ++++++++++++++ crates/ui-egui/src/dialogs/save_for_web/tests.rs | 15 +++++++++++++++ crates/ui-egui/src/dialogs/save_pdf/tests.rs | 14 ++++++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 16 ++++++++-------- crates/ui-egui/src/panels/actions/tests_edits.rs | 14 ++++++++++++++ docs/control-protocol.md | 8 ++++---- docs/mcp.md | 8 ++++---- 11 files changed, 124 insertions(+), 24 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 9730bd7853..abbf2d89e6 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1274,7 +1274,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layerOptions", "Options for Selection…", "", - "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog", + "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `ui.layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog", ), ( "ui.layerDelete", @@ -1292,7 +1292,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.newLayer", "New Layer Options…", "Cmd+Alt+L", - "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer", + "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `ui.layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer", ), ( "ui.newArtboard", @@ -1310,13 +1310,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layersPanelOptions", "Panel Options…", "", - "{} open the Layers panel's Panel Options: dialog `layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)", + "{} open the Layers panel's Panel Options: dialog `ui.layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)", ), ( "ui.navigatorPanelOptions", "Panel Options…", "", - "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", + "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `ui.navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", ), ( "ui.attributesPanelOptions", @@ -1645,7 +1645,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.rasterEffectsSettingsDialog", "Document Raster Effects Settings Dialog", "", - "{} open Document Raster Effects Settings (dialog `rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too", + "{} open Document Raster Effects Settings (dialog `document.rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too", ), ( "ui.effectGalleryDialog", @@ -1663,7 +1663,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.pdfPresetDialog", "PDF Preset", "", - "{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdfPreset`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets", + "{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdf-export`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets", ), ("file.openRecent11", "Open Recent File 11", "", "{}"), ("file.openRecent12", "Open Recent File 12", "", "{}"), @@ -1918,7 +1918,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.actionSet.reset", "Reset Actions", "", - "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", + "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `actionsQuestion`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", ), ( "ui.actionSet.clear", @@ -1949,7 +1949,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.saveForWeb", "Save for Web (Legacy)…", "Cmd+Alt+Shift+S", - "{} open Save for Web (dialog `saveForWeb`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}", + "{} open Save for Web (dialog `save-for-web`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}", ), ( "file.saveForWeb.browser", diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index fb0ad99911..0553775449 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -1185,4 +1185,20 @@ mod tests { ok(&mut app); assert_eq!(app.session.active().unwrap().doc.node(layer).unwrap().display_name(), "Fresh Draft"); } + + /// `ui.layerOptions` and `ui.newLayer` open the dialog whose `key` their params text names, as `ui.inspect` + /// lists it. + #[test] + fn layer_options_params_text_names_the_dialog_key_ui_inspect_lists() { + for (command, arguments) in [("ui.layerOptions", json!({})), ("ui.newLayer", json!({})), ("ui.newLayer", json!({"sublayer": true}))] { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == command).expect("registered").3; + let mut app = app(); + app.run(command, arguments).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, KEY); + assert!(doc.contains(&format!("dialog `{key}`")), "{command} opens `{key}`, which its params text does not name"); + } + } } diff --git a/crates/ui-egui/src/dialogs/layers_panel_options.rs b/crates/ui-egui/src/dialogs/layers_panel_options.rs index 290641848d..0771d6ca38 100644 --- a/crates/ui-egui/src/dialogs/layers_panel_options.rs +++ b/crates/ui-egui/src/dialogs/layers_panel_options.rs @@ -127,4 +127,17 @@ mod tests { let old: crate::UiState = serde_json::from_value(json!({"layers_panel": {"layersOnly": true}})).unwrap(); assert!(old.layers_panel.layers_only && !old.layers_panel.locate_selected, "options saved without it"); } + + /// `ui.layersPanelOptions` opens the dialog whose `key` its params text names, as `ui.inspect` lists it. + #[test] + fn panel_options_params_text_names_the_dialog_key_ui_inspect_lists() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == CMD).expect("registered").3; + let mut app = app(); + app.run(CMD, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, CMD); + assert!(doc.contains(&format!("dialog `{key}`")), "{CMD} opens `{key}`, which its params text does not name"); + } } diff --git a/crates/ui-egui/src/dialogs/navigator_panel_options.rs b/crates/ui-egui/src/dialogs/navigator_panel_options.rs index c3639dbf49..b37a541ac8 100644 --- a/crates/ui-egui/src/dialogs/navigator_panel_options.rs +++ b/crates/ui-egui/src/dialogs/navigator_panel_options.rs @@ -208,4 +208,18 @@ mod tests { let old: crate::UiState = serde_json::from_value(json!({})).unwrap(); assert_eq!(old.navigator_panel, crate::panels::navigator::PanelOptions::default(), "UI state saved without them"); } + + /// `ui.navigatorPanelOptions` without options opens the dialog whose `key` its params text names, as `ui.inspect` + /// lists it. + #[test] + fn panel_options_params_text_names_the_dialog_key_ui_inspect_lists() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == KEY).expect("registered").3; + let mut app = app(); + app.run(KEY, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, KEY); + assert!(doc.contains(&format!("dialog `{key}`")), "{KEY} opens `{key}`, which its params text does not name"); + } } diff --git a/crates/ui-egui/src/dialogs/raster_effects.rs b/crates/ui-egui/src/dialogs/raster_effects.rs index 6e7f191f8f..be61dbe02b 100644 --- a/crates/ui-egui/src/dialogs/raster_effects.rs +++ b/crates/ui-egui/src/dialogs/raster_effects.rs @@ -217,4 +217,18 @@ mod tests { assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }), "the rectangle stays a path"); assert_eq!(st.history.undo.len(), steps + 1); } + + /// `ui.rasterEffectsSettingsDialog` opens the dialog whose `key` its params text names, as `ui.inspect` lists it. + #[test] + fn settings_dialog_params_text_names_the_dialog_key_ui_inspect_lists() { + const COMMAND: &str = "ui.rasterEffectsSettingsDialog"; + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3; + let mut app = app(); + app.run(COMMAND, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, super::CMD); + assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name"); + } } diff --git a/crates/ui-egui/src/dialogs/save_for_web/tests.rs b/crates/ui-egui/src/dialogs/save_for_web/tests.rs index 6c79fb69da..1bf7819ecb 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/tests.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/tests.rs @@ -898,3 +898,18 @@ fn optimize_to_file_size_starts_at_the_size_of_the_art_as_it_is_now() { let bytes = fields(&app)["optimizeK"].as_f64().unwrap() * 1024.0; assert!(bytes >= after as f64 && bytes < after as f64 + 2.0, "{bytes} for {after}"); } + +/// `file.saveForWeb` without settings opens the dialog whose `key` its params text names, as `ui.inspect` lists it. +#[test] +fn params_text_names_the_dialog_key_ui_inspect_lists() { + const COMMAND: &str = "file.saveForWeb"; + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3; + let dir = vectorcraft_testkit::temp_dir("sfw-dialog-key"); + let (mut app, _) = app(&dir, false); + app.run(COMMAND, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, "save-for-web"); + assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name"); +} diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 091a2d5d97..1dad06f331 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -1175,3 +1175,17 @@ fn the_range_bleed_and_subset_fields_are_named() { } } } + +/// `ui.pdfPresetDialog` opens the preset editor whose `key` its params text names, as `ui.inspect` lists it. +#[test] +fn preset_editor_params_text_names_the_dialog_key_ui_inspect_lists() { + const COMMAND: &str = "ui.pdfPresetDialog"; + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3; + let (mut app, _) = app(); + app.run(COMMAND, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, PDF_KEY); + assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name"); +} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f5e6908a8a..63cf0eaa47 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1275,7 +1275,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layerOptions", "Options for Selection…", "", - "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog", + "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `ui.layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog", ), ( "ui.layerDelete", @@ -1293,7 +1293,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.newLayer", "New Layer Options…", "Cmd+Alt+L", - "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer", + "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `ui.layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer", ), ( "ui.newArtboard", @@ -1311,13 +1311,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layersPanelOptions", "Panel Options…", "", - "{} open the Layers panel's Panel Options: dialog `layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)", + "{} open the Layers panel's Panel Options: dialog `ui.layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)", ), ( "ui.navigatorPanelOptions", "Panel Options…", "", - "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", + "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `ui.navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", ), ( "ui.attributesPanelOptions", @@ -1646,7 +1646,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.rasterEffectsSettingsDialog", "Document Raster Effects Settings Dialog", "", - "{} open Document Raster Effects Settings (dialog `rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too", + "{} open Document Raster Effects Settings (dialog `document.rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too", ), ( "ui.effectGalleryDialog", @@ -1664,7 +1664,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.pdfPresetDialog", "PDF Preset", "", - "{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdfPreset`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets", + "{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdf-export`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets", ), ("file.openRecent11", "Open Recent File 11", "", "{}"), ("file.openRecent12", "Open Recent File 12", "", "{}"), @@ -1919,7 +1919,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ crate::panels::actions::RESET, "Reset Actions", "", - "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", + "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `actionsQuestion`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", ), ( crate::panels::actions::CLEAR, @@ -1950,7 +1950,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.saveForWeb", "Save for Web (Legacy)…", "Cmd+Alt+Shift+S", - "{} open Save for Web (dialog `saveForWeb`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}", + "{} open Save for Web (dialog `save-for-web`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}", ), ( "file.saveForWeb.browser", diff --git a/crates/ui-egui/src/panels/actions/tests_edits.rs b/crates/ui-egui/src/panels/actions/tests_edits.rs index 1fe2f13711..14ecbd97d3 100644 --- a/crates/ui-egui/src/panels/actions/tests_edits.rs +++ b/crates/ui-egui/src/panels/actions/tests_edits.rs @@ -1342,3 +1342,17 @@ fn insert_select_object_refuses_bad_params_and_changes_nothing() { } assert!(app.run(INSERT_SELECT_OBJECT, place(json!({"note": "x".repeat(1024)}))).is_ok(), "1,024 bytes goes in"); } + +/// The panel menu's Reset Actions asks in the dialog whose `key` the params text of [`RESET`] names, as `ui.inspect` +/// lists it. +#[test] +fn reset_params_text_names_the_question_key_ui_inspect_lists() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == RESET).expect("registered").3; + let mut app = new_app(); + edits::ask_reset(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, "actionsQuestion"); + assert!(doc.contains(&format!("dialog `{key}`")), "Reset Actions opens `{key}`, which the params text of {RESET} does not name"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index df9b36eee8..7c010b90df 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -597,7 +597,7 @@ keeps the dialog's options as a saved preset. PDF presets: `ui.pdfPresetsDialog {selected?}` opens Edit → PDF Presets (dialog `pdfPresets`, field `selected`: a preset name). Built-in presets are read-only. New… and Edit… open the preset editor, which `ui.pdfPresetDialog {name? -(a saved preset to edit) | preset? (the preset a new one starts from)}` opens too: dialog `pdfPreset`, the Save PDF +(a saved preset to edit) | preset? (the preset a new one starts from)}` opens too: dialog `pdf-export`, the Save PDF dialog's option fields plus `name` and `description`; `ui.dialog.confirm` runs `pdf.preset.save` and returns to PDF Presets (a new preset can't take a name in use). Delete, Import… and Export… are `pdf.preset.delete`, `pdf.preset.import` and `pdf.preset.export`; `ui.dialog.confirm` closes. Opening a `.vcpdfpresets` file with `app.open` @@ -754,7 +754,7 @@ the dock's tab strip while Layers shows) lists the layer commands (New Layer…, Options for Selection…, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers, Reverse Order, Template, Hide/Outline/Lock Others or Show/Preview/Unlock All Layers), Paste Remembers Layers (`layer.pasteRemembersLayers`, checked when on) and Panel Options…. Layer Options is the -`layerOptions` dialog (`ui.layerOptions {ids?}`, `ui.newLayer {sublayer?}`), Panel Options the `layersPanelOptions` +`ui.layerOptions` dialog (`ui.layerOptions {ids?}`, `ui.newLayer {sublayer?}`), Panel Options the `ui.layersPanelOptions` dialog (`ui.layersPanelOptions`), and `ui.layersExpand {ids?, open?}` opens or closes rows; see the Layers panel section of `docs/mcp.md` for the row commands (`layer.setCurrent`, `layer.highlight`, `layer.move`…). @@ -766,7 +766,7 @@ File Info: File → File Info… (`file.info` from the menu or Cmd+Alt+Shift+I; stays open. Document Raster Effects Settings: Effect → Document Raster Effects Settings… (`ui.rasterEffectsSettingsDialog` for -agents) opens the `rasterEffectsSettings` dialog. Its fields are what `document.rasterEffectsSettings` reports +agents) opens the `document.rasterEffectsSettings` dialog. Its fields are what `document.rasterEffectsSettings` reports (`resolution`, `colorModel`, `background`, `antiAlias`, `clippingMask`, `addAround` in pt, `preserveSpotColors`); `ui.dialog.confirm` runs it with them as one undo step; a bad value keeps the dialog open. Object → Rasterize… opens a `command` dialog for `object.rasterize` whose fields (`ppi`, `colorModel`, `background`, `antiAlias`, `clippingMask`, @@ -994,7 +994,7 @@ the save dialog) opens `tiffOptions`, `bmpOptions` or `tgaOptions`: the raster r rows off; RLE turns flipped rows off). `ui.dialog.set` the fields and `ui.dialog.confirm` writes the file(s) with `document.export`. -Save for Web: File → Export → Save for Web (Legacy)… (`file.saveForWeb`, Ctrl/Cmd+Alt+Shift+S) opens the `saveForWeb` +Save for Web: File → Export → Save for Web (Legacy)… (`file.saveForWeb`, Ctrl/Cmd+Alt+Shift+S) opens the `save-for-web` dialog on the remembered settings (`webExport.settings`). Its fields are the `document.exportForWeb` settings (`format`, `colors`, `reduction`, `dither`, `quality`, `colorTable`, `width`, `percent`, `output`…; set `preset` to load a preset) plus `__view` (`original`, `optimized`, `2up`, `4up`), `__zoom` (`fit` or a percentage), `__kbps` and diff --git a/docs/mcp.md b/docs/mcp.md index 7ed0eebae6..c077c8211d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4686,7 +4686,7 @@ shows no notice. ## Navigator panel options -The Navigator panel menu's Panel Options… opens the `navigatorPanelOptions` dialog (fields `color`, `solidDashes`), +The Navigator panel menu's Panel Options… opens the `ui.navigatorPanelOptions` dialog (fields `color`, `solidDashes`), and `ui.navigatorPanelOptions {color?, solidDashes?, viewArtboardContentsOnly?}` sets the options without it → `{color, solidDashes, viewArtboardContentsOnly}`; with none of the keys it opens the dialog. `color` is the color the panel's view box is drawn in: `#rrggbb` or a preset name. @@ -5855,7 +5855,7 @@ already walks Image Trace. Short agent entry points: next free number when its name is in use (`Default Actions 2`), and keeps the current set and the selection. Omitted params count as `{}`. Params of another type, another key, another `mode`, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. Reset records no undo step. The panel menu's Reset - Actions is disabled while an action records or plays; it opens a `resetActions` question (fields `message`, + Actions is disabled while an action records or plays; it opens an `actionsQuestion` question (fields `message`, `detail`, `append`): OK runs this with `replace`, Append with `append`, and `ui.dialog.cancel` changes nothing. `ui.actionSet.clear {ids?: [id]}` is Clear Actions, and returns `{cleared}`, the number of sets deleted. It deletes every set in the panel with its actions, the built-in Default Actions set included, so no set is current or @@ -7736,14 +7736,14 @@ and `layerRows`, the rows highlighted in the panel. `object.setProps` return an error when they would give either name to another path directly in the group, and a path pasted directly into the group under either name loses its name. - **Dialogs and panel state** (control channel and the app's MCP): `ui.layerOptions {ids?}` and `ui.newLayer - {sublayer?}` open Layer Options (dialog `layerOptions`: name, color, template, locked, visible, printable, preview, + {sublayer?}` open Layer Options (dialog `ui.layerOptions`: name, color, template, locked, visible, printable, preview, dimImages, dimPercent; for existing rows, unchanged approval adds no undo step; an edit is one undo step. Existing rows keep their stored names unless Name is edited or explicitly set through `ui.dialog.set`, so generated labels remain automatic. `ui.dialog.set` of `template` also sets `locked` and `dimImages`, as the checkbox does, except a Dim Images set before it; for several `ids` the dialog shows the first row's settings, and OK sends only the fields set with a control or `ui.dialog.set`; Cmd/Ctrl+Alt+L runs `ui.newLayer` for a new layer; in isolation mode `ui.newLayer` for a layer that would be outside the isolated art is an error, OK in the dialog checks again and returns the same error, - and the Layers panel's New Layer and New Sublayer are off then), `ui.layersPanelOptions` opens Panel Options (`layersPanelOptions`: + and the Layers panel's New Layer and New Sublayer are off then), `ui.layersPanelOptions` opens Panel Options (`ui.layersPanelOptions`: layersOnly, locateSelected, rowSize small|medium|large|other, otherSize, thumbLayers, thumbGroups, thumbObjects), and `ui.layersExpand {ids?, open?}` opens or closes rows as their triangles do (Alt-click: everything inside). With `locateSelected` on (Locate Selected Objects, off by default), when the last selected object changes on the canvas From 314ee3681e38396520ad27ac9b7e4b77960a145e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 12:57:12 -0800 Subject: [PATCH 27/72] Arrange Tools: Mark Bounds of Each draws corner marks or a rectangle on each selected object's bounds Object > Plug-ins > Arrange Tools > Mark Bounds of Each... runs the new command addon.arrange.markBounds. For each selected object it draws a group of four inward L-shaped corner marks (10 pt legs by default, each at most half the side it runs along) or a rectangle, with no fill and a red 1 pt stroke by default, on the object's geometric or visual bounds. Visual bounds count strokes, brush art and effects as drawn. - Clip groups are measured by their clipping path, other groups by their members together. Guides and objects without bounds, such as empty groups, are skipped; a selection with nothing to mark is an error that makes no undo step. - The marks go directly above their object, or above the outermost clip group or clipping sublayer that holds it, so the mask does not clip them. The run is one undo step and selects the marks. - Out-of-range lengths and weights, unknown styles and bounds, and bad colors are errors; defaults apply only to omitted values. At most 20000 objects are marked at once. - The dialog has Preview; Length is off unless Draw is Corner Marks. - vectorcraft-render gains drawn_bounds_with, drawn_bounds with a shared symbol cache, so a large selection measures each symbol once. Docs: docs/mcp.md, ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd/addons/arrange.rs | 9 +- crates/engine/src/cmd/addons/arrange/marks.rs | 147 ++++++++ .../src/cmd/addons/arrange/marks/tests.rs | 336 ++++++++++++++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/tests/command_sweep.rs | 4 + crates/render/src/bounds.rs | 8 +- crates/render/src/lib.rs | 4 +- crates/ui-egui/src/addons/arrange.rs | 31 +- crates/ui-egui/src/addons/arrange/tests.rs | 66 ++++ docs/mcp.md | 4 +- 11 files changed, 603 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/cmd/addons/arrange/marks.rs create mode 100644 crates/engine/src/cmd/addons/arrange/marks/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index d40c33e9e1..aa31ed21ba 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -163,6 +163,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). +- 2026-11-29: Mark Bounds of Each joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own inward corner marks, or a rectangle, on its geometric or visual bounds, stroked in the color and weight given, stacked directly above it; clip groups are measured by their clipping path. A dialog with Preview, one undo step (`addon.arrange.markBounds`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index f81d7a599a..43a3e51ada 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -5,9 +5,11 @@ //! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the //! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random //! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in -//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection -//! (a view command) are the UI's. +//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object. +//! Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a view +//! command) are the UI's. +pub mod marks; #[cfg(test)] mod tests; @@ -107,6 +109,9 @@ pub fn specs() -> Vec { sort ), ] + .into_iter() + .chain(marks::specs()) + .collect() } /// Exactly two objects are selected (Swap Objects). diff --git a/crates/engine/src/cmd/addons/arrange/marks.rs b/crates/engine/src/cmd/addons/arrange/marks.rs new file mode 100644 index 0000000000..5e59924827 --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/marks.rs @@ -0,0 +1,147 @@ +//! Mark Bounds of Each (`addon.arrange.markBounds`; Object › Plug-ins › Arrange Tools › Mark Bounds +//! of Each…): corner marks, or a rectangle, on the bounds of each selected object rather than +//! around the whole selection, stroked in a colour of their own and stacked directly above the +//! object, as one undo step. + +#[cfg(test)] +mod tests; + +use std::collections::HashMap; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes}; +use vectorcraft_render::drawn_bounds_with; + +use super::super::super::edit::selected_roots; +use super::super::super::object::choice; +use super::super::super::paint::new_color; +use super::super::super::{CommandSpec, bad, cmd, color_param, has_selection}; +use super::{LEAST, LIMIT, MAX_OBJECTS, number_in}; +use crate::{Result, Session}; + +/// The command. +pub const COMMAND: &str = "addon.arrange.markBounds"; +/// The heaviest stroke (pt) the marks take, and the lightest. +const MAX_WEIGHT: f64 = 1000.0; +const MIN_WEIGHT: f64 = 0.01; +/// A side shorter than this (pt) is no side: its marks are drawn as lines along the other one. +const FLAT: f64 = 1e-9; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.arrange.markBounds", + "Mark Bounds of Each", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: colour (\"#ff0000\"; an RGB colour takes the document's colour mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, and objects without bounds such as empty groups, get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", + has_selection, + mark_bounds + )] +} + +/// The four corners of `r`, each with the directions its legs run in (inward), the corners that +/// fall on an earlier one left out. +fn corners(r: Rect) -> Vec<(Point, f64, f64)> { + let mut out: Vec<(Point, f64, f64)> = vec![]; + for (x, y, sx, sy) in [(r.x0, r.y0, 1.0, 1.0), (r.x1, r.y0, -1.0, 1.0), (r.x1, r.y1, -1.0, -1.0), (r.x0, r.y1, 1.0, -1.0)] { + let at = Point::new(x, y); + if out.iter().all(|(p, _, _)| (p.x - at.x).abs() > FLAT || (p.y - at.y).abs() > FLAT) { + out.push((at, sx, sy)); + } + } + out +} + +/// The corner marks of `r` with legs `length` long, each at most half its side: one open path per +/// corner, a line where `r` has no width or no height. +fn corner_paths(r: Rect, length: f64) -> Vec { + let (lx, ly) = (length.min(r.width() / 2.0), length.min(r.height() / 2.0)); + corners(r) + .into_iter() + .filter_map(|(p, sx, sy)| { + let across = Point::new(p.x + sx * lx, p.y); + let down = Point::new(p.x, p.y + sy * ly); + let points = match (lx > FLAT, ly > FLAT) { + (true, true) => vec![across, p, down], + (true, false) => vec![across, p], + (false, true) => vec![p, down], + (false, false) => return None, + }; + Some(PathData::single(SubPath::polyline(&points, false))) + }) + .collect() +} + +/// Where the marks of object `id` go: directly above it, or above the outermost clip group or +/// clipping sublayer that holds it at any depth, which would otherwise clip them. A top-level layer +/// with a clipping mask holds its marks too, since nothing lies outside it. +fn anchor(d: &Document, id: NodeId) -> NodeId { + let (mut at, mut outermost) = (id, id); + while let Some(up) = d.parent_of(at) { + if d.node(up).is_some_and(|n| n.clips()) && d.parent_of(up).is_some() { + outermost = up; + } + at = up; + } + outermost +} + +fn mark_bounds(s: &mut Session, p: &Value) -> Result { + const C: &str = COMMAND; + let rectangle = choice(p, C, "style", &["corners", "rectangle"])? == Some("rectangle"); + let visual = choice(p, C, "bounds", &["geometric", "visual"])? == Some("visual"); + let length = number_in(p, "length", 10.0, (LEAST, LIMIT), C)?; + let weight = number_in(p, "weight", 1.0, (MIN_WEIGHT, MAX_WEIGHT), C)?; + let color = new_color(s, p, color_param(p, "color", C)?.unwrap_or(Color::rgb(1.0, 0.0, 0.0))); + let roots = selected_roots(s)?; + if roots.len() > MAX_OBJECTS { + return Err(bad(C, "too many objects selected (at most 20000)")); + } + let d = &s.doc()?.doc; + let symbols = d.symbol_boxes(); + let mut marked: Vec<(NodeId, Rect)> = Vec::with_capacity(roots.len()); + for id in roots { + let Some(n) = d.node(id).filter(|n| !n.is_guide()) else { continue }; + let bounds = if visual { drawn_bounds_with(&symbols, n) } else { n.geometric_bounds_with(&symbols) }; + if let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) { + marked.push((anchor(d, id), r)); + } + } + if marked.is_empty() { + return Err(bad(C, "nothing to mark: the selection has no bounds")); + } + let ap = Appearance::basic(Paint::None, Paint::solid(color), weight); + let ids = s.edit("Mark Bounds of Each", |d, sel| { + // Each anchor once, its objects' marks in stacking order from the back. + let mut lists: Vec<(NodeId, Vec)> = vec![]; + let mut at: HashMap = HashMap::new(); + let mut out = Vec::with_capacity(marked.len()); + for (anchor, r) in &marked { + let node = if rectangle { + let mut n = Node::path(d.alloc_id(), shapes::rectangle(*r), ap.clone()); + n.name = Some("Bounds".into()); + n + } else { + let children = corner_paths(*r, length).into_iter().map(|path| Arc::new(Node::path(d.alloc_id(), path, ap.clone()))).collect(); + let mut g = Node::group(d.alloc_id(), children); + g.name = Some("Corner Marks".into()); + g + }; + out.push(node.id); + let k = *at.entry(*anchor).or_insert_with(|| { + lists.push((*anchor, vec![])); + lists.len() - 1 + }); + if let Some((_, nodes)) = lists.get_mut(k) { + nodes.push(node); + } + } + d.insert_beside(lists, false)?; + sel.set(out.iter().copied()); + Ok(out) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "count": ids.len() })) +} diff --git a/crates/engine/src/cmd/addons/arrange/marks/tests.rs b/crates/engine/src/cmd/addons/arrange/marks/tests.rs new file mode 100644 index 0000000000..c00085c701 --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/marks/tests.rs @@ -0,0 +1,336 @@ +//! Mark Bounds of Each: the marks each object gets, where they go in the stacking order, how +//! groups, clip groups, strokes and guides are measured, one undo step, and bad params refused. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Node, NodeId}; +use vectorcraft_geom::Rect; + +use super::COMMAND; +use crate::Session; + +/// A new document whose new art has no stroke, so visual and geometric bounds agree. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +fn ids_of(v: &Value) -> Vec { + v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +/// The ids of the children of `parent`, in stacking order from the back. +fn children(s: &Session, parent: NodeId) -> Vec { + node(s, parent).children().unwrap().iter().map(|n| n.id).collect() +} + +fn parent(s: &Session, id: NodeId) -> NodeId { + s.doc().unwrap().doc.parent_of(id).unwrap() +} + +/// Each path of the mark `id` (a group's members, or the path itself) as its points. +fn lines(s: &Session, id: NodeId) -> Vec> { + let n = node(s, id); + let paths: Vec = match n.children() { + Some(c) => c.iter().map(|c| (**c).clone()).collect(), + None => vec![n], + }; + paths + .iter() + .map(|p| { + let path = p.path_data().unwrap(); + path.subpaths[0].anchors.iter().map(|a| ((a.p.x * 1e6).round() / 1e6, (a.p.y * 1e6).round() / 1e6)).collect() + }) + .collect() +} + +fn near(a: Rect, b: (f64, f64, f64, f64)) -> bool { + [(a.x0, b.0), (a.y0, b.1), (a.x1, b.2), (a.y1, b.3)].iter().all(|(x, y)| (x - y).abs() < 1e-6) +} + +fn marks_bounds(s: &Session, id: NodeId) -> Rect { + node(s, id).geometric_bounds().unwrap() +} + +#[test] +fn each_object_gets_inward_corner_marks_above_it_in_one_step() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 50.0); + let b = rect(&mut s, 200.0, 100.0, 40.0, 40.0); + let layer = parent(&s, a); + select(&mut s, &[a, b]); + let n = steps(&s); + let r = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + let marks = ids_of(&r); + assert_eq!((marks.len(), r["count"].as_u64()), (2, Some(2))); + // Directly above each object, not around the selection. + assert_eq!(children(&s, layer), vec![a, marks[0], b, marks[1]]); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), marks, "the marks are selected"); + assert_eq!(node(&s, marks[0]).name.as_deref(), Some("Corner Marks")); + assert_eq!( + lines(&s, marks[0]), + vec![ + vec![(10.0, 0.0), (0.0, 0.0), (0.0, 10.0)], + vec![(90.0, 0.0), (100.0, 0.0), (100.0, 10.0)], + vec![(90.0, 50.0), (100.0, 50.0), (100.0, 40.0)], + vec![(10.0, 50.0), (0.0, 50.0), (0.0, 40.0)], + ] + ); + assert!(near(marks_bounds(&s, marks[1]), (200.0, 100.0, 240.0, 140.0))); + // A red 1 pt stroke and no fill. + let group = node(&s, marks[1]); + let ap = &group.children().unwrap()[0].appearance; + assert_eq!((ap.fill_paint(), ap.stroke_paint(), ap.stroke_width()), (Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(children(&s, layer), vec![a, b]); +} + +#[test] +fn length_weight_color_and_the_rectangle_style() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 30.0, 100.0); + select(&mut s, &[a]); + let r = s.execute(COMMAND, &json!({"length": 40, "weight": 2.5, "color": "#0000ff"})).unwrap(); + let marks = ids_of(&r); + // A leg is never longer than half its side, so opposite marks do not meet. + assert_eq!(lines(&s, marks[0])[0], vec![(15.0, 0.0), (0.0, 0.0), (0.0, 40.0)]); + let group = node(&s, marks[0]); + let ap = &group.children().unwrap()[0].appearance; + assert_eq!((ap.stroke_paint(), ap.stroke_width()), (Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 2.5)); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap(); + let mark = ids_of(&r)[0]; + let rect = node(&s, mark); + assert!(rect.children().is_none() && rect.path_data().unwrap().subpaths[0].closed, "one closed path"); + assert_eq!(rect.name.as_deref(), Some("Bounds")); + assert!(near(marks_bounds(&s, mark), (0.0, 0.0, 30.0, 100.0))); +} + +#[test] +fn geometric_bounds_leave_strokes_out_and_visual_bounds_count_them() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[a]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap(); + assert!(near(marks_bounds(&s, ids_of(&r)[0]), (0.0, 0.0, 20.0, 20.0)), "{:?}", marks_bounds(&s, ids_of(&r)[0])); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap(); + assert!(near(marks_bounds(&s, ids_of(&r)[0]), (-2.0, -2.0, 22.0, 22.0)), "{:?}", marks_bounds(&s, ids_of(&r)[0])); +} + +#[test] +fn visual_bounds_enclose_a_drop_shadow_and_geometric_bounds_leave_it_out() { + let mut s = session(); + let a = rect(&mut s, 50.0, 50.0, 20.0, 20.0); + select(&mut s, &[a]); + let geometry = marks_bounds(&s, a); + let (dx, dy) = (12.0, 8.0); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null, "params": {"x": dx, "y": dy, "blur": 0}})).unwrap(); + let shadow = Rect::new(geometry.x0 + dx, geometry.y0 + dy, geometry.x1 + dx, geometry.y1 + dy); + let reach = geometry.union(shadow); + let encloses = |r: Rect| r.x0 <= reach.x0 && r.y0 <= reach.y0 && r.x1 >= reach.x1 && r.y1 >= reach.y1; + + let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "geometric"})).unwrap(); + let geometric = marks_bounds(&s, ids_of(&r)[0]); + assert!(near(geometric, (geometry.x0, geometry.y0, geometry.x1, geometry.y1))); + assert!(!encloses(geometric), "the geometric mark leaves the shadow outside"); + s.execute("edit.undo", &json!({})).unwrap(); + + let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap(); + let visual = marks_bounds(&s, ids_of(&r)[0]); + assert!(encloses(visual), "the visual mark encloses the artwork and its shadow: {visual:?}"); +} + +#[test] +fn visual_bounds_enclose_brush_art_on_paths_and_in_groups() { + for grouped in [false, true] { + let mut s = session(); + let path = NodeId(s.execute("shape.line", &json!({"x1": 50, "y1": 50, "x2": 150, "y2": 50})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[path]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 1})).unwrap(); + s.execute("brush.apply", &json!({"name": "Dots"})).unwrap(); + let target = if grouped { + s.execute("object.group", &json!({})).unwrap(); + parent(&s, path) + } else { + path + }; + select(&mut s, &[target]); + let geometry = marks_bounds(&s, path); + let d = &s.doc().unwrap().doc; + let source = d.node(target).unwrap(); + let painted = vectorcraft_render::painted_bounds(d, source).unwrap(); + let drawn = vectorcraft_render::drawn_bounds(d, source).unwrap(); + let base = vectorcraft_render::effect_bounds(&d.symbol_boxes(), source).unwrap(); + assert!(drawn.y0 < base.y0 && drawn.y1 > base.y1, "brush art reaches past the base stroke: {drawn:?}, {base:?}"); + let encloses = |r: Rect| r.x0 <= drawn.x0 && r.y0 <= drawn.y0 && r.x1 >= drawn.x1 && r.y1 >= drawn.y1; + + let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "geometric"})).unwrap(); + let geometric = marks_bounds(&s, ids_of(&r)[0]); + assert!(near(geometric, (geometry.x0, geometry.y0, geometry.x1, geometry.y1))); + assert!(!encloses(geometric), "the geometric mark leaves brush art outside"); + s.execute("edit.undo", &json!({})).unwrap(); + + let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap(); + let visual = marks_bounds(&s, ids_of(&r)[0]); + assert!(near(visual, (drawn.x0, drawn.y0, drawn.x1, drawn.y1)), "the visual mark follows the drawn bounds: {visual:?}, {drawn:?}"); + assert!(encloses(visual), "the visual mark encloses the brush art: {visual:?}, {drawn:?}"); + assert!( + visual.x0 > painted.x0 && visual.y0 > painted.y0 && visual.x1 < painted.x1 && visual.y1 < painted.y1, + "the visual mark stays inside the culling margin: {visual:?}, {painted:?}" + ); + } +} + +#[test] +fn groups_by_their_members_and_clip_groups_by_the_clipping_path() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 50.0, 30.0, 10.0, 10.0); + select(&mut s, &[a, b]); + s.execute("object.group", &json!({})).unwrap(); + let group = parent(&s, a); + let art = rect(&mut s, 100.0, 100.0, 200.0, 150.0); + let clip = rect(&mut s, 150.0, 120.0, 50.0, 40.0); + select(&mut s, &[art, clip]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let clip_group = parent(&s, art); + let layer = parent(&s, group); + select(&mut s, &[group, clip_group]); + let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap(); + let marks = ids_of(&r); + assert!(near(marks_bounds(&s, marks[0]), (0.0, 0.0, 60.0, 40.0)), "the members together"); + assert!(near(marks_bounds(&s, marks[1]), (150.0, 120.0, 200.0, 160.0)), "the clipping path"); + assert_eq!(children(&s, layer), vec![group, marks[0], clip_group, marks[1]]); + s.execute("edit.undo", &json!({})).unwrap(); + // An object inside the clip group: its marks go above the clip group, where it does not hide them. + select(&mut s, &[art]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let mark = ids_of(&r)[0]; + assert_eq!(children(&s, layer), vec![group, clip_group, mark]); + assert!(near(marks_bounds(&s, mark), (100.0, 100.0, 300.0, 250.0)), "the object's own bounds"); + s.execute("edit.undo", &json!({})).unwrap(); + // And when a plain group lies between the object and the clip group. + select(&mut s, &[art]); + s.execute("object.group", &json!({})).unwrap(); + let inner = parent(&s, art); + let clip_group = parent(&s, clip); + assert_eq!(parent(&s, inner), clip_group); + select(&mut s, &[art]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(children(&s, layer), vec![group, clip_group, ids_of(&r)[0]]); +} + +#[test] +fn marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer() { + let mut s = session(); + let top = s.doc().unwrap().current_layer().unwrap(); + let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + rect(&mut s, 20.0, 20.0, 10.0, 10.0); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("layer.clippingMask.toggle", &json!({"id": sub.0})).unwrap()["clip"].as_bool().unwrap()); + select(&mut s, &[art]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(children(&s, top), vec![sub, ids_of(&r)[0]], "above the clipping sublayer"); + + // A clipping top-level layer has nothing outside it to hold them: they go above the object. + let mut s = session(); + let top = s.doc().unwrap().current_layer().unwrap(); + let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + rect(&mut s, 20.0, 20.0, 10.0, 10.0); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("layer.clippingMask.toggle", &json!({"id": top.0})).unwrap()["clip"].as_bool().unwrap()); + select(&mut s, &[art]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let mark = ids_of(&r)[0]; + let stack = children(&s, top); + assert_eq!(stack.iter().position(|id| *id == mark), stack.iter().position(|id| *id == art).map(|i| i + 1), "{stack:?}"); +} + +#[test] +fn flat_objects_get_lines_and_guides_and_empty_groups_none() { + let mut s = session(); + let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 50, "x2": 100, "y2": 50})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[line]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + // No height: one mark at each end, along the line. + assert_eq!(lines(&s, ids_of(&r)[0]), vec![vec![(10.0, 50.0), (0.0, 50.0)], vec![(90.0, 50.0), (100.0, 50.0)]]); + s.execute("edit.undo", &json!({})).unwrap(); + + let guide = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[guide]); + s.execute("view.guides.make", &json!({})).unwrap(); + select(&mut s, &[guide]); + let layer = s.doc().unwrap().target_parent().unwrap(); + let empty = s + .edit("test", |d, _| { + let g = Node::group(d.alloc_id(), vec![]); + let id = g.id; + d.insert(layer, usize::MAX, g)?; + Ok(id) + }) + .unwrap(); + select(&mut s, &[guide, empty]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string(); + assert!(refused.contains("nothing to mark"), "{refused}"); + assert_eq!(steps(&s), n, "no undo step"); + assert!(*s.doc().unwrap().doc == *before); + // With a real object as well, only it gets marks. + let a = rect(&mut s, 100.0, 100.0, 20.0, 20.0); + select(&mut s, &[guide, empty, a]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(r["count"], 1); + assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0))); +} + +#[test] +fn bad_params_are_refused_and_it_is_off_without_a_selection() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + select(&mut s, &[a]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + for p in [ + json!({"style": "cross"}), + json!({"bounds": "preview"}), + json!({"length": 0}), + json!({"length": 1e7}), + json!({"length": "10"}), + json!({"weight": 0}), + json!({"weight": 1001}), + json!({"color": "not a color"}), + json!({"color": "#ff000080"}), + json!({"color": 3}), + ] { + assert!(s.execute(COMMAND, &p).is_err(), "{p}"); + } + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before); + s.execute("select.none", &json!({})).unwrap(); + assert!(!s.commands().into_iter().find(|c| c.id == COMMAND).unwrap().enabled); + assert!(s.execute(COMMAND, &json!({})).is_err()); +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 783f971487..ab7f1b12dc 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -6,6 +6,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.arrange.grid", "addon.arrange.groupOverlapping", + "addon.arrange.markBounds", "addon.arrange.randomizeOpacity", "addon.arrange.replace", "addon.arrange.size", diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 462641b953..007a78962a 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1009,6 +1009,10 @@ fn structured_junk() { ("addon.arrange.sort", json!({"by": "opacity", "apply": "y", "order": "descending", "ids": [u64::MAX]})), ("addon.arrange.sort", json!({"by": "x", "apply": "opacity", "distribute": true, "seed": 1e308, "ids": []})), ("addon.arrange.sort", json!({"by": "nope", "apply": null, "order": 3, "distribute": "x"})), + ("addon.arrange.markBounds", json!({"style": "rectangle", "bounds": "visual", "weight": 1000, "color": "cmyk 0 100 100 0"})), + ("addon.arrange.markBounds", json!({"length": 1e6, "weight": 0.01, "color": [0, 0, 1]})), + ("addon.arrange.markBounds", json!({"length": f64::MAX, "weight": -1, "color": "#ff000080", "style": 3})), + ("addon.arrange.markBounds", json!({"length": 1e-308, "bounds": "nope", "color": {"swatch": 1}})), ("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})), ("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})), ("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})), diff --git a/crates/render/src/bounds.rs b/crates/render/src/bounds.rs index fafb1b188f..299d6d627a 100644 --- a/crates/render/src/bounds.rs +++ b/crates/render/src/bounds.rs @@ -61,7 +61,13 @@ pub(crate) fn effect_bounds_with( /// reach of its own and its members' raster effects, measured as [`Node::visual_bounds_with`] /// measures art without effects: what Object › Rasterize makes its image over. pub fn drawn_bounds(doc: &Document, n: &Node) -> Option { - fx::painted_reach(&doc.symbol_boxes(), n) + drawn_bounds_with(&doc.symbol_boxes(), n) +} + +/// [`drawn_bounds`] with symbol instances measured by their art in `symbols` (made with +/// [`Document::symbol_boxes`]). +pub fn drawn_bounds_with(symbols: &SymbolBoxes, n: &Node) -> Option { + fx::painted_reach(symbols, n) } /// For a path or compound path whose own Rasterize effect is followed by Transform effects that diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 457c4c48c8..544438d96f 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -294,7 +294,9 @@ mod renderer; mod text_geom; mod threads; -pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage}; +pub use bounds::{ + drawn_bounds, drawn_bounds_with, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage, +}; pub use frame::FrameStats; use frame::{ ClipEntry, ClipPaintEntry, Frame, FxArtEntry, GeomEntry, PlacedEntry, PlacedKey, PtrHasher, PtrMap, SliceEntry, StrokeEntry, StrokeKey, diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index a26f5f7a28..0b3b2c1ed3 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -1,6 +1,6 @@ //! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of -//! Arrange in Grid, Replace with Top Object, Set Size of Each, Randomize Opacity and Sort Objects, -//! which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping +//! Arrange in Grid, Replace with Top Object, Set Size of Each, Randomize Opacity, Sort Objects and +//! Mark Bounds of Each, which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping //! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection. use std::borrow::Cow; @@ -26,14 +26,19 @@ const REPLACE: &str = "addon.arrange.replace"; const SIZE: &str = "addon.arrange.size"; const OPACITY: &str = "addon.arrange.randomizeOpacity"; const SORT: &str = "addon.arrange.sort"; +const MARKS: &str = "addon.arrange.markBounds"; /// Each dialog's command and heading. -const DIALOGS: [(&str, &str); 5] = [ +const DIALOGS: [(&str, &str); 6] = [ (GRID, "Arrange in Grid"), (REPLACE, "Replace with Top Object"), (SIZE, "Set Size of Each"), (OPACITY, "Randomize Opacity"), (SORT, "Sort Objects"), + (MARKS, "Mark Bounds of Each"), ]; +/// The mark lengths (pt) Mark Bounds of Each takes, and its stroke weights. +const MARK_LENGTHS: std::ops::RangeInclusive = 0.001..=1e6; +const WEIGHTS: std::ops::RangeInclusive = 0.01..=1000.0; /// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid takes. const SIZES: std::ops::RangeInclusive = 0.001..=1e6; const GAPS: std::ops::RangeInclusive = -1e6..=1e6; @@ -63,6 +68,7 @@ pub fn menu() -> Vec { cp("Group Overlapping Objects", "addon.arrange.groupOverlapping", json!({})), c("Randomize Opacity…", OPACITY), c("Sort Objects…", SORT), + c("Mark Bounds of Each…", MARKS), Sep, cp("Zoom to Selection", ZOOM, json!({})), ] @@ -73,6 +79,7 @@ static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, fou static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None }; static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None }; static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None }; +static MARKS_SPEC: Spec = Spec { command: MARKS, params: marks_params, found: None }; /// The dialog over `rows`, titled by the heading of `command`. fn dialog<'a>(command: &str, rows: Vec) -> ParamDialog<'a> { @@ -152,6 +159,22 @@ fn sort_rows() -> Vec { ] } +fn marks_rows(lengths: LengthUnits) -> Vec { + let styles = [("corners", "Corner Marks"), ("rectangle", "Rectangle")]; + let bounds = [("geometric", "Geometric Bounds"), ("visual", "Visual Bounds")]; + vec![ + choice("style", "Draw:", &styles, "corners"), + choice("bounds", "Bounds:", &bounds, "geometric"), + length("length", "Length:", 10.0, MARK_LENGTHS, lengths).enabled_when("style", "corners"), + Param::number("weight", tl!("Weight:"), 1.0, 0.25, 2).bounds(Some(*WEIGHTS.start()), Some(*WEIGHTS.end())).unit(UnitKind::Points), + Param::new("color", tl!("Color:"), ParamKind::color(Some([1.0, 0.0, 0.0]))), + ] +} + +fn marks_params(fields: &DialogFields) -> Value { + Value::Object(form::json_of(&marks_rows(POINTS), fields)) +} + fn grid_params(fields: &DialogFields) -> Value { Value::Object(form::json_of(&grid_rows(POINTS), fields)) } @@ -207,6 +230,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option (marks_rows(lengths), json!({ "style": "corners", "bounds": "geometric", "length": 10, "weight": 1, "color": "#ff0000" })), // The first selected object's size, as the command measures it (a side it lacks: the least). _ => { let (w, h) = st.selection.objects.first().and_then(|id| app.session.transform_box(&[*id])).map_or((100.0, 100.0), |b| { @@ -229,6 +253,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option super::dialogs::open(app, &SORT_SPEC, fields, |fields| dialog(SORT, sort_rows()).values(Bind::bound(fields))), + MARKS => super::dialogs::open(app, &MARKS_SPEC, fields, move |fields| dialog(MARKS, marks_rows(lengths)).values(Bind::bound(fields))), _ => super::dialogs::open(app, &SIZE_SPEC, fields, move |fields| { let either = fields.bool("widthOn").unwrap_or(true) || fields.bool("heightOn").unwrap_or(true); dialog(SIZE, size_rows(lengths)).ok_enabled(either).ok_reason(tl!("Tick Width or Height.").into()).values(Bind::bound(fields)) diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 420bfdb01d..a56791df55 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -162,3 +162,69 @@ fn zoom_to_selection_fits_the_selection_in_the_view() { assert!(!menus::enabled(&app, ZOOM)); assert!(app.run(ZOOM, json!({})).is_err()); } + +/// The objects of the first layer, from the back. +fn layer(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +/// The points of the first corner mark in the marks group `id`. +fn first_mark(app: &VectorcraftApp, id: NodeId) -> Vec<(f64, f64)> { + let doc = &app.session.doc().unwrap().doc; + let mark = &doc.node(id).unwrap().children().unwrap()[0]; + mark.path_data().unwrap().subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect() +} + +fn steps(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +#[test] +fn real_mark_bounds_edits_reach_the_preview_ok_keeps_them_and_cancel_drops_them() { + let (app, a, b) = app(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + let before = steps(&panel.app()); + click(&mut panel.app(), "Mark Bounds of Each…"); + type_number(&mut panel, "Length", "4"); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.number("length")), Some(4.0)); + // The preview: corner marks directly above each rectangle, their legs 4 pt long. + let preview = layer(&panel.app()); + assert_eq!((preview.len(), preview[0], preview[2]), (4, a, b), "{preview:?}"); + assert_eq!(first_mark(&panel.app(), preview[1]), vec![(4.0, 0.0), (0.0, 0.0), (0.0, 4.0)]); + panel.click("OK"); + panel.frame(); + { + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!(layer(&app), preview); + assert_eq!(steps(&app), before + 1, "one undo step"); + } + panel.app().run("select.set", json!({"ids": [a.0]})).unwrap(); + click(&mut panel.app(), "Mark Bounds of Each…"); + type_number(&mut panel, "Length", "2"); + assert_eq!(layer(&panel.app()).len(), 5, "the preview adds marks above a"); + panel.click("Cancel"); + panel.frame(); + let app = panel.app(); + assert_eq!(layer(&app), preview, "Cancel takes the preview away"); + assert_eq!(steps(&app), before + 1); +} + +#[test] +fn mark_bounds_sends_the_dialog_values_to_its_command() { + let (mut app, a, _) = app(); + click(&mut app, "Mark Bounds of Each…"); + let id = host::dialog_id(&app); + let opened = host::read(&app, id, |f| (f.text("style").map(str::to_owned), f.text("bounds").map(str::to_owned), f.number("weight"))); + assert_eq!(opened, (Some("corners".to_owned()), Some("geometric".to_owned()), Some(1.0))); + host::set(&app, id, "style", json!("rectangle")); + host::set(&app, id, "weight", json!(3)); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + let marks = layer(&app); + let doc = &app.session.doc().unwrap().doc; + let rect = doc.node(marks[1]).unwrap(); + assert_eq!((marks[0], rect.name.as_deref(), rect.appearance.stroke_width()), (a, Some("Bounds"), 3.0)); + assert_eq!(rect.geometric_bounds().unwrap(), vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 10.0)); +} diff --git a/docs/mcp.md b/docs/mcp.md index 7ed0eebae6..bf5a048a9a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17542,12 +17542,14 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | +| `addon.arrange.markBounds` | `style`: `corners`, `rectangle` (`corners`); `bounds`: `geometric` (strokes not counted), `visual` (strokes, brush art and effects as drawn) (`geometric`); `length` pt 0.001…1000000 (10, for `corners`); `weight` pt 0.01…1000 (1); `color` (`#ff0000`; an RGB color takes the document's color mode) | Draws marks on the bounds of each selected object (at most 20000), not around the whole selection: a group named Corner Marks of four L-shaped marks, one on each corner with its two legs running inward along the edges (each leg at most half the side it runs along), or a rectangle named Bounds. The marks have no fill and the stroke given, and go directly above their object, or above the outermost clip group or clipping sublayer that holds it. A clip group is measured by its clipping path and other groups by their members together. Guides and objects without bounds, such as empty groups, get no marks, and a selection with nothing to mark is an error that makes no step. The marks are selected. → `{ids, count}` | Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs (`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize`, `arrangeOpacity` and `arrangeSort`) whose -fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. +fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. Mark Bounds of Each… opens a dialog of the +command's parameters with Preview; Length is off unless Draw is Corner Marks. ```json {"name":"run_command","arguments":{"command":"addon.arrange.grid","params":{"columns":4,"gapX":12,"gapY":12}}} From 57631406d7e6fd1b6eb6666820d41b23126a13b3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:03:39 -0800 Subject: [PATCH 28/72] Symbols: art dropped on a symbol with Alt+Shift redefines it and stays as it was Art dragged off the canvas and released on a symbol's tile or row with Alt (Option on macOS) held redefines that symbol, and the dropped art becomes an instance of it. With Shift held as well, the panel now sends `symbol.update` with `keepArt: true`, so the art stays ordinary art in its place, as Redefine Symbol from the panel menu with Shift leaves it. The redefine is one undo step either way. Docs: docs/mcp.md (symbol.update). --- crates/ui-egui/src/panels/symbols.rs | 11 +++++++--- crates/ui-egui/src/panels/symbols/tests.rs | 25 ++++++++++++++++++++++ docs/mcp.md | 5 +++-- 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index e8dbf1a468..63edfcb53b 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -535,7 +535,7 @@ const AT_START: usize = 4; /// A click makes a symbol current and a double click edits it; a symbol drags out to the canvas, /// onto New Symbol (duplicated) or onto Delete Symbol. Art dragged off the canvas and dropped on the /// list becomes a symbol (Shift at the release keeps the art as ordinary art); dropped on a symbol -/// with Alt it redefines that symbol in one undo step. +/// with Alt it redefines that symbol in one undo step, and Alt+Shift also keeps the art. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let Some((doc, revision, uid, reverts, has_sel)) = app.session.active().map(|st| (st.doc.clone(), st.revision, st.uid, st.reverts, !st.selection.is_empty())) @@ -651,8 +651,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { && redefines(&doc, ids) { // Redefine Symbol with the dropped art, which becomes an instance of it, in one - // undo step. Alt art that cannot redefine changes nothing. - run_reported(app, "symbol.update", json!({ "name": target.name, "ids": node_ids(ids) })); + // undo step; Shift keeps the art as ordinary art, as the menu's Redefine Symbol + // does. Alt art that cannot redefine changes nothing. + let mut params = json!({ "name": target.name, "ids": node_ids(ids) }); + if mods.shift { + params["keepArt"] = json!(true); + } + run_reported(app, "symbol.update", params); } } PresetEvent::Menu { target, command, .. } => item_command(app, &target.name, &command), diff --git a/crates/ui-egui/src/panels/symbols/tests.rs b/crates/ui-egui/src/panels/symbols/tests.rs index 262f1d7cdb..23bd444373 100644 --- a/crates/ui-egui/src/panels/symbols/tests.rs +++ b/crates/ui-egui/src/panels/symbols/tests.rs @@ -1638,6 +1638,31 @@ fn alt_art_drop_on_a_symbol_redefines_that_symbol_in_one_step() { } } +/// Art released with Alt and Shift held on a symbol's tile or row, in each view, redefines that +/// symbol and stays ordinary art in its place, as Redefine Symbol with Shift leaves it, in one +/// undo step. +#[test] +fn alt_shift_art_drop_on_a_symbol_redefines_it_and_keeps_the_art() { + for view in ["thumbnail", "smallList", "largeList"] { + let (app, shape, placed) = alt_drop_doc(view); + let leaf = symbol_art(&app, "Leaf"); + let undo = undo_len(&app); + let mut p = harness(app, art_and_symbols); + p.drag("Art", "Leaf", Modifiers::ALT | Modifiers::SHIFT); + let mut app = p.app(); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "{view}: no symbol added"); + assert_eq!(undo_len(&app), undo + 1, "{view}: one undo step"); + let doc = app.session.active().unwrap().doc.clone(); + let ratio = doc.node(placed).and_then(|n| n.geometric_bounds()).map(|b| b.width() / b.height()); + assert!(ratio.is_some_and(|r| (r - 2.0).abs() < 1e-6), "{view}: Leaf is the dropped art: {ratio:?}"); + assert!(doc.node(shape).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })), "{view}: the art keeps its id as a path"); + assert_eq!(art(&app, "Leaf"), (1, 1), "{view}: the art stays ordinary art, not a Leaf instance"); + app.run("edit.undo", json!({})).unwrap(); + assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "{view}: undo restores Leaf"); + assert_eq!(art(&app, "Leaf"), (1, 1), "{view}: undo leaves the art"); + } +} + /// An Alt drop that cannot redefine the symbol under the pointer changes nothing, makes no new /// symbol and adds no undo step: art holding an instance of the symbol, which the redefine /// refuses, a layer, and art released outside the list. diff --git a/docs/mcp.md b/docs/mcp.md index d984e7b92d..0695a42dae 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5083,8 +5083,9 @@ already walks Image Trace. Short agent entry points: of it in one undo step; with `keepArt: true` the art stays ordinary art in its place, with its ids, and stays selected unless it is hidden or locked, and the result's `id` is null; a `keepArt` other than true or false is an error; art that holds an instance of the symbol (opacity masks included), directly or through the art of the symbols it holds instances of, is refused and nothing changes; the Symbols panel menu's Redefine Symbol sends `keepArt: true` when it - is chosen with Shift held, and the panel sends it with the dragged art's `ids` when art dragged - off the canvas is released on a symbol's tile or row with Alt (Option on macOS) held), + is chosen with Shift held, and the panel sends `symbol.update` with the dragged art's `ids` when art dragged + off the canvas is released on a symbol's tile or row with Alt (Option on macOS) held, with `keepArt: true` when Shift + is held too), `symbol.edit {id?, ids?, name?, x?, y?, artboard?, viewCenter?}` (symbol editing mode: the symbol's art on a temporary isolated layer, where the instance `id` shows it or centered on (x, y), by default on the center of artboard `artboard`, the active one the app passes, or in a document without artboards on `viewCenter`, the view's center the From 9693ce96aac2a7ec6caed6fdb4d89e82b14ee621 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 13:33:21 -0800 Subject: [PATCH 29/72] Arrange Tools: Group by Row puts each row of the selection in its own group Object > Plug-ins > Arrange Tools > Group by Row... (addon.arrange.groupRows) groups the selected top-level objects by the rows their visual bounds share: an object joins a row when its bounds overlap the row from top to bottom, and Group By Columns does the same from left to right. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard share a row; an object alone in its row stays as it is. Each new group takes its frontmost member's place in the stacking order, and the groups and the objects left alone stay selected. One undo step, none when no row holds two objects; an unknown direction is refused. At most 20000 objects, sorted once along the axis. Group Overlapping Objects and Group by Row share the step that builds the groups. The dialog has Group By (Rows or Columns) with Preview. Docs: docs/mcp.md, docs/ui-parity.md, docs/target-app-parity.md, ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd/addons/arrange.rs | 77 ++++++++- crates/engine/src/cmd/addons/arrange/tests.rs | 154 ++++++++++++++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/tests/command_sweep.rs | 2 + crates/ui-egui/src/addons/arrange.rs | 19 ++- crates/ui-egui/src/addons/arrange/tests.rs | 58 +++++++ docs/mcp.md | 5 +- docs/target-app-parity.md | 4 + docs/ui-parity.md | 1 + 10 files changed, 317 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c743448b07..4a869f1d36 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -164,6 +164,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). - 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-29: Group by Row joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap from top to bottom go into one group for each row (or, by column, from left to right), within their own layer or group and artboard, at the stacking place of their frontmost member; an object alone in its row stays as it is. One undo step, with a previewed dialog (`addon.arrange.groupRows`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index a25f341d1c..4274932141 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -4,7 +4,8 @@ //! Replace with Top Object puts a copy of the topmost selected object in place of each of the //! others; and Set Size of Each gives every selected object an exact width and height. Places and //! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the -//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random +//! objects whose visual bounds overlap, Group by Row groups them by the rows (or columns) their +//! visual bounds share, Randomize Opacity gives each selected object a random //! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in //! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection //! (a view command) are the UI's. @@ -98,6 +99,15 @@ pub fn specs() -> Vec { has_multi, group_overlapping ), + cmd!( + "addon.arrange.groupRows", + "Group by Row", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\")} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. An object joins a row when its visual bounds (strokes and effects as drawn; a clipping group by its mask) overlap the row's extent across it; extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row, an object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}", + has_multi, + group_rows + ), cmd!( "addon.arrange.randomizeOpacity", "Randomize Opacity", @@ -407,11 +417,74 @@ fn group_overlapping(s: &mut Session, _: &Value) -> Result { roots.iter().filter_map(|id| Some((*id, (d.parent_of(*id), effects::preview::bounds_of(d, &[*id], true)?)))).collect(); let keyed: Vec<(Option, Rect)> = items.iter().map(|(_, k)| *k).collect(); let sets: Vec> = overlapping(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect(); + group_each(s, "Group Overlapping Objects", &roots, sets) +} + +/// The rows of `items` (each a key and an extent `(start, end)` along the axis across the rows): the sets of +/// two or more (each in the order given) among items of the same key whose extents overlap, chains included. +/// Extents that only touch stay apart. Sorted by start, then by end, each item joins its key's open row when it +/// starts before that row ends, so the rows come out in order along the axis, and an extent with no length at +/// another's start stays apart from it whatever their order. +fn rows_of(items: &[(K, (f64, f64))]) -> Vec> { + let mut order: Vec = (0..items.len()).collect(); + order.sort_by(|a, b| items[*a].1.0.total_cmp(&items[*b].1.0).then(items[*a].1.1.total_cmp(&items[*b].1.1))); + let mut rows: Vec> = vec![]; + // Each key's open row: its index in `rows` and where it ends. + let mut open: HashMap = HashMap::new(); + for i in order { + let (key, (start, end)) = items[i]; + match open.get_mut(&key) { + Some((row, until)) if start < *until => { + if let Some(r) = rows.get_mut(*row) { + r.push(i); + } + *until = until.max(end); + } + _ => { + open.insert(key, (rows.len(), end)); + rows.push(vec![i]); + } + } + } + rows.retain(|r| r.len() > 1); + for r in &mut rows { + r.sort_unstable(); + } + rows +} + +fn group_rows(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.groupRows"; + let rows = choice(p, C, "direction", &["row", "column"])?.unwrap_or("row") == "row"; + let roots = selected_roots(s)?; + if roots.len() > MAX_OBJECTS { + return Err(bad(C, "too many objects selected (at most 20000)")); + } + let d = &s.doc()?.doc; + // Each object's row key (its parent and its artboard) and its extent across the rows. + type Keyed = ((Option, Option), (f64, f64)); + let items: Vec<(NodeId, Keyed)> = roots + .iter() + .filter_map(|id| { + let b = effects::preview::bounds_of(d, &[*id], true)?; + let extent = if rows { (b.y0, b.y1) } else { (b.x0, b.x1) }; + Some((*id, ((d.parent_of(*id), d.artboard_for_bounds(b)), extent))) + }) + .collect(); + let keyed: Vec<_> = items.iter().map(|(_, k)| *k).collect(); + let sets: Vec> = rows_of(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect(); + group_each(s, if rows { "Group by Row" } else { "Group by Column" }, &roots, sets) +} + +/// Put each of `sets` (two or more of the selected top-level objects `roots`, each in stacking order) into a +/// new group of its own at its frontmost member's place, as undo step `label`, and select the new groups and +/// the objects of `roots` left alone. No step when `sets` is empty. +fn group_each(s: &mut Session, label: &str, roots: &[NodeId], sets: Vec>) -> Result { if sets.is_empty() { return Ok(json!({ "groups": [], "grouped": 0 })); } let grouped: std::collections::HashSet = sets.iter().flatten().copied().collect(); - let groups = s.edit("Group Overlapping Objects", |d, sel| { + let groups = s.edit(label, |d, sel| { // Every group at once: the members behind each front one go, then each front one is // replaced by its group (one pass over the tree each, however many groups). let (mut places, mut behind, mut groups) = (vec![], vec![], vec![]); diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 498a927898..94e43a78d2 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -390,6 +390,7 @@ fn off_without_a_selection() { "addon.arrange.replace", "addon.arrange.size", "addon.arrange.groupOverlapping", + "addon.arrange.groupRows", "addon.arrange.randomizeOpacity", "addon.arrange.sort", ] { @@ -473,6 +474,159 @@ fn group_overlapping_is_off_with_one_object_and_scales_to_many() { assert!(sets.iter().all(|s| s.len() == 2 && s[1] == s[0] + 1)); } +fn layer_children(s: &Session) -> Vec { + s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +#[test] +fn group_rows_groups_each_row_and_leaves_loners() { + let mut s = session(); + // Row one: a and b (y 0 to 12). c only touches it (from y 12), alone in its row. Row two: d and e. + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let d = rect(&mut s, 0.0, 40.0, 10.0, 10.0); + let b = rect(&mut s, 20.0, 2.0, 10.0, 10.0); + let c = rect(&mut s, 40.0, 12.0, 10.0, 10.0); + let e = rect(&mut s, 20.0, 45.0, 10.0, 10.0); + select(&mut s, &[a, b, c, d, e]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!(r["grouped"], json!(4)); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 2); + assert_eq!(children(&s, groups[0]), [a, b], "the top row first, its members in stacking order"); + assert_eq!(children(&s, groups[1]), [d, e]); + // Each group where its frontmost member was: a d b c e → group(ab) at b, c, group(de) at e. + assert_eq!(layer_children(&s), [groups[0], c, groups[1]]); + let sel = &s.doc().unwrap().selection.objects; + assert!(sel.contains(&groups[0]) && sel.contains(&groups[1]) && sel.contains(&c) && sel.len() == 3, "{sel:?}"); + assert_eq!(s.doc().unwrap().history.undo.last().map(|step| step.label.as_str()), Some("Group by Row")); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(layer_children(&s), [a, d, b, c, e]); +} + +#[test] +fn group_rows_makes_columns_and_joins_rows_an_object_spans() { + let mut s = session(); + // Columns: a and b share x 0 to 15, c stands apart. + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 5.0, 50.0, 10.0, 10.0); + let c = rect(&mut s, 30.0, 0.0, 10.0, 10.0); + select(&mut s, &[a, b, c]); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": "column"})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [a, b]); + assert_eq!(s.doc().unwrap().history.undo.last().map(|step| step.label.as_str()), Some("Group by Column")); + // By row, p and q lie in two rows until r, reaching from one to the other, joins them. + let mut s = session(); + let p = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let q = rect(&mut s, 50.0, 20.0, 10.0, 10.0); + select(&mut s, &[p, q]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": "row"})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "two rows of one: no groups, no step"); + let bridge = rect(&mut s, 100.0, 5.0, 10.0, 20.0); + select(&mut s, &[p, q, bridge]); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": "row"})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [p, q, bridge]); +} + +#[test] +fn group_rows_keeps_layers_and_artboards_apart_and_measures_visual_bounds() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 500, "y": 0, "width": 200, "height": 300})).unwrap(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + // Touching a's bottom edge: a row of its own until strokes reach over the edge. + let below = rect(&mut s, 50.0, 20.0, 20.0, 20.0); + let far = rect(&mut s, 550.0, 0.0, 20.0, 20.0); + s.execute("layer.new", &json!({})).unwrap(); + let other = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, below, far, other]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "another artboard, another layer, a touching edge: no groups"); + select(&mut s, &[a, below]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + select(&mut s, &[a, below, far, other]); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [a, below], "the strokes overlap"); + let doc = &s.doc().unwrap().doc; + assert_ne!(doc.parent_of(far), Some(groups[0]), "left on its own artboard"); + assert_ne!(doc.layer_of(other), doc.layer_of(a), "left in its own layer"); +} + +#[test] +fn group_rows_measures_clipping_groups_by_their_mask() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + // A 200 tall object clipped to a 30 tall mask at y 100. + let clipped = rect(&mut s, 50.0, 0.0, 10.0, 200.0); + let mask = rect(&mut s, 40.0, 100.0, 30.0, 30.0); + select(&mut s, &[clipped, mask]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let group = s.doc().unwrap().selection.objects[0]; + let b = rect(&mut s, 100.0, 110.0, 10.0, 10.0); + select(&mut s, &[a, group, b]); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [group, b], "the mask's row, not the clipped art's"); +} + +#[test] +fn group_rows_is_off_with_one_object_skips_locked_ones_and_refuses_bad_params() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[a]); + assert!(!enabled(&s, "addon.arrange.groupRows")); + let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0); + let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b, c]); + assert!(enabled(&s, "addon.arrange.groupRows")); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": "diagonal"}), json!({"direction": 3}), json!({"direction": true})]); + select(&mut s, &[b]); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [a, c], "the locked object stays out"); + assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(s.doc().unwrap().doc.layers[0].id)); +} + +#[test] +fn group_rows_sorts_many_objects_into_rows() { + // 20000 objects in pairs up the page, the front one of each pair starting higher: each pair overlaps, + // neighboring pairs only touch. + let items: Vec<(u8, (f64, f64))> = (0..20_000) + .map(|i| { + let top = (10_000 - i / 2) as f64 * 10.0; + (0, (if i % 2 == 0 { top + 1.0 } else { top }, top + 10.0)) + }) + .collect(); + let rows = super::rows_of(&items); + assert_eq!(rows.len(), 10_000); + assert!(rows.iter().all(|r| r.len() == 2 && r[1] == r[0] + 1), "pairs, in the order given"); + assert_eq!(rows.first(), Some(&vec![19_998, 19_999]), "the top row first"); +} + +#[test] +fn group_rows_keeps_a_flat_object_on_a_row_edge_apart_in_either_order() { + // An extent with no height at the top edge of another only touches it, whichever is in front. + let flat_behind: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 0.0)), (0, (0.0, 10.0))]; + let flat_in_front: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 10.0)), (0, (0.0, 0.0))]; + assert!(super::rows_of(&flat_behind).is_empty()); + assert!(super::rows_of(&flat_in_front).is_empty(), "{:?}", super::rows_of(&flat_in_front)); + // Inside the row, it joins. + assert_eq!(super::rows_of(&[(0u8, (0.0, 10.0)), (0, (5.0, 5.0))]), vec![vec![0, 1]]); +} + fn opacity(s: &Session, id: NodeId) -> f32 { s.doc().unwrap().doc.node(id).unwrap().opacity } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 75074c6c3c..a0bd0d94b2 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -6,6 +6,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.arrange.grid", "addon.arrange.groupOverlapping", + "addon.arrange.groupRows", "addon.arrange.offset", "addon.arrange.randomizeOpacity", "addon.arrange.replace", diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index c98cd9278e..bc72152b5c 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1003,6 +1003,8 @@ fn structured_junk() { ("addon.arrange.size", json!({"width": 1e6, "height": 0.001, "reference": 8, "scaleStrokes": true})), ("addon.arrange.size", json!({"width": 0.001, "proportional": true, "reference": u64::MAX})), ("addon.arrange.groupOverlapping", json!({"ids": "x", "junk": f64::MAX})), + ("addon.arrange.groupRows", json!({"direction": "column"})), + ("addon.arrange.groupRows", json!({"direction": "diagonal", "junk": f64::MAX})), ("addon.arrange.randomizeOpacity", json!({"min": 0, "max": 100, "seed": u64::MAX})), ("addon.arrange.randomizeOpacity", json!({"min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})), ("addon.arrange.randomizeOpacity", json!({"min": 100, "max": 0, "seed": 1e308, "ids": []})), diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index ccd32bd7aa..44eb168b3b 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -1,5 +1,5 @@ //! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of -//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Randomize Opacity and Sort Objects, +//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Group by Row, Randomize Opacity and Sort Objects, //! which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping //! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection. @@ -25,14 +25,16 @@ const GRID: &str = "addon.arrange.grid"; const OFFSET: &str = "addon.arrange.offset"; const REPLACE: &str = "addon.arrange.replace"; const SIZE: &str = "addon.arrange.size"; +const ROWS: &str = "addon.arrange.groupRows"; const OPACITY: &str = "addon.arrange.randomizeOpacity"; const SORT: &str = "addon.arrange.sort"; /// Each dialog's command and heading. -const DIALOGS: [(&str, &str); 6] = [ +const DIALOGS: [(&str, &str); 7] = [ (GRID, "Arrange in Grid"), (OFFSET, "Offset Objects"), (REPLACE, "Replace with Top Object"), (SIZE, "Set Size of Each"), + (ROWS, "Group by Row"), (OPACITY, "Randomize Opacity"), (SORT, "Sort Objects"), ]; @@ -64,6 +66,7 @@ pub fn menu() -> Vec { c("Replace with Top Object…", REPLACE), c("Set Size of Each…", SIZE), cp("Group Overlapping Objects", "addon.arrange.groupOverlapping", json!({})), + c("Group by Row…", ROWS), c("Randomize Opacity…", OPACITY), c("Sort Objects…", SORT), Sep, @@ -75,6 +78,7 @@ static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None }; static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None }; static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None }; +static ROWS_SPEC: Spec = Spec { command: ROWS, params: group_rows_params, found: None }; static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None }; static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None }; @@ -149,6 +153,11 @@ fn size_rows(lengths: LengthUnits) -> Vec { ] } +fn group_rows_rows() -> Vec { + let directions = [("row", "Rows"), ("column", "Columns")]; + vec![choice("direction", "Group By:", &directions, "row")] +} + fn opacity_rows() -> Vec { vec![percent("min", "Minimum:", 30.0), percent("max", "Maximum:", 100.0), seed()] } @@ -192,6 +201,10 @@ fn size_params(fields: &DialogFields) -> Value { Value::Object(params) } +fn group_rows_params(fields: &DialogFields) -> Value { + Value::Object(form::json_of(&group_rows_rows(), fields)) +} + fn opacity_params(fields: &DialogFields) -> Value { Value::Object(form::json_of(&opacity_rows(), fields)) } @@ -217,6 +230,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option (offset_rows(lengths), json!({ "direction": "row", "gap": 10, "order": "stacking", "reverse": false })), REPLACE => (replace_rows(), json!({ "fit": "keep", "keep": false, "scaleStrokes": strokes })), + ROWS => (group_rows_rows(), json!({ "direction": "row" })), // A new seed each time the document has changed, so running it again varies the result. OPACITY => (opacity_rows(), json!({ "min": 30, "max": 100, "seed": st.revision % SEEDS })), // The random order's seed (not shown): new whenever the document has changed, so each run @@ -245,6 +259,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))), OFFSET => super::dialogs::open(app, &OFFSET_SPEC, fields, move |fields| dialog(OFFSET, offset_rows(lengths)).values(Bind::bound(fields))), REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_rows()).values(Bind::bound(fields))), + ROWS => super::dialogs::open(app, &ROWS_SPEC, fields, |fields| dialog(ROWS, group_rows_rows()).values(Bind::bound(fields))), OPACITY => super::dialogs::open(app, &OPACITY_SPEC, fields, |fields| { let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0)); dialog(OPACITY, opacity_rows()).ok_enabled(min <= max).values(Bind::bound(fields)) diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 016391d661..41686a4bd1 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -169,6 +169,64 @@ fn stacking(panel: &Harness) -> Vec { panel.app().session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() } +/// [`app`] with a third rectangle, c, in b's row and a's column; all three selected. +fn rows_app() -> (VectorcraftApp, NodeId, NodeId, NodeId) { + let (mut app, a, b) = app(); + let c = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + app.run("select.all", json!({})).unwrap(); + (app, a, b, c) +} + +fn parent(panel: &Harness, id: NodeId) -> Option { + panel.app().session.doc().unwrap().doc.parent_of(id) +} + +#[test] +fn real_group_by_row_keyboard_choice_reaches_the_preview_and_ok_groups_as_one_step() { + let (app, a, b, c) = rows_app(); + let n = steps(&app); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Group by Row…"); + panel.frame(); + let layer = panel.app().session.doc().unwrap().doc.layers[0].id; + // Rows: b and c share one, a is alone in its own. + assert_eq!(parent(&panel, b), parent(&panel, c), "the preview groups b's row"); + assert_ne!(parent(&panel, b), Some(layer)); + assert_eq!(parent(&panel, a), Some(layer)); + panel.click_role("Group By", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + panel.frame(); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.text("direction").map(str::to_owned)), Some("column".to_owned())); + // Columns: a and c share one, b is alone in its own. + assert_eq!(parent(&panel, a), parent(&panel, c), "the preview follows the keyboard choice"); + assert_ne!(parent(&panel, a), Some(layer)); + assert_eq!(parent(&panel, b), Some(layer)); + panel.click("OK"); + panel.frame(); + let group = parent(&panel, a).unwrap(); + assert_eq!(stacking(&panel), vec![b, group], "the group takes c's place, in front of b"); + assert_eq!(parent(&panel, c), Some(group)); + assert_eq!(steps(&panel.app()), n + 1, "one undo step"); + assert!(!panel.app().any_dialog_open()); +} + +#[test] +fn real_group_by_row_cancel_leaves_the_objects_ungrouped() { + let (app, a, b, c) = rows_app(); + let n = steps(&app); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Group by Row…"); + panel.frame(); + assert_eq!(stacking(&panel).len(), 2, "the preview groups b and c"); + panel.click("Cancel"); + panel.frame(); + assert_eq!(stacking(&panel), vec![a, b, c]); + assert_eq!(steps(&panel.app()), n); + assert!(!panel.app().any_dialog_open()); +} + #[test] fn real_replace_edits_reach_the_preview_and_confirmed_copies() { let (app, a, b) = app(); diff --git a/docs/mcp.md b/docs/mcp.md index d984e7b92d..1582662613 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17582,6 +17582,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | +| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row`) | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds, a clipping group's by its mask, overlap the row's extent from top to bottom (left to right). Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row; an object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | @@ -17591,11 +17592,13 @@ and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, (`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize`, `arrangeOpacity` and `arrangeSort`) whose fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. Offset Objects… opens one the same way (`ui.menuDialog {command: "addon.arrange.offset"}`), with Direction, Gap, Order -and Reverse Order. +and Reverse Order. Group by Row… opens one too (`ui.menuDialog {command: "addon.arrange.groupRows"}`), with Group By +(Rows or Columns). ```json {"name":"run_command","arguments":{"command":"addon.arrange.grid","params":{"columns":4,"gapX":12,"gapY":12}}} {"name":"run_command","arguments":{"command":"addon.arrange.offset","params":{"direction":"column","gap":6,"order":"position"}}} +{"name":"run_command","arguments":{"command":"addon.arrange.groupRows","params":{"direction":"row"}}} {"name":"run_command","arguments":{"command":"addon.arrange.replace","params":{"fit":"proportional"}}} {"name":"run_command","arguments":{"command":"addon.arrange.size","params":{"width":72,"proportional":true}}} ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ee49042298..ef8382bb36 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3162,6 +3162,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Offset Objects… chains the top-level selected objects one after another in a row (left to right) or a column (top to bottom) with a gap of −1000000 to 1000000 pt (10 by default; a negative gap overlaps them). The order is the stacking order from the back, or the position (left edges in a row, top edges in a column), and Reverse Order runs it the other way. The first object stays where it is; each later one moves only along the row or column so that it starts the gap past the end of the one before it, and keeps its place across it. Objects are measured by their visual bounds, a clipping group by its mask. One undo step; no step when nothing moves. Tests: `offset_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (row and column, both orders and reversed, a negative gap, strokes and clipping groups, no step, locked objects left out, bad params), `real_offset_*` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +## Arrange Tools add-on: Group by Row (2026-11-29) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Group by Row… puts the top-level selected objects (at most 20000) into one group for each row: an object joins a row when its visual bounds, a clipping group's by its mask, overlap the row from top to bottom. Group By Columns does the same from left to right. Extents that only touch stay apart, an object that overlaps two rows joins them, and only objects in the same layer or group and on the same artboard share a row; an object alone in its row stays as it is. Each new group takes its frontmost member's place in the stacking order, and the groups and the objects left alone stay selected. One undo step; no step when no row holds two objects. Tests: `group_rows_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (rows and loners, columns, an object spanning two rows, layers and artboards kept apart, strokes and clipping groups, locked objects left out, bad params, 20000 objects), `real_group_by_row_*` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. + ## Type Tools add-on: Text Tweaker (2026-11-03) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Type Tools › Text Tweaker… gives one character attribute (size, baseline shift, character rotation, horizontal or vertical scale, tracking, leading or stroke weight) to the selected characters letter by letter, from a start value to an end value along a straight ramp, an ease in and out, a bow, a spike or at random with a seed, while the text stays live and editable (#4924). With Block enabled, a leading ramp sets Line Gap from the first changed character instead of varying leading across the text. Values are set as the Character panel sets them, in its units and ranges, so scaled type takes the sizes shown; spaces and line breaks are skipped unless asked for, each type object gets its own ramp, the range is the Type tool's selection or all the text of the selected type objects, and the run is one undo step from a dialog with Preview. Tests: `cmd::addons::typetools::tests` in `vectorcraft-engine` (each shape, each attribute, skipped spaces, ranges, one ramp per object, seeded random values, scaled type, one undo step, bad params refused), `addons::typetools::tests` in `vectorcraft-ui-egui` (the submenu, the dialog, Preview and Cancel, OK) and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index ac20453f86..795af5c60c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -568,6 +568,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Offset Objects… chains the selected objects one after another in a Direction (Row (Left to Right) or Column (Top to Bottom)) with a Gap (negative overlaps), in an Order (Stacking Order or Position) with Reverse Order; the first stays in place and the others move only along the row or column; Preview; one undo step | done | `addon.arrange.offset`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group by Row… groups the selected objects whose visual bounds overlap from top to bottom into one group for each row, or with Group By Columns from left to right (within one layer or group and one artboard), each group at its frontmost member's stacking place; Preview; one undo step | done | `addon.arrange.groupRows`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `_YYYY-MM-DD_HH-MM.` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Document Tools add-on (VectorCraft addition): Export All Open Documents as PDF / as SVG (#4920) | done | asks for a folder, writes a copy of every open document named after it (taken names numbered, nothing replaced), documents and active tab unchanged; failures named in the status bar | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images, then a destination folder, traces each image with a preset (optionally expanded) and saves it there as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps` under its own name (taken names numbered, nothing replaced), closing each image again; the status bar counts the images traced and those that couldn't be; off on the web | done | #4921; `addon.document.batchTraceFolder`, `crates/engine/src/cmd/addons/document/batch_trace.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app | From 1f9238190c5e39d0112e0459384780184def951f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:16:10 -0800 Subject: [PATCH 30/72] Arrange Tools: Group by Row treats a -0.0 edge as 0.0 rows_of sorted extents with total_cmp, which puts -0.0 before 0.0, so an extent starting at -0.0 opened its row before a flat extent at 0.0 and the flat one joined a row it only touches. Both ends of each extent now go through + 0.0 first, with a test for a -0.0 start beside a flat 0.0 extent. --- crates/engine/src/cmd/addons/arrange.rs | 4 +++- crates/engine/src/cmd/addons/arrange/tests.rs | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 4274932141..9c64df9c1d 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -424,8 +424,10 @@ fn group_overlapping(s: &mut Session, _: &Value) -> Result { /// two or more (each in the order given) among items of the same key whose extents overlap, chains included. /// Extents that only touch stay apart. Sorted by start, then by end, each item joins its key's open row when it /// starts before that row ends, so the rows come out in order along the axis, and an extent with no length at -/// another's start stays apart from it whatever their order. +/// another's start stays apart from it whatever their order. Adding 0.0 turns -0.0 into 0.0, which +/// `total_cmp` would otherwise order first. fn rows_of(items: &[(K, (f64, f64))]) -> Vec> { + let items: Vec<(K, (f64, f64))> = items.iter().map(|(k, (start, end))| (*k, (start + 0.0, end + 0.0))).collect(); let mut order: Vec = (0..items.len()).collect(); order.sort_by(|a, b| items[*a].1.0.total_cmp(&items[*b].1.0).then(items[*a].1.1.total_cmp(&items[*b].1.1))); let mut rows: Vec> = vec![]; diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 94e43a78d2..2a586763b6 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -625,6 +625,9 @@ fn group_rows_keeps_a_flat_object_on_a_row_edge_apart_in_either_order() { assert!(super::rows_of(&flat_in_front).is_empty(), "{:?}", super::rows_of(&flat_in_front)); // Inside the row, it joins. assert_eq!(super::rows_of(&[(0u8, (0.0, 10.0)), (0, (5.0, 5.0))]), vec![vec![0, 1]]); + // A start of -0.0 is the same edge as 0.0, so the flat extent there still only touches. + let negative_zero: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 0.0)), (0, (-0.0, 10.0))]; + assert!(super::rows_of(&negative_zero).is_empty(), "{:?}", super::rows_of(&negative_zero)); } fn opacity(s: &Session, id: NodeId) -> f32 { From 62199b98b3d1b9f11cc73a554f9a3abc380e2c05 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:29:52 -0800 Subject: [PATCH 31/72] Links: Placement Options applies to the images it opened on Opened without ids (the menu, a shortcut or ui.placementOptionsDialog {}), the dialog read the selected images but sent null ids on OK, and links.placementOptions read null as the selection at that moment. Selecting another image while the dialog was open applied the options to that image, and emptying the selection made OK fail. links.placementOptions without options now returns {ids, placement}, and the dialog sends those ids on OK. OK is refused when one of them has been deleted. Callers that pass ids are unchanged, as is the check that OK edits only the drawing the dialog opened in. --- crates/engine/src/cmd/links.rs | 4 +- crates/engine/src/tests/linkspanel.rs | 5 +- .../ui-egui/src/dialogs/placement_options.rs | 6 +- crates/ui-egui/src/panels/tests_links.rs | 88 +++++++++++++++++++ docs/control-protocol.md | 2 +- 5 files changed, 99 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 65f268f2b0..142cb8a654 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -135,7 +135,7 @@ pub fn specs() -> Vec { "Placement Options", [], None, - "{ids?: [image or placed document ids] (default: the selected ones), preserve?: transforms|bounds (default)|fileDimensions|fit|fill, align?: topLeft|top|topRight|left|center (default)|right|bottomLeft|bottom|bottomRight (where the new art sits; not for bounds), clip?: false (clip it to the old bounds where it is larger)} how a file read again (links.relink, links.update) takes each image's place: transforms keeps its scale (relative to each file's 100% size), rotation and position; bounds stretches it into the old bounds; fileDimensions puts it at 100%, unrotated; fit and fill scale it proportionally to fit inside or cover the old bounds. Without options → {placement} of the first image; else one undo step → {ids, placement}", + "{ids?: [image or placed document ids] (default: the selected ones), preserve?: transforms|bounds (default)|fileDimensions|fit|fill, align?: topLeft|top|topRight|left|center (default)|right|bottomLeft|bottom|bottomRight (where the new art sits; not for bounds), clip?: false (clip it to the old bounds where it is larger)} how a file read again (links.relink, links.update) takes each image's place: transforms keeps its scale (relative to each file's 100% size), rotation and position; bounds stretches it into the old bounds; fileDimensions puts it at 100%, unrotated; fit and fill scale it proportionally to fit inside or cover the old bounds. Without options → {ids, placement} (the images read, and the placement of the first); else one undo step → {ids, placement}", has_doc, placement_options ), @@ -3230,7 +3230,7 @@ fn placement_options(s: &mut Session, p: &Value) -> Result { let first = ids.first().and_then(|id| placement_of(&doc, *id)).unwrap_or_default(); drop(doc); if preserve.is_none() && align.is_none() && clip.is_none() { - return Ok(json!({ "placement": placement_json(first) })); + return Ok(json!({ "ids": ids_json(&ids), "placement": placement_json(first) })); } let set = |o: &mut PlacementOptions| { o.preserve = preserve.unwrap_or(o.preserve); diff --git a/crates/engine/src/tests/linkspanel.rs b/crates/engine/src/tests/linkspanel.rs index cd844fa28d..26f6ca51ce 100644 --- a/crates/engine/src/tests/linkspanel.rs +++ b/crates/engine/src/tests/linkspanel.rs @@ -578,7 +578,10 @@ fn placement_options_read_set_and_round_trip() { let mut s = session(); let id = place(&mut s, &pic); run(&mut s, "select.set", json!({"ids": [id.0]})); - assert_eq!(run(&mut s, "links.placementOptions", json!({})), json!({"placement": {"preserve": "bounds", "align": "center", "clip": false}})); + assert_eq!( + run(&mut s, "links.placementOptions", json!({})), + json!({"ids": [id.0], "placement": {"preserve": "bounds", "align": "center", "clip": false}}) + ); let r = run(&mut s, "links.placementOptions", json!({"preserve": "fill", "align": "topRight", "clip": true})); assert_eq!(r, json!({"ids": [id.0], "placement": {"preserve": "fill", "align": "topRight", "clip": true}})); assert!(s.execute("links.placementOptions", &json!({"preserve": "stretch"})).is_err()); diff --git a/crates/ui-egui/src/dialogs/placement_options.rs b/crates/ui-egui/src/dialogs/placement_options.rs index d6f05d0af7..03b4cc19bd 100644 --- a/crates/ui-egui/src/dialogs/placement_options.rs +++ b/crates/ui-egui/src/dialogs/placement_options.rs @@ -3,8 +3,8 @@ //! clipped to them. //! //! Fields: `preserve` (transforms|bounds|fileDimensions|fit|fill), `align` (0-8, row by row from -//! the top left) and `clip`. OK runs `links.placementOptions` with them and `ids` (null: the -//! selected images): one undo step. +//! the top left) and `clip`. OK runs `links.placementOptions` with them and the `ids` the dialog +//! opened on (by default the images selected then): one undo step. // PLAN: assumed craft_ui paths for ParamDialog, ParamKind, Param, DialogFields, FieldValue, HostedParamDialog and Label. use craft::ui::contract::Bind; @@ -48,6 +48,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let source = (active.uid, active.reverts); let ids = p.get("ids").cloned().unwrap_or(Value::Null); let r = app.session.execute(CMD, &json!({ "ids": ids })).map_err(|e| e.to_string())?; + // The images read: OK applies to these, whatever is selected by then. + let ids = r["ids"].clone(); let placement = &r["placement"]; let align = ALIGN.iter().position(|a| Some(*a) == placement["align"].as_str()).unwrap_or(CENTRE); let mut fields = DialogFields::from_pairs([ diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index af34acbd8e..d6be853ad4 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -681,6 +681,94 @@ fn placement_options_dialog_sets_the_options() { assert_eq!(r["placement"], json!({"preserve": "fit", "align": "bottomRight", "clip": false})); } +#[test] +fn placement_options_dialog_keeps_the_links_it_opened_on_when_the_selection_changes() { + use crate::tests::picks::{answer_dialog, open_dialogs}; + let dir = Folder::new("dialog-selection"); + let (app, first, _) = app(&dir); + let mut app = crate::testing::windowed(app); + let c = dir.file("second.png", &png(60, 40)); + let second = app.run("file.place", json!({"path": c, "at": [200, 150]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("links.placementOptions", json!({"ids": [first], "preserve": "fill"})).unwrap(); + app.run("links.placementOptions", json!({"ids": [second], "preserve": "bounds"})).unwrap(); + let placement = |app: &mut VectorcraftApp, id: u64| app.run("links.placementOptions", json!({"ids": [id]})).unwrap()["placement"].clone(); + let second_before = placement(&mut app, second); + + app.run("select.set", json!({"ids": [first]})).unwrap(); + app.run("ui.placementOptionsDialog", json!({})).unwrap(); + let open = open_dialogs(&app); + assert_eq!(open.len(), 1, "the dialog is open"); + app.run("select.set", json!({"ids": [second]})).unwrap(); + answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit"))], true); + + assert_eq!(placement(&mut app, second), second_before, "the image selected after the dialog opened keeps its options"); + assert_eq!(placement(&mut app, first)["preserve"], json!("fit"), "OK applies to the image the dialog opened on"); +} + +/// Two linked images, the first with preserve `fill` and the second with `bounds`, in a window. +fn two_links(dir: &Folder) -> (VectorcraftApp, u64, u64) { + let (app, first, _) = app(dir); + let mut app = crate::testing::windowed(app); + let c = dir.file("second.png", &png(60, 40)); + let second = app.run("file.place", json!({"path": c, "at": [200, 150]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("links.placementOptions", json!({"ids": [first], "preserve": "fill"})).unwrap(); + app.run("links.placementOptions", json!({"ids": [second], "preserve": "bounds"})).unwrap(); + (app, first, second) +} + +fn preserve_of(app: &mut VectorcraftApp, id: u64) -> serde_json::Value { + app.run("links.placementOptions", json!({"ids": [id]})).unwrap()["placement"]["preserve"].clone() +} + +#[test] +fn placement_options_dialog_keeps_the_links_it_opened_on_when_the_selection_is_emptied() { + use crate::tests::picks::{answer_dialog, open_dialogs}; + let dir = Folder::new("dialog-deselect"); + let (mut app, first, second) = two_links(&dir); + app.run("select.set", json!({"ids": [first]})).unwrap(); + app.run("ui.placementOptionsDialog", json!({})).unwrap(); + let open = open_dialogs(&app); + app.run("select.set", json!({"ids": []})).unwrap(); + answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit"))], true); + assert!(open_dialogs(&app).is_empty(), "OK closes the dialog"); + assert_eq!(preserve_of(&mut app, first), json!("fit")); + assert_eq!(preserve_of(&mut app, second), json!("bounds")); +} + +#[test] +fn placement_options_dialog_changes_nothing_when_a_link_it_opened_on_is_deleted() { + use craft::ui::dialog::HeldOk; + + use crate::tests::picks::{answer_dialog, open_dialogs}; + let dir = Folder::new("dialog-deleted"); + let (mut app, first, second) = two_links(&dir); + app.run("select.set", json!({"ids": [first]})).unwrap(); + app.run("ui.placementOptionsDialog", json!({})).unwrap(); + let open = open_dialogs(&app); + app.run("edit.clear", json!({})).unwrap(); + app.run("select.set", json!({"ids": [second]})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit"))], true); + let refused = app.dialogs().unwrap().with(|h| matches!(h.held_state(open[0].id), Some(HeldOk::Refused(_)))); + assert!(refused, "OK is refused and the dialog stays open"); + assert_eq!(preserve_of(&mut app, second), json!("bounds"), "the selected image keeps its options"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "no undo step"); +} + +#[test] +fn placement_options_dialog_applies_to_the_ids_it_was_given() { + use crate::tests::picks::{answer_dialog, open_dialogs}; + let dir = Folder::new("dialog-ids"); + let (mut app, first, second) = two_links(&dir); + app.run("select.set", json!({"ids": [first]})).unwrap(); + app.run("ui.placementOptionsDialog", json!({"ids": [second]})).unwrap(); + let open = open_dialogs(&app); + assert_eq!(open.len(), 1, "the dialog is open"); + answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit"))], true); + assert_eq!(preserve_of(&mut app, second), json!("fit")); + assert_eq!(preserve_of(&mut app, first), json!("fill"), "the selected image keeps its options"); +} + #[test] fn properties_shows_the_selected_image_and_its_link_actions() { let dir = Folder::new("props"); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index df9b36eee8..25bdc8206f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -881,7 +881,7 @@ art too large at that scale) keeps the dialog open. Placement Options: the Links panel's flyout (or `ui.placementOptionsDialog {ids?}` for agents) opens the `placementOptions` dialog for the selected images (fields `ids`, `preserve`: `transforms`/`bounds`/`fileDimensions`/ `fit`/`fill`, `align`: `topLeft` … `bottomRight`, `clip`). `ui.dialog.confirm` runs `links.placementOptions` with them as -one undo step. +one undo step, on the images the dialog opened on even when the selection has changed since. Relink: the Links panel's Relink… button and flyout item (or `ui.relinkDialog {ids?}` for agents) open the `relink` dialog for the selected images and placed documents (fields `ids`, `links`: `[{name, ids}]`, one row per linked file, From aa7962ec9514a0718a5c6b3a330fe20d44704dda Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:11:19 -0800 Subject: [PATCH 32/72] Arrange Tools: Group by Row leaves masks, locked objects and blend keys alone Clipping masks, locked or hidden objects and objects outside every artboard stay in place; a selection inside a live blend and a direction of null are rejected. The docs say raster effects do not count toward row bounds. --- crates/engine/src/cmd/addons/arrange.rs | 29 ++++- crates/engine/src/cmd/addons/arrange/tests.rs | 119 +++++++++++++++++- docs/mcp.md | 2 +- 3 files changed, 143 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 9c64df9c1d..d33bcfcee5 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -18,7 +18,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::recolor::Rng; -use vectorcraft_doc::{Node, NodeId, OrientedBox}; +use vectorcraft_doc::{Node, NodeId, NodeKind, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use vectorcraft_render::effects; @@ -104,7 +104,7 @@ pub fn specs() -> Vec { "Group by Row", ["Object", "Plug-ins", "Arrange Tools"], None, - "{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\")} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. An object joins a row when its visual bounds (strokes and effects as drawn; a clipping group by its mask) overlap the row's extent across it; extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row, an object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}", + "{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\" when omitted; null is invalid)} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. An object joins a row when its visual bounds overlap the row's extent across it. Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, and clipping masks stay in place. The command rejects selections of editable objects whose parent is neither a layer nor a group, including live blend keys. An object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}", has_multi, group_rows ), @@ -457,20 +457,39 @@ fn rows_of(items: &[(K, (f64, f64))]) -> Vec Result { const C: &str = "addon.arrange.groupRows"; + if p.get("direction").is_some_and(Value::is_null) { + return Err(bad(C, "`direction` must be row or column")); + } let rows = choice(p, C, "direction", &["row", "column"])?.unwrap_or("row") == "row"; let roots = selected_roots(s)?; if roots.len() > MAX_OBJECTS { return Err(bad(C, "too many objects selected (at most 20000)")); } let d = &s.doc()?.doc; + let editable_roots: Vec<_> = { + let editable = d.editable(); + roots.iter().copied().filter(|id| editable(*id)).collect() + }; + for id in &editable_roots { + if d.parent_of(*id).and_then(|parent| d.node(parent)).is_some_and(|n| !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })) { + return Err(bad(C, "selected objects must be in a layer or group")); + } + } // Each object's row key (its parent and its artboard) and its extent across the rows. - type Keyed = ((Option, Option), (f64, f64)); - let items: Vec<(NodeId, Keyed)> = roots + type Keyed = ((Option, usize), (f64, f64)); + let items: Vec<(NodeId, Keyed)> = editable_roots .iter() .filter_map(|id| { + let parent = d.parent_of(*id); + if parent + .and_then(|parent| d.node(parent)) + .is_some_and(|n| n.clips() && n.children().and_then(|c| c.first()).is_some_and(|c| c.id == *id)) + { + return None; + } let b = effects::preview::bounds_of(d, &[*id], true)?; let extent = if rows { (b.y0, b.y1) } else { (b.x0, b.x1) }; - Some((*id, ((d.parent_of(*id), d.artboard_for_bounds(b)), extent))) + Some((*id, ((parent, d.artboard_for_bounds(b)?), extent))) }) .collect(); let keyed: Vec<_> = items.iter().map(|(_, k)| *k).collect(); diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 2a586763b6..e382c2a440 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -579,6 +579,119 @@ fn group_rows_measures_clipping_groups_by_their_mask() { assert_eq!(children(&s, groups[0]), [group, b], "the mask's row, not the clipped art's"); } +#[test] +fn group_rows_keeps_clipping_masks_first_in_groups_and_layers() { + for clipping_layer in [false, true] { + let mut s = session(); + let mask = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0); + select(&mut s, &[mask, a, b]); + let parent = if clipping_layer { + s.doc().unwrap().doc.layers[0].id + } else { + s.execute("object.group", &json!({})).unwrap(); + s.doc().unwrap().selection.objects[0] + }; + s.edit("Set clipping", |d, _| { + d.node_mut(parent).unwrap().set_clips(true); + Ok(()) + }) + .unwrap(); + select(&mut s, &[mask, a]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n)); + assert_eq!(children(&s, parent), [mask, a, b]); + select(&mut s, &[mask, a, b]); + let before = s.doc().unwrap().doc.clone(); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(r["grouped"], json!(2)); + assert_eq!(children(&s, parent), [mask, groups[0]]); + assert_eq!(children(&s, groups[0]), [a, b]); + assert!(s.doc().unwrap().selection.objects.contains(&mask)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(*s.doc().unwrap().doc == *before); + } +} + +#[test] +fn group_rows_refuses_explicitly_selected_live_blend_keys() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("object.blend.make", &json!({})).unwrap(); + let blend = s.doc().unwrap().selection.objects[0]; + let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0); + let d = rect(&mut s, 90.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({})]); + select(&mut s, &[a, b, c, d]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({})]); + assert_eq!(children(&s, blend), [a, b]); +} + +#[test] +fn group_rows_skips_explicitly_selected_locked_and_hidden_objects() { + for command in ["object.lock", "object.hide"] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0); + let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0); + select(&mut s, &[b]); + s.execute(command, &json!({})).unwrap(); + select(&mut s, &[a, b, c]); + assert!(s.doc().unwrap().selection.objects.contains(&b)); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(r["grouped"], json!(2)); + assert_eq!(children(&s, groups[0]), [a, c]); + assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(s.doc().unwrap().doc.layers[0].id)); + } +} + +#[test] +fn group_rows_leaves_objects_outside_all_artboards_ungrouped() { + for direction in ["row", "column"] { + let mut s = session(); + let a = rect(&mut s, 500.0, 500.0, 20.0, 20.0); + let b = rect(&mut s, 505.0, 505.0, 20.0, 20.0); + select(&mut s, &[a, b]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n)); + assert!(*s.doc().unwrap().doc == *before); + let c = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let d = rect(&mut s, 5.0, 5.0, 20.0, 20.0); + select(&mut s, &[a, b, c, d]); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(r["grouped"], json!(2)); + assert_eq!(children(&s, groups[0]), [c, d]); + assert_eq!(layer_children(&s), [a, b, groups[0]]); + let sel = &s.doc().unwrap().selection.objects; + assert!(sel.contains(&a) && sel.contains(&b)); + } +} + +#[test] +fn group_rows_documents_and_excludes_raster_effects_from_bounds() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[a]); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"x": 0, "y": 5, "blur": 0}})).unwrap(); + let b = rect(&mut s, 0.0, 21.0, 20.0, 20.0); + select(&mut s, &[a, b]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n)); + assert_eq!(layer_children(&s), [a, b]); + let spec = super::specs().into_iter().find(|c| c.id == "addon.arrange.groupRows").unwrap(); + assert!(spec.params.contains("excludes raster effects")); +} + #[test] fn group_rows_is_off_with_one_object_skips_locked_ones_and_refuses_bad_params() { let mut s = session(); @@ -589,7 +702,11 @@ fn group_rows_is_off_with_one_object_skips_locked_ones_and_refuses_bad_params() let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0); select(&mut s, &[a, b, c]); assert!(enabled(&s, "addon.arrange.groupRows")); - refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": "diagonal"}), json!({"direction": 3}), json!({"direction": true})]); + refuses( + &mut s, + "addon.arrange.groupRows", + &[json!({"direction": "diagonal"}), json!({"direction": 3}), json!({"direction": true}), json!({"direction": null})], + ); select(&mut s, &[b]); s.execute("object.lock", &json!({})).unwrap(); s.execute("select.all", &json!({})).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 1582662613..e01104769b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17582,7 +17582,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | -| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row`) | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds, a clipping group's by its mask, overlap the row's extent from top to bottom (left to right). Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row; an object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | +| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid) | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, and clipping masks stay in place. The command rejects selections of editable objects whose parent is neither a layer nor a group, including live blend keys. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | From 875157116bffa2b7f9d6101599c1a40568178375 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:16:11 -0800 Subject: [PATCH 33/72] Arrange Tools: Mark Bounds of Each tests the vertical leg cap and has its docs rows - A test marks a wide, short object and checks that each vertical leg stops at half the height while each horizontal leg keeps its length. - The params text and module doc spell "color" the American way. - docs/ui-parity.md gets a row and docs/target-app-parity.md a section for Mark Bounds of Each, next to Offset Objects. - The ui-egui arrange tests keep one `steps` helper; main added the same helper for Offset Objects. --- crates/engine/src/cmd/addons/arrange/marks.rs | 4 ++-- .../src/cmd/addons/arrange/marks/tests.rs | 19 ++++++++++++++++++- crates/ui-egui/src/addons/arrange/tests.rs | 4 ---- docs/target-app-parity.md | 4 ++++ docs/ui-parity.md | 1 + 5 files changed, 25 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange/marks.rs b/crates/engine/src/cmd/addons/arrange/marks.rs index 5e59924827..fc01a8730d 100644 --- a/crates/engine/src/cmd/addons/arrange/marks.rs +++ b/crates/engine/src/cmd/addons/arrange/marks.rs @@ -1,6 +1,6 @@ //! Mark Bounds of Each (`addon.arrange.markBounds`; Object › Plug-ins › Arrange Tools › Mark Bounds //! of Each…): corner marks, or a rectangle, on the bounds of each selected object rather than -//! around the whole selection, stroked in a colour of their own and stacked directly above the +//! around the whole selection, stroked in a color of their own and stacked directly above the //! object, as one undo step. #[cfg(test)] @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Mark Bounds of Each", ["Object", "Plug-ins", "Arrange Tools"], None, - "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: colour (\"#ff0000\"; an RGB colour takes the document's colour mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, and objects without bounds such as empty groups, get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", + "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, and objects without bounds such as empty groups, get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", has_selection, mark_bounds )] diff --git a/crates/engine/src/cmd/addons/arrange/marks/tests.rs b/crates/engine/src/cmd/addons/arrange/marks/tests.rs index c00085c701..dc44f47d5b 100644 --- a/crates/engine/src/cmd/addons/arrange/marks/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/marks/tests.rs @@ -111,7 +111,7 @@ fn length_weight_color_and_the_rectangle_style() { select(&mut s, &[a]); let r = s.execute(COMMAND, &json!({"length": 40, "weight": 2.5, "color": "#0000ff"})).unwrap(); let marks = ids_of(&r); - // A leg is never longer than half its side, so opposite marks do not meet. + // A leg is never longer than half its side, so opposite marks do not overlap. assert_eq!(lines(&s, marks[0])[0], vec![(15.0, 0.0), (0.0, 0.0), (0.0, 40.0)]); let group = node(&s, marks[0]); let ap = &group.children().unwrap()[0].appearance; @@ -125,6 +125,23 @@ fn length_weight_color_and_the_rectangle_style() { assert!(near(marks_bounds(&s, mark), (0.0, 0.0, 30.0, 100.0))); } +#[test] +fn a_leg_is_at_most_half_the_side_it_runs_along_vertically() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 200.0, 20.0); + select(&mut s, &[a]); + let r = s.execute(COMMAND, &json!({"length": 30})).unwrap(); + assert_eq!( + lines(&s, ids_of(&r)[0]), + vec![ + vec![(30.0, 0.0), (0.0, 0.0), (0.0, 10.0)], + vec![(170.0, 0.0), (200.0, 0.0), (200.0, 10.0)], + vec![(170.0, 20.0), (200.0, 20.0), (200.0, 10.0)], + vec![(30.0, 20.0), (0.0, 20.0), (0.0, 10.0)], + ] + ); +} + #[test] fn geometric_bounds_leave_strokes_out_and_visual_bounds_count_them() { let mut s = session(); diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 524fc290ec..7241291cab 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -282,10 +282,6 @@ fn first_mark(app: &VectorcraftApp, id: NodeId) -> Vec<(f64, f64)> { mark.path_data().unwrap().subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect() } -fn steps(app: &VectorcraftApp) -> usize { - app.session.doc().unwrap().history.undo.len() -} - #[test] fn real_mark_bounds_edits_reach_the_preview_ok_keeps_them_and_cancel_drops_them() { let (app, a, b) = app(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ee49042298..60f626d470 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3162,6 +3162,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Offset Objects… chains the top-level selected objects one after another in a row (left to right) or a column (top to bottom) with a gap of −1000000 to 1000000 pt (10 by default; a negative gap overlaps them). The order is the stacking order from the back, or the position (left edges in a row, top edges in a column), and Reverse Order runs it the other way. The first object stays where it is; each later one moves only along the row or column so that it starts the gap past the end of the one before it, and keeps its place across it. Objects are measured by their visual bounds, a clipping group by its mask. One undo step; no step when nothing moves. Tests: `offset_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (row and column, both orders and reversed, a negative gap, strokes and clipping groups, no step, locked objects left out, bad params), `real_offset_*` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +## Arrange Tools add-on: Mark Bounds of Each (2026-11-29) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Mark Bounds of Each… draws marks on each top-level selected object's bounds (at most 20000 objects), rather than around the whole selection. Draw is Corner Marks by default (four inward L-shaped marks in a group named Corner Marks), or Rectangle (one closed path named Bounds). Bounds is Geometric Bounds by default (strokes not counted), or Visual Bounds (strokes, brush art and effects as drawn). Length is 0.001 to 1000000 pt (10 by default), with each corner leg capped at half the side it runs along; Length is off in the dialog for Rectangle. Weight is 0.01 to 1000 pt (1 by default), and Color defaults to red (`#ff0000`); an RGB color takes the document's color mode. The marks have no fill and the stroke given. Each goes directly above its object, or above the outermost clip group or clipping sublayer that holds it; a clipping top-level layer keeps the marks inside it. Clip groups are measured by their clipping path, other groups by their members together. For flat objects, corner marks become lines along their nonzero side. Guides and objects without bounds, such as empty groups, are skipped; nothing to mark is an error with no undo step. The new marks become selected, in one undo step. The dialog has Preview; OK keeps the marks and Cancel removes the preview. Tests: `each_object_gets_inward_corner_marks_above_it_in_one_step`, `length_weight_color_and_the_rectangle_style`, `a_leg_is_at_most_half_the_side_it_runs_along_vertically`, `geometric_bounds_leave_strokes_out_and_visual_bounds_count_them`, `visual_bounds_enclose_a_drop_shadow_and_geometric_bounds_leave_it_out`, `visual_bounds_enclose_brush_art_on_paths_and_in_groups`, `groups_by_their_members_and_clip_groups_by_the_clipping_path`, `marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer`, `flat_objects_get_lines_and_guides_and_empty_groups_none` and `bad_params_are_refused_and_it_is_off_without_a_selection` in `cmd::addons::arrange::marks::tests` in `vectorcraft-engine`; `real_mark_bounds_edits_reach_the_preview_ok_keeps_them_and_cancel_drops_them` and `mark_bounds_sends_the_dialog_values_to_its_command` in `crates/ui-egui/src/addons/arrange/tests.rs` in `vectorcraft-ui-egui`; and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. + ## Type Tools add-on: Text Tweaker (2026-11-03) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Type Tools › Text Tweaker… gives one character attribute (size, baseline shift, character rotation, horizontal or vertical scale, tracking, leading or stroke weight) to the selected characters letter by letter, from a start value to an end value along a straight ramp, an ease in and out, a bow, a spike or at random with a seed, while the text stays live and editable (#4924). With Block enabled, a leading ramp sets Line Gap from the first changed character instead of varying leading across the text. Values are set as the Character panel sets them, in its units and ranges, so scaled type takes the sizes shown; spaces and line breaks are skipped unless asked for, each type object gets its own ramp, the range is the Type tool's selection or all the text of the selected type objects, and the run is one undo step from a dialog with Preview. Tests: `cmd::addons::typetools::tests` in `vectorcraft-engine` (each shape, each attribute, skipped spaces, ranges, one ramp per object, seeded random values, scaled type, one undo step, bad params refused), `addons::typetools::tests` in `vectorcraft-ui-egui` (the submenu, the dialog, Preview and Cancel, OK) and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index ac20453f86..283214dc79 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -568,6 +568,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Offset Objects… chains the selected objects one after another in a Direction (Row (Left to Right) or Column (Top to Bottom)) with a Gap (negative overlaps), in an Order (Stacking Order or Position) with Reverse Order; the first stays in place and the others move only along the row or column; Preview; one undo step | done | `addon.arrange.offset`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Mark Bounds of Each… draws inward Corner Marks or a Rectangle on each selected object's Geometric Bounds or Visual Bounds, with Length, Weight, Color and Preview; marks go above the object or its outermost clip group or clipping sublayer and become selected; one undo step | done | `addon.arrange.markBounds`, `crates/engine/src/cmd/addons/arrange/marks.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `_YYYY-MM-DD_HH-MM.` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Document Tools add-on (VectorCraft addition): Export All Open Documents as PDF / as SVG (#4920) | done | asks for a folder, writes a copy of every open document named after it (taken names numbered, nothing replaced), documents and active tab unchanged; failures named in the status bar | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images, then a destination folder, traces each image with a preset (optionally expanded) and saves it there as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps` under its own name (taken names numbered, nothing replaced), closing each image again; the status bar counts the images traced and those that couldn't be; off on the web | done | #4921; `addon.document.batchTraceFolder`, `crates/engine/src/cmd/addons/document/batch_trace.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app | From 59d7c483c976ac3b43fba75a0d4e2e54af6dcc5f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:20:08 -0800 Subject: [PATCH 34/72] New Document: file.new refuses artboard counts that are not whole numbers file.new rounded artboards, artboardLayout.columns and artboardLayout.rows before checking them, so a value such as 2.4 or 0.6 was quietly taken as a different count, and artboards or columns outside 1 to 1000 were clamped. A direct call now refuses a count that is not a whole number from 1 to 1000 and opens no document. A step replayed from a journal or played from the Actions panel keeps the earlier rounding, so saved steps still play. The artboardLayout error messages now list rows among the keys. --- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/newdoc.rs | 49 ++++++++------- crates/engine/src/tests/newdoc.rs | 73 ++++++++++++++++++++++ crates/engine/src/tests/script_dom.rs | 2 +- crates/ui-egui/src/dialogs/new_document.rs | 3 +- docs/mcp.md | 7 ++- 6 files changed, 111 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 4fc1b83c29..e0dee8f105 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 21f3661c89..058d0c93aa 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -299,7 +299,11 @@ impl DocSettings { } /// These settings with `p`'s changes (the params of `file.new`) → validated. - pub fn with_params(mut self, p: &Value, cmd: &str) -> Result { + pub fn with_params(self, p: &Value, cmd: &str) -> Result { + self.with_params_inner(p, cmd, false) + } + + fn with_params_inner(mut self, p: &Value, cmd: &str, replaying: bool) -> Result { if let Some(u) = p.get("units").filter(|v| !v.is_null()) { let u = u.as_str().unwrap_or(""); self.units = Unit::named(u).ok_or_else(|| bad(cmd, format!("unknown units `{u}`")))?; @@ -329,11 +333,11 @@ impl DocSettings { Some(o) => return Err(bad(cmd, format!("orientation must be portrait or landscape, not `{o}`"))), } if let Some(n) = p.get("artboards").filter(|v| !v.is_null()) { - let n = n.as_f64().filter(|n| n.is_finite()).ok_or_else(|| bad(cmd, "artboards must be a number"))?; - self.artboards = n.round().clamp(1.0, MAX_ARTBOARDS as f64) as u32; + self.artboards = if replaying { n.as_f64().map(|n| n.round().clamp(1.0, f64::from(MAX_ARTBOARDS)) as u32) } else { count(n) } + .ok_or_else(|| bad(cmd, format!("artboards must be a whole number from 1 to {MAX_ARTBOARDS}")))?; } if let Some(l) = p.get("artboardLayout").filter(|v| !v.is_null()) { - self.layout_params(l, cmd)?; + self.layout_params(l, cmd, replaying)?; } if let Some(b) = p.get("bleed").filter(|v| !v.is_null()) { self.bleed = super::docsetup::bleed_param(b, self.bleed, cmd)?; @@ -371,7 +375,7 @@ impl DocSettings { } /// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id. - fn layout_params(&mut self, l: &Value, cmd: &str) -> Result<()> { + fn layout_params(&mut self, l: &Value, cmd: &str, replaying: bool) -> Result<()> { let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column"); if let Some(id) = l.as_str() { self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?; @@ -380,25 +384,22 @@ impl DocSettings { } return Ok(()); } - let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?; + let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?}"))?; for (k, v) in o { match k.as_str() { "layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?, "columns" => { - self.columns = v - .as_f64() - .filter(|c| c.is_finite() && *c >= 1.0) - .ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))? - .round() - .min(MAX_ARTBOARDS as f64) as u32 + self.columns = + if replaying { v.as_f64().filter(|n| *n >= 1.0).map(|n| n.round().min(f64::from(MAX_ARTBOARDS)) as u32) } else { count(v) } + .ok_or_else(|| bad(cmd, format!("artboardLayout.columns must be a whole number from 1 to {MAX_ARTBOARDS}")))? } "rows" => { - self.rows = v - .as_f64() - .map(f64::round) - .filter(|r| (1.0..=MAX_ARTBOARDS as f64).contains(r)) - .map(|r| r as u32) - .ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be from 1 to {MAX_ARTBOARDS}")))? + 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) + } else { + count(v) + } + .ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be a whole number from 1 to {MAX_ARTBOARDS}")))? } "spacing" => { self.spacing = v @@ -407,7 +408,7 @@ impl DocSettings { .ok_or_else(|| bad(cmd, format!("artboardLayout.spacing must be 0–{MAX_SPACING} pt")))? } "rightToLeft" => self.right_to_left = v.as_bool().ok_or_else(|| bad(cmd, "artboardLayout.rightToLeft must be true or false"))?, - _ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft)"))), + _ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft)"))), } } if o.contains_key("rows") && self.layout != ArtboardLayout::GridByColumn { @@ -610,6 +611,12 @@ fn de_rows<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result Option { + v.as_f64().filter(|n| n.fract() == 0.0 && (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n 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)) @@ -871,7 +878,7 @@ 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 settings = base.with_params_inner(p, C, s.replaying())?; if size != Some(sorted(&settings)) { settings.name = "Custom".into(); } @@ -956,7 +963,7 @@ fn save(s: &mut Session, p: &Value) -> Result { Some(from) => find(s, from).ok_or_else(|| bad(C, format!("no preset called `{from}` (see file.newPresets)")))?, None => s.default_settings(), }; - let mut preset = base.with_params(p, C)?; + let mut preset = base.with_params_inner(p, C, s.replaying())?; preset.name = name.to_string(); let saved = &mut s.prefs.new_doc_presets; match saved.iter_mut().find(|q| q.name.eq_ignore_ascii_case(name)) { diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index ad2711558e..94caaf4348 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -173,6 +173,79 @@ fn ppi_overprint_preview_and_bad_params() { } } +/// Artboard counts, columns and rows are whole numbers in range: a fraction or a count outside +/// 1 to 1000 is an error, not rounded or clamped to one. +#[test] +fn counts_that_are_not_whole_or_out_of_range_are_errors() { + for p in [ + json!({"artboards": 2.4}), + json!({"artboards": 0}), + json!({"artboards": -0.5}), + json!({"artboards": 1001}), + json!({"artboardLayout": {"columns": 2.4}}), + json!({"artboardLayout": {"columns": 1001}}), + json!({"artboardLayout": {"layout": "gridByColumn", "rows": 2.4}}), + json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0.6}}), + json!({"artboardLayout": {"layout": "gridByColumn", "rows": 1000.4}}), + ] { + let mut s = Session::new(); + assert!(s.execute("file.new", &p).is_err(), "{p}"); + assert!(s.active().is_none(), "{p}: no document on an error"); + } + let s = new_doc(json!({"artboards": 6.0, "artboardLayout": {"layout": "gridByColumn", "rows": 2.0}})); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 6, "a whole number written 6.0 is a count"); +} + +#[test] +fn replaying_a_journal_rounds_an_older_artboard_count() { + let mut recorded = new_doc(json!({"artboards": 2})); + recorded.journal.last_mut().unwrap().1["artboards"] = json!(2.4); + let mut s = Session::new(); + for (id, p) in &recorded.journal { + s.replay(id, p).unwrap(); + } + assert_eq!(boards(&s), boards(&recorded)); + assert_eq!(boards(&s).len(), 2); + assert!(s.execute("file.new", &json!({"artboards": 2.4})).is_err()); +} + +#[test] +fn replayed_counts_keep_their_rounding_and_range_rules() { + for (key, value, expected) in [ + ("artboards", 0.0, 1), + ("artboards", 1001.0, 1000), + ("columns", 2.4, 2), + ("columns", 1001.0, 1000), + ("rows", 2.4, 2), + ("rows", 0.6, 1), + ("rows", 1000.4, 1000), + ] { + let mut p = json!({"width": 10, "height": 10, "artboards": 4, + "artboardLayout": {"layout": "gridByColumn", "spacing": 0}}); + if key == "artboards" { + p[key] = json!(value); + } else { + p["artboardLayout"][key] = json!(value); + } + let mut s = Session::new(); + s.replay("file.new", &p).unwrap(); + assert!(s.execute("file.new", &p).is_err(), "{p}"); + if key == "artboards" { + p[key] = json!(expected); + } else { + p["artboardLayout"][key] = json!(expected); + } + assert_eq!(boards(&s), boards(&new_doc(p))); + } + for layout in [json!({"columns": 0.6}), json!({"rows": 0.4}), json!({"rows": 1000.6})] { + let mut p = json!({"artboardLayout": layout}); + p["artboardLayout"]["layout"] = json!("gridByColumn"); + let mut s = Session::new(); + assert!(s.replay("file.new", &p).is_err(), "{p}"); + assert!(s.active().is_none(), "{p}"); + } +} + #[test] fn categories_list_generated_presets_with_neutral_names() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index bb333e91d8..f006b5217e 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1017,7 +1017,7 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { let (plain, spaced) = (plain.with_params(&to_row, "file.new").unwrap(), spaced.with_params(&to_row, "file.new").unwrap()); assert_eq!(plain.grid_columns(), spaced.grid_columns()); let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string(); - assert!(e.contains("rows must be from 1 to 1000"), "{e}"); + assert!(e.contains("rows must be a whole number from 1 to 1000"), "{e}"); for layout in ["gridByRow", "row", "column"] { let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string(); assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}"); diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index c20582141e..8d4b9aa247 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -1293,7 +1293,8 @@ mod tests { let mut app = app(); open(&mut app); set(&app, "artboards", json!(5)).unwrap(); - set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).unwrap(); + assert!(set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).is_err(), "a fraction is refused"); + set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4, "spacing": 10})).unwrap(); assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4)); create(&mut app); let st = app.session.active().unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index d984e7b92d..ad2d536722 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -632,6 +632,11 @@ of `appearance.setItem`, `anchor` of `path.removeAnchor` and `addon.pen.removePo value such as `"3"`, `2.5`, `-1` or `true` with `` `index` must be a whole number ``, naming the key, and reports a key left out or null as missing (such as `` missing integer `index` ``). An optional one, such as `subpath`, keeps its default when left out or null; `appearance.setActiveItem` reads a null `index` as clearing the active item. +`file.new` refuses a number given for `artboards`, `artboardLayout.columns` or `artboardLayout.rows` that is not a +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. 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 @@ -10504,7 +10509,7 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes `file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height` (points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns, -rows, spacing, rightToLeft}` (`rows`, 1 to 1000 and rounded to a whole number, gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is +rows, spacing, rightToLeft}` (`artboards`, `columns` and `rows` are whole numbers from 1 to 1000, and any other number is an error; `rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are fewer artboards, until `columns` without `rows`, or another layout, is given; New Document's Columns shows the columns the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes), From 6532abda434ceed8e59919e3305c490750518510 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 17:19:26 -0800 Subject: [PATCH 35/72] Arrange Tools: Group by Row refuses Shaper and compound shape children and non-object params Group by Row now refuses objects whose parent is a Shaper group or a live compound shape, since regrouping them breaks the Shaper group or changes the Boolean result, and refuses parameters that are not an object. Row measurements share one symbol name index instead of indexing every symbol for each instance. --- crates/engine/src/cmd/addons/arrange.rs | 14 ++- crates/engine/src/cmd/addons/arrange/tests.rs | 95 +++++++++++++++++++ docs/mcp.md | 2 +- 3 files changed, 106 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index d33bcfcee5..1d6d57b0cc 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -104,7 +104,7 @@ pub fn specs() -> Vec { "Group by Row", ["Object", "Plug-ins", "Arrange Tools"], None, - "{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\" when omitted; null is invalid)} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. An object joins a row when its visual bounds overlap the row's extent across it. Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, and clipping masks stay in place. The command rejects selections of editable objects whose parent is neither a layer nor a group, including live blend keys. An object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}", + "{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\" when omitted; null is invalid)} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. Parameters must be an object. An object joins a row when its visual bounds overlap the row's extent across it. Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, and clipping masks stay in place. The command rejects selections of editable objects whose parent is neither a layer nor a group, including live blend keys, and direct children of Shaper groups or live compound shapes. An object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}", has_multi, group_rows ), @@ -457,6 +457,9 @@ fn rows_of(items: &[(K, (f64, f64))]) -> Vec Result { const C: &str = "addon.arrange.groupRows"; + if !p.is_object() { + return Err(bad(C, "parameters must be an object")); + } if p.get("direction").is_some_and(Value::is_null) { return Err(bad(C, "`direction` must be row or column")); } @@ -471,12 +474,15 @@ fn group_rows(s: &mut Session, p: &Value) -> Result { roots.iter().copied().filter(|id| editable(*id)).collect() }; for id in &editable_roots { - if d.parent_of(*id).and_then(|parent| d.node(parent)).is_some_and(|n| !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })) { - return Err(bad(C, "selected objects must be in a layer or group")); + if d.parent_of(*id).and_then(|parent| d.node(parent)).is_some_and(|n| { + !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.is_compound_shape() || n.extras().shaper.is_some() + }) { + return Err(bad(C, "selected objects must be in a layer or group without live structural roles")); } } // Each object's row key (its parent and its artboard) and its extent across the rows. type Keyed = ((Option, usize), (f64, f64)); + let symbols = d.symbol_boxes(); let items: Vec<(NodeId, Keyed)> = editable_roots .iter() .filter_map(|id| { @@ -487,7 +493,7 @@ fn group_rows(s: &mut Session, p: &Value) -> Result { { return None; } - let b = effects::preview::bounds_of(d, &[*id], true)?; + let b = effects::preview::visual_bounds(&symbols.unmeasured(), d.node(*id)?)?; let extent = if rows { (b.y0, b.y1) } else { (b.x0, b.x1) }; Some((*id, ((parent, d.artboard_for_bounds(b)?), extent))) }) diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index e382c2a440..5416687473 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -633,6 +633,58 @@ fn group_rows_refuses_explicitly_selected_live_blend_keys() { assert_eq!(children(&s, blend), [a, b]); } +#[test] +fn group_rows_refuses_explicitly_selected_shaper_children() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + select(&mut s, &[a, b]); + let shaper = NodeId(s.execute("shaper.scribble", &json!({"points": [[25, 25], [125, 25]]})).unwrap()["id"].as_u64().unwrap()); + let members = children(&s, shaper); + assert!(members.len() >= 2); + let sources = members[0]; + let face = s + .doc() + .unwrap() + .doc + .node(shaper) + .unwrap() + .children() + .unwrap() + .iter() + .find(|n| n.name.as_deref().is_some_and(|name| name.starts_with(vectorcraft_doc::shaper::FILL_PREFIX))) + .unwrap() + .id; + let c = rect(&mut s, 200.0, 0.0, 20.0, 20.0); + let d = rect(&mut s, 230.0, 0.0, 20.0, 20.0); + for direction in ["row", "column"] { + select(&mut s, &[sources, face]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + select(&mut s, &[sources, face, c, d]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + assert_eq!(children(&s, shaper), members); + } +} + +#[test] +fn group_rows_refuses_explicitly_selected_live_compound_shape_operands() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let b = rect(&mut s, 10.0, 0.0, 30.0, 30.0); + select(&mut s, &[a, b]); + s.execute("object.compoundShape.make", &json!({"mode": "subtract"})).unwrap(); + let shape = s.doc().unwrap().selection.objects[0]; + let c = rect(&mut s, 200.0, 0.0, 20.0, 20.0); + let d = rect(&mut s, 230.0, 0.0, 20.0, 20.0); + for direction in ["row", "column"] { + select(&mut s, &[a, b]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + select(&mut s, &[a, b, c, d]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + assert_eq!(children(&s, shape), [a, b]); + } +} + #[test] fn group_rows_skips_explicitly_selected_locked_and_hidden_objects() { for command in ["object.lock", "object.hide"] { @@ -717,6 +769,49 @@ fn group_rows_is_off_with_one_object_skips_locked_ones_and_refuses_bad_params() assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(s.doc().unwrap().doc.layers[0].id)); } +#[test] +fn group_rows_refuses_non_object_params_without_an_edit() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + let selection = s.doc().unwrap().selection.objects.clone(); + refuses(&mut s, "addon.arrange.groupRows", &[json!([]), json!(["row"]), json!("row"), json!(true), json!(3)]); + assert_eq!(s.doc().unwrap().selection.objects, selection); +} + +#[test] +fn group_rows_reads_the_symbol_index_once_for_all_members() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, Document, Node, NodeKind, Symbol}; + use vectorcraft_geom::Affine; + + let mut d = Document::new(400.0, 300.0); + for i in 0..200 { + let art = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + d.symbols.push(Symbol { dynamic: false, name: format!("Mark {i}"), art: Arc::new(art) }); + } + let layer = d.layers[0].id; + let ids: Vec<_> = (0..8) + .map(|i| { + let xf = Affine::translate((0.0, f64::from(i) * 20.0)); + let n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: format!("Mark {i}"), xf }); + d.insert(Some(layer), usize::MAX, n).unwrap() + }) + .collect(); + let symbol_count = d.symbols.len(); + let mut s = Session::new(); + s.add_document(d, None); + select(&mut s, &ids); + let n = steps(&s); + let before = vectorcraft_doc::symbols_read(); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= symbol_count, "{read} symbols read, {symbol_count} in the document"); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n)); + assert_eq!(layer_children(&s), ids); +} + #[test] fn group_rows_sorts_many_objects_into_rows() { // 20000 objects in pairs up the page, the front one of each pair starting higher: each pair overlaps, diff --git a/docs/mcp.md b/docs/mcp.md index e01104769b..3543a70ff2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17582,7 +17582,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | -| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid) | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, and clipping masks stay in place. The command rejects selections of editable objects whose parent is neither a layer nor a group, including live blend keys. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | +| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid). Parameters must be an object. | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, and clipping masks stay in place. The command rejects selections of editable objects whose parent is neither a layer nor a group, including live blend keys, and direct children of Shaper groups or live compound shapes. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | From 26a70bb546448a70b3290eca394668d647f5f0f3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 17:40:55 -0800 Subject: [PATCH 36/72] Scripts: test that eval code with a forbidden super or new.target runs none of it The tests from #10023 for `super` and `new.target` in global eval, indirect eval and `Function` bodies check only that a SyntaxError is thrown. The interpreter also throws one at run time when `super` has no home object or constructor (class_ops.rs:450 and :555), so a case the parser let through would still pass them if it threw only at run time. Two tests in es2015_tests.rs put `x = 1` ahead of the forbidden form: - eval_code_with_a_forbidden_super_or_new_target_runs_none_of_it covers 13 cases of `super.y`, `super(...)` and `new.target` in global eval, indirect eval, direct eval in a plain function, and direct eval in a method or constructor that does not allow the form. Each leaves `x` at 0 and throws a SyntaxError. - a_function_body_with_super_is_not_made covers 5 `Function` calls with `super` in the body or a parameter default. Each throws a SyntaxError from `Function` itself, so no function is returned and `x` stays 0. Every case was already rejected by the parser; the tests change no behavior. --- crates/js/src/es2015_tests.rs | 55 +++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index f134176bfc..28fb8c3408 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -1714,6 +1714,61 @@ fn a_function_body_reads_its_own_new_target() { truth("class A { m() { return Function('return new.target')(); } } new A().m() === undefined"); } +/// Eval code that uses `super` or `new.target` where it may not is a `SyntaxError` before any of +/// it runs, so `x = 1` ahead of the forbidden form leaves `x` at 0 (ECMA-262 2015 sections +/// 18.2.1.1 and 15.1.1). +#[test] +fn eval_code_with_a_forbidden_super_or_new_target_runs_none_of_it() { + let a = "class A { constructor(v) { this.a = v; } } "; + let calls = [ + "eval('x = 1; super.y');".to_string(), + "class C { m() { (0, eval)('x = 1; super.y'); } } new C().m();".to_string(), + "function F() { eval('x = 1; super.y'); } F();".to_string(), + "class C { m() { (function () { eval('x = 1; super.y'); })(); } } new C().m();".to_string(), + "eval('x = 1; super()');".to_string(), + "class C { constructor() { eval('x = 1; super()'); } } new C();".to_string(), + format!("{a}class B extends A {{ m() {{ eval('x = 1; super(1)'); }} }} new B(1).m();"), + format!("{a}class B extends A {{ constructor() {{ (0, eval)('x = 1; super(1)'); }} }} new B();"), + format!("{a}class B extends A {{ constructor() {{ (function () {{ eval('x = 1; super(1)'); }})(); }} }} new B();"), + "function F() { eval('x = 1; super()'); } F();".to_string(), + "eval('x = 1; new.target');".to_string(), + "(() => eval('x = 1; new.target'))();".to_string(), + "function F() { (0, eval)('x = 1; new.target'); } new F();".to_string(), + ]; + let ran: Vec<&String> = calls + .iter() + .filter(|call| { + let src = format!("var x = 0, e; try {{ {call} }} catch (err) {{ e = err; }} x === 0 && e instanceof SyntaxError"); + run(&src) != JsValue::Bool(true) + }) + .collect(); + assert!(ran.is_empty(), "eval code ran or did not throw a SyntaxError: {ran:#?}"); +} + +/// The `Function` constructor throws the `SyntaxError` for `super` in the body or a parameter +/// itself, so it returns no function to call and `x = 1` in the body never runs (ECMA-262 2015 +/// section 19.2.1.1.1). +#[test] +fn a_function_body_with_super_is_not_made() { + let a = "class A { constructor(v) { this.a = v; } } "; + let calls = [ + "class C { m() { f = Function('x = 1; super.y'); } } new C().m();".to_string(), + "class C { m() { f = Function('a = super.y', 'x = 1'); } } new C().m();".to_string(), + "f = Function('x = 1; super.y');".to_string(), + format!("{a}class B extends A {{ constructor() {{ super(1); f = Function('x = 1; super(1)'); }} }} new B();"), + "f = Function('x = 1; super()');".to_string(), + ]; + let made: Vec<&String> = calls + .iter() + .filter(|call| { + let src = + format!("var x = 0, f, e; try {{ {call} f(); }} catch (err) {{ e = err; }} f === undefined && x === 0 && e instanceof SyntaxError"); + run(&src) != JsValue::Bool(true) + }) + .collect(); + assert!(made.is_empty(), "Function made a function or did not throw a SyntaxError: {made:#?}"); +} + #[test] fn deep_class_chains_stay_within_the_limits() { let src = "var C = class {}; for (var i = 0; i < 2000; i++) { C = class extends C {}; } new C();"; From 5fccf73431456ec49eb08f0761649eeb2dbe4b69 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 18:02:26 -0800 Subject: [PATCH 37/72] Color Effects: Randomize Fill Colors colors compound marks in a graph series A compound path or live compound shape directly in a graph series group now takes a color. Generated column, marker and legend swatch copies carry a new graph_design_art flag and keep their design's fill; in documents saved before the flag, a compound in a series whose assigned design is itself a compound is still treated as design art. Paths a user groups inside a series keep their fills, as for paint.setFill. Nested members resolve to the outermost compound in one walk of the ancestry, and series membership is looked up once per run. --- ROADMAP.md | 2 +- crates/doc/src/graph.rs | 1 + crates/doc/src/node/extras.rs | 3 + crates/doc/src/node/tests.rs | 2 + crates/doc/src/node/wire.rs | 5 + crates/engine/src/cmd/addons/color.rs | 2 +- .../src/cmd/addons/color/random_fill.rs | 136 +++++- .../src/cmd/addons/color/random_fill/tests.rs | 415 ++++++++++++++++++ crates/engine/src/cmd/graph.rs | 4 +- crates/engine/src/cmd/graph/columns.rs | 4 +- crates/engine/src/cmd/graph/labels.rs | 4 +- crates/engine/src/cmd/graph/series.rs | 2 +- docs/mcp.md | 12 +- docs/target-app-parity.md | 2 +- 14 files changed, 567 insertions(+), 27 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index e00dedaaa6..bc350856d2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -160,7 +160,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923). -- 2026-11-29: Randomize Fill Colors joins the Color Effects add-on (Object › Plug-ins › Color Effects): each selected filled path and compound path, inside groups too, gets a fill color of its own at random: any color, tints of a global or spot swatch, or grays between a minimum and a maximum percent, with a seed that repeats the result and Preview, as one undo step (`addon.color.randomFill`); art on a locked artboard keeps its fill (also when `ids` names it), except new art made there while it is still selected. +- 2026-11-29: Randomize Fill Colors joins the Color Effects add-on (Object › Plug-ins › Color Effects): each selected filled path, compound path and live compound shape, inside groups and graph series too, gets a fill color of its own at random: any color, tints of a global or spot swatch, or grays between a minimum and a maximum percent, with a seed that repeats the result and Preview, as one undo step (`addon.color.randomFill`); art on a locked artboard keeps its fill (also when `ids` names it), except new art made there while it is still selected. - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index 36fe29a8f2..43614eba87 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -108,6 +108,7 @@ impl GraphDesign { let mut e = n.extras_mut(); e.graph = None; e.series_index = None; + e.graph_design_art = false; } if let Some(ch) = n.children_mut() { let old = std::mem::take(ch); diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index 9dbb409706..99ca99a2c5 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -22,6 +22,8 @@ pub struct NodeExtras { /// Index of the graph series this generated group belongs to. Axes, the legend and other /// children leave it unset, so a series named "Legend" or "Axes" is not mistaken for them. pub series_index: Option, + /// This object is a generated copy of a graph column or marker design. + pub graph_design_art: bool, /// The group holds the glyph outlines of type. Geometry effects that reshape it move and scale /// the placed gradients in it with the outlines. pub type_outlines: bool, @@ -108,6 +110,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { wrap: None, graph: None, series_index: None, + graph_design_art: false, type_outlines: false, pixelated: false, shaper: None, diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 8d6520265a..8b8d848ed3 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -13,6 +13,7 @@ fn extras_are_written_flat_in_order() { e.mask = Some(Box::new(OpacityMask::new(Node::group(NodeId(8), vec![]), true))); e.trace = Some(Box::new(serde_json::json!({"preset": "p"}))); e.series_index = Some(2); + e.graph_design_art = true; e.type_outlines = true; e.graphic_style = Some(3); e.attrs = Some(Box::default()); @@ -59,6 +60,7 @@ fn extras_are_written_flat_in_order() { "mask", "trace", "series_index", + "graph_design_art", "type_outlines", "kind", "graphic_style", diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index d543c9d9e1..234adb7793 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -36,6 +36,7 @@ impl Serialize for Node { e.wrap.is_none(), e.graph.is_none(), e.series_index.is_none(), + is_default(&e.graph_design_art), is_default(&e.type_outlines), is_default(&e.pixelated), e.shaper.is_none(), @@ -86,6 +87,7 @@ impl Serialize for Node { field!("wrap", &e.wrap); field!("graph", &e.graph); field!("series_index", &e.series_index); + field!("graph_design_art", &e.graph_design_art); field!("type_outlines", &e.type_outlines); field!("pixelated", &e.pixelated); field!("shaper", &e.shaper); @@ -220,6 +222,8 @@ pub(super) struct NodeWire { #[serde(default)] series_index: Option, #[serde(default)] + graph_design_art: bool, + #[serde(default)] type_outlines: bool, #[serde(default)] pixelated: bool, @@ -480,6 +484,7 @@ impl From for Node { wrap: w.wrap, graph: w.graph, series_index: w.series_index, + graph_design_art: w.graph_design_art, type_outlines: w.type_outlines, pixelated: w.pixelated, shaper: w.shaper, diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index c991d75389..bd07f1552f 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Randomize Fill Colors", ["Object", "Plug-ins", "Color Effects"], None, - "{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors), ids?: [id…] (default: the selection)} give each selected filled path and compound path, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Paths and compound paths with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}", + "{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base, which must still support tints), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors), ids?: [id…] (default: the selection)} give each selected filled path, compound path and live compound shape, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}", has_selection, random_fill::run ), diff --git a/crates/engine/src/cmd/addons/color/random_fill.rs b/crates/engine/src/cmd/addons/color/random_fill.rs index f8ac3967b3..eaf78e5660 100644 --- a/crates/engine/src/cmd/addons/color/random_fill.rs +++ b/crates/engine/src/cmd/addons/color/random_fill.rs @@ -1,18 +1,22 @@ //! Randomize Fill Colors (`addon.color.randomFill`, Object › Plug-ins › Color Effects › Randomize -//! Fill Colors…): each selected filled path and compound path, and each one inside the selected +//! Fill Colors…): each selected filled path, compound path and live compound shape, and each one inside the selected //! groups, gets a fill color of its own, picked at random from a seed: any color, a tint of one //! global or spot swatch, or a gray, as one undo step. #[cfg(test)] mod tests; +use std::collections::HashSet; + use serde_json::{Value, json}; use vectorcraft_color::recolor::Rng; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use super::super::super::colorcmds::{edit_if_changed, keeping_series_paint}; -use super::super::super::graph::paint_targets; +#[cfg(test)] +use super::super::super::graph::is_design_art; +use super::super::super::graph::{is_series_group, paint_targets}; use super::super::super::menucmds::whole_or; use super::super::super::paint::swatch_solid; use super::super::super::{bad, checked_ids_or_selection, number_or, text_param}; @@ -32,10 +36,10 @@ enum Scheme { Gray(f32, f32), } -/// The percentage `p` gives for `key` (`default` when left out) as a fraction. -fn percent(p: &Value, key: &str, default: f64) -> Result { +/// The percentage `p` gives for `key` (`default` when left out). +fn percent(p: &Value, key: &str, default: f64) -> Result { let v = number_or(p, key, default, C)?; - if (0.0..=100.0).contains(&v) { Ok((v / 100.0) as f32) } else { Err(bad(C, format!("`{key}` must be from 0 to 100"))) } + if (0.0..=100.0).contains(&v) { Ok(v) } else { Err(bad(C, format!("`{key}` must be from 0 to 100"))) } } /// The scheme `p` asks for, checked against the document's swatches. @@ -58,11 +62,18 @@ fn scheme(s: &Session, p: &Value) -> Result { if min > max { return Err(bad(C, "`min` is greater than `max`")); } + let (min, max) = ((min / 100.0) as f32, (max / 100.0) as f32); if name == "gray" { return Ok(Scheme::Gray(min, max)); } let swatch = text_param(p, "swatch", C)?.ok_or_else(|| bad(C, "scheme tint needs a `swatch`: a global or spot color swatch"))?; - swatch_solid(&s.doc()?.doc, swatch, Some(1.0)).map_err(|e| bad(C, e))?; + let d = &s.doc()?.doc; + swatch_solid(d, swatch, Some(1.0)).map_err(|e| bad(C, e))?; + if let Some((base, _)) = d.swatch_link(swatch) + && d.tint_paint(&base, 1.0).is_none() + { + return Err(bad(C, format!("`{swatch}` needs a global or spot base swatch `{base}`"))); + } Ok(Scheme::Tint(swatch.to_string(), min, max)) } @@ -77,7 +88,7 @@ fn left_alone(d: &Document, id: NodeId) -> bool { matches!(nodes.as_slice(), [.., parent, n] if parent.clips() && parent.children().and_then(|c| c.first()).is_some_and(|c| c.id == n.id)) } -/// Add to `out` `n` when it is a filled path or compound path that is shown and unlocked, or the +/// Add to `out` `n` when it is a filled path, compound path or live compound shape that is shown and unlocked, or the /// ones inside it when it is a group or a layer. A clipping path (the first object of a clipping /// group or clipped layer, a compound path included), a guide, type, images, symbol instances, /// blends and envelopes are left as they are. @@ -85,6 +96,12 @@ fn filled(n: &Node, out: &mut Vec) { if !n.visible || n.locked { return; } + if n.is_compound_shape() { + if !n.appearance.fill_paint().is_none() { + out.push(n.id); + } + return; + } match &n.kind { NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { for c in children.iter().skip(usize::from(n.clips())) { @@ -96,6 +113,45 @@ fn filled(n: &Node, out: &mut Vec) { } } +/// `ids` with each graph series group replaced by the paths, compound paths and live compound shapes directly inside +/// it. A compound path or live compound shape directly in a series group is kept, and the other ids go through +/// [`paint_targets`], as for `paint.setFill`. +fn series_roots(doc: &Document, ids: &[NodeId]) -> Vec { + let is_series = |id: NodeId| doc.node(id).is_some_and(|n| is_series_group(doc, n)); + let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape(); + let ordinary: std::collections::HashSet = paint_targets(doc, ids).into_iter().collect(); + let mut out = vec![]; + for id in ids { + let Some(n) = doc.node(*id) else { continue }; + if is_series(*id) { + out.extend(n.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. }) || compound(m)).map(|m| m.id)); + } else if (compound(n) && doc.parent_of(*id).is_some_and(is_series)) || ordinary.contains(id) { + out.push(*id); + } + } + let mut seen = std::collections::HashSet::new(); + out.retain(|id| seen.insert(*id)); + out +} + +/// The graph series groups among the ancestors of `targets`, each checked once. +fn cached_series_groups(doc: &Document, targets: &[NodeId]) -> HashSet { + let mut groups: HashSet = targets.iter().filter_map(|id| doc.ancestry(*id)).flatten().collect(); + groups.retain(|id| doc.node(*id).is_some_and(|n| is_series_group(doc, n))); + groups +} + +/// [`is_design_art`] with the series groups looked up in `series_groups`. +fn cached_is_design_art(doc: &Document, id: NodeId, series_groups: &HashSet) -> bool { + let Some(chain) = doc.ancestry(id) else { return false }; + let Some(at) = chain.iter().position(|a| series_groups.contains(a)) else { return false }; + match chain.len() - at { + 1 => false, + 2 => doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. })), + _ => true, + } +} + pub(super) fn run(s: &mut Session, p: &Value) -> Result { let scheme = scheme(s, p)?; let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); @@ -106,24 +162,76 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result { let model = s.doc()?.doc.color_mode.model(); // A run that gives every object the fill it has records no undo step. let count = edit_if_changed(s, "Randomize Fill Colors", |before, d| { - // A graph's series group stands for its marks, as for `paint.setFill`. - let roots = paint_targets(before, &ids); // Art on a locked artboard is left as it is, as for the other commands that take `ids`. let locks = before.locked_artboards(); + // A nested member stands for the outermost compound path or live compound shape after each ancestor is checked. + let mut resolved = vec![]; + for id in &ids { + let Some(chain) = before.ancestry(*id) else { continue }; + let mut target = None; + let mut blocked = false; + let mut parent: Option<&Node> = None; + let mut layer_object_checked = false; + for ancestor in &chain { + let Some(n) = before.node(*ancestor) else { + blocked = true; + break; + }; + if !n.visible || n.locked || parent.is_some_and(|p| p.clips() && p.children().and_then(|c| c.first()).is_some_and(|c| c.id == n.id)) { + blocked = true; + break; + } + if !layer_object_checked && (n.is_ruler_guide() || !n.is_layer()) { + layer_object_checked = true; + if !n.is_ruler_guide() && locks.holds(n) { + blocked = true; + break; + } + } + if matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape() { + target.get_or_insert(*ancestor); + } + parent = Some(n); + } + if !blocked { + resolved.push(target.unwrap_or(*id)); + } + } + // A graph's series group stands for its marks, as for `paint.setFill`. + let roots = series_roots(before, &resolved); let mut targets = vec![]; for id in &roots { - let id = before - .parent_of(*id) - .filter(|parent| before.node(*parent).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))) - .unwrap_or(*id); + let id = *id; if left_alone(before, id) || locks.holds_id(id) { continue; } let Some(n) = before.node(id) else { continue }; filled(n, &mut targets); } + let series_groups = cached_series_groups(before, &targets); let mut seen = std::collections::HashSet::new(); - targets.retain(|id| seen.insert(*id) && !locks.holds_id(*id)); + // A compound directly in a series group is one of the series' marks unless the graph drew it from a design; + // the rest of the series' art below its top level is design art. + let series_compound = |id: NodeId| { + let Some(n) = before.node(id) else { return false }; + if !(matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape()) || n.extras().graph_design_art { + return false; + } + let Some(group) = before.parent_of(id).filter(|p| series_groups.contains(p)).and_then(|p| before.node(p)) else { return false }; + let Some(index) = group.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false }; + let graph = before.parent_of(group.id).and_then(|p| before.node(p)).and_then(|p| p.extras().graph.as_deref()); + graph.is_some_and(|spec| { + let column = spec.series_columns.get(index).and_then(Option::as_ref).map(|c| c.design.as_str()); + let marker = spec.series_markers.get(index).and_then(Option::as_deref); + ![column, marker].into_iter().flatten().any(|name| { + before + .graph_designs + .iter() + .any(|design| design.name == name && (matches!(design.art.kind, NodeKind::Compound { .. }) || design.art.is_compound_shape())) + }) + }) + }; + targets.retain(|id| seen.insert(*id) && !locks.holds_id(*id) && (series_compound(*id) || !cached_is_design_art(before, *id, &series_groups))); let count = keeping_series_paint(d, &roots, |d| { let mut count = 0; for id in &targets { diff --git a/crates/engine/src/cmd/addons/color/random_fill/tests.rs b/crates/engine/src/cmd/addons/color/random_fill/tests.rs index 3253ce98ee..1c66e7cde4 100644 --- a/crates/engine/src/cmd/addons/color/random_fill/tests.rs +++ b/crates/engine/src/cmd/addons/color/random_fill/tests.rs @@ -212,6 +212,421 @@ fn a_compound_clipping_path_keeps_its_fill() { assert_eq!(fill(&s, compound), mask_fill); } +#[test] +fn a_live_compound_shape_takes_one_color_and_keeps_its_members_fills() { + for target in ["shape", "group", "member"] { + let mut s = session(); + let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x)); + select(&mut s, &[a, b]); + let shape = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert!(s.doc().unwrap().doc.node(shape).unwrap().is_compound_shape()); + let id = match target { + "group" => NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()), + "member" => a, + _ => shape, + }; + let before = fill(&s, shape); + let members = fills(&s, &[a, b]); + let n = steps(&s); + assert_eq!(s.execute(C, &json!({"ids": [id.0], "scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(1), "{target}"); + assert_eq!(fill(&s, shape), Paint::solid(Color::gray(0.3)), "{target}"); + assert_eq!(fills(&s, &[a, b]), members, "{target}"); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(fill(&s, shape), before); + assert_eq!(fills(&s, &[a, b]), members); + } +} + +#[test] +fn a_selected_graph_keeps_the_fills_of_generated_design_art() { + let mut s = session(); + let a = rect(&mut s, 0.0); + s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#336699"})).unwrap(); + select(&mut s, &[a]); + s.execute("graph.design", &json!({"new": "Tile"})).unwrap(); + let graph = NodeId( + s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("graph.column", &json!({"id": graph.0, "design": "Tile"})).unwrap(); + let mut design_paths = vec![]; + let d = &s.doc().unwrap().doc; + d.node(graph).unwrap().walk(&mut |n| { + if matches!(n.kind, NodeKind::Path { .. }) && super::is_design_art(d, n.id) && !n.appearance.fill_paint().is_none() { + design_paths.push(n.id); + } + }); + assert!(!design_paths.is_empty()); + let before = fills(&s, &design_paths); + select(&mut s, &[graph]); + s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap(); + assert_eq!(fills(&s, &design_paths), before); +} + +#[test] +fn a_compound_path_in_a_graph_series_takes_a_color() { + let mut s = session(); + let graph = NodeId( + s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let d = &s.doc().unwrap().doc; + let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap(); + let group = series.id; + let marks: Vec = series.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect(); + assert!(marks.len() >= 2); + let marks = &marks[..2]; + select(&mut s, marks); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "the compound path is directly in the series group"); + for ids in [vec![compound], vec![marks[0]], vec![group]] { + let before = fill(&s, compound); + let r = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + assert!(r["count"].as_u64().unwrap() >= 1, "{ids:?}"); + assert_ne!(fill(&s, compound), before, "{ids:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + } +} + +#[test] +fn a_compound_in_a_graph_series_takes_a_color_after_its_design_is_deleted() { + for kind in ["column", "line", "scatter"] { + let mut s = session(); + let a = rect(&mut s, 0.0); + select(&mut s, &[a]); + s.execute("graph.design", &json!({"new": "Tile"})).unwrap(); + let graph = NodeId( + s.execute( + "graph.create", + &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Tile"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.is_empty()); + let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap(); + let group = series.id; + let index = series.extras().series_index.unwrap() as usize; + let spec = d.node(graph).unwrap().extras().graph.as_deref().unwrap(); + if kind == "column" { + assert_eq!(spec.series_columns[index].as_ref().unwrap().design, "Tile"); + } else { + assert_eq!(spec.series_markers[index].as_deref(), Some("Tile")); + } + let marks: Vec = series + .children() + .into_iter() + .flatten() + .filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none()) + .map(|m| m.id) + .collect(); + assert!(marks.len() >= 2, "{kind}"); + let marks = &marks[..2]; + select(&mut s, marks); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "{kind}"); + let before = fill(&s, compound); + let members = fills(&s, marks); + select(&mut s, &[graph]); + let result = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap(); + assert!(result["count"].as_u64().unwrap() >= 1, "{kind}"); + assert_ne!(fill(&s, compound), before, "{kind}"); + assert_eq!(fills(&s, marks), members, "{kind}"); + } +} + +#[test] +fn a_user_compound_in_a_series_with_a_plain_path_design_takes_a_color() { + for kind in ["column", "line", "scatter"] { + let mut s = session(); + let a = rect(&mut s, 0.0); + select(&mut s, &[a]); + s.execute("graph.design", &json!({"new": "Tile"})).unwrap(); + assert!(matches!(s.doc().unwrap().doc.graph_designs[0].art.kind, NodeKind::Path { .. })); + let graph = NodeId( + s.execute( + "graph.create", + &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap(); + let designed = s.doc().unwrap().doc.node(graph).unwrap().extras().graph.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + s.edit("Set series design without replacing ordinary marks", |d, _| { + d.node_mut(graph).unwrap().extras_mut().graph = designed; + Ok(()) + }) + .unwrap(); + let d = &s.doc().unwrap().doc; + let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap(); + let group = series.id; + let marks: Vec = series + .children() + .into_iter() + .flatten() + .filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none()) + .map(|m| m.id) + .collect(); + assert!(marks.len() >= 2, "{kind}"); + let marks = &marks[..2]; + select(&mut s, marks); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "{kind}"); + assert!(!s.doc().unwrap().doc.node(compound).unwrap().extras().graph_design_art, "{kind}"); + let members = fills(&s, marks); + for ids in [vec![compound], vec![marks[0]], vec![group], vec![graph]] { + let before = fill(&s, compound); + let result = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + assert!(result["count"].as_u64().unwrap() >= 1, "{kind}: {ids:?}"); + assert_eq!(fill(&s, compound), Paint::solid(Color::gray(0.4)), "{kind}: {ids:?}"); + assert_ne!(fill(&s, compound), before, "{kind}: {ids:?}"); + assert_eq!(fills(&s, marks), members, "{kind}: {ids:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + } + } +} + +#[test] +fn grouped_paths_in_a_graph_series_keep_their_fills_as_for_paint_set_fill() { + for kind in ["column", "line", "scatter"] { + let mut s = session(); + let graph = NodeId( + s.execute( + "graph.create", + &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let d = &s.doc().unwrap().doc; + let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap(); + let group = series.id; + let marks: Vec = series + .children() + .into_iter() + .flatten() + .filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none()) + .map(|m| m.id) + .collect(); + assert!(marks.len() >= 2, "{kind}"); + let marks = &marks[..2]; + select(&mut s, marks); + let nested = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(nested), Some(group), "{kind}"); + let before = fills(&s, marks); + select(&mut s, &[graph]); + // `paint.setFill` on the graph leaves a group inside a series alone, as design art; so does this command. + s.execute("paint.setFill", &json!({"color": "#aa0000"})).unwrap(); + let after_set_fill = fills(&s, marks); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap(); + assert_eq!(fills(&s, marks), before, "{kind}"); + assert_eq!(after_set_fill, before, "{kind}: paint.setFill keeps grouped marks too"); + } +} + +#[test] +fn generated_compound_design_copies_in_a_graph_series_keep_their_fills() { + for (kind, legacy) in ["column", "line", "scatter"].into_iter().flat_map(|kind| [false, true].map(|legacy| (kind, legacy))) { + let mut s = session(); + let marks = rects(&mut s, 2); + select(&mut s, &marks); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [compound.0], "color": "#336699"})).unwrap(); + select(&mut s, &[compound]); + s.execute("graph.design", &json!({"new": "Tile"})).unwrap(); + let graph = NodeId( + s.execute( + "graph.create", + &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap(); + let d = &s.doc().unwrap().doc; + let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap(); + let group = series.id; + let copies: Vec = + series.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Compound { .. })).map(|m| m.id).collect(); + assert!(!copies.is_empty(), "{kind}: the generated compound is directly in the series group"); + for id in &copies { + assert!(d.node(*id).unwrap().extras().graph_design_art, "{kind}"); + assert!(super::is_design_art(d, *id), "{kind}"); + } + let mut art = vec![]; + series.walk(&mut |n| { + if super::is_design_art(d, n.id) { + art.push(n.id); + } + }); + if legacy { + s.edit("Clear graph design flags", |d, _| { + for id in &art { + d.node_mut(*id).unwrap().extras_mut().graph_design_art = false; + } + Ok(()) + }) + .unwrap(); + } + let before = fills(&s, &art); + for ids in [vec![graph], vec![group], copies] { + s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + assert_eq!(fills(&s, &art), before, "{kind}, legacy: {legacy}: {ids:?}"); + } + } +} + +#[test] +fn hidden_or_locked_compound_members_given_by_id_keep_the_compounds_fill() { + for hide in [true, false] { + let mut s = session(); + let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x)); + select(&mut s, &[a, b]); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.setProps", &if hide { json!({"id": a.0, "visible": false}) } else { json!({"id": a.0, "locked": true}) }).unwrap(); + let member = s.doc().unwrap().doc.node(a).unwrap(); + assert!(if hide { !member.visible } else { member.locked }); + let parent = s.doc().unwrap().doc.node(compound).unwrap(); + assert!(parent.visible && !parent.locked); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + assert_eq!(s.execute(C, &json!({"ids": [a.0], "scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(0), "hidden: {hide}"); + assert_eq!(fill(&s, compound), before.node(compound).unwrap().appearance.fill_paint()); + assert!(*s.doc().unwrap().doc == *before); + assert_eq!(steps(&s), n); + } +} + +#[test] +fn seeded_colors_follow_ids_order_without_repeating_objects() { + let mut s = session(); + let ids = rects(&mut s, 3); + s.execute(C, &json!({"ids": ids.iter().map(|id| id.0).collect::>(), "seed": 7})).unwrap(); + let first = fills(&s, &ids); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.execute(C, &json!({"ids": [ids[2].0, ids[0].0, ids[2].0, ids[1].0], "seed": 7})).unwrap()["count"], json!(3)); + assert_eq!(fills(&s, &[ids[2], ids[0], ids[1]]), first); +} + +#[test] +fn nested_members_color_the_outermost_compound_unless_an_ancestor_is_blocked() { + for blocked in ["none", "hidden", "locked", "artboard"] { + let mut s = session(); + let [a, b, c] = [0.0, 2.0, 4.0].map(|x| rect(&mut s, x)); + select(&mut s, &[a]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[group, b]); + let inner = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[inner, c]); + let outer = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + match blocked { + "hidden" => { + s.execute("object.setProps", &json!({"id": group.0, "visible": false})).unwrap(); + } + "locked" => { + s.execute("object.setProps", &json!({"id": inner.0, "locked": true})).unwrap(); + } + "artboard" => { + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + } + _ => {} + } + let before = s.doc().unwrap().doc.clone(); + let members = fills(&s, &[a, b, c, group, inner]); + let n = steps(&s); + let r = s.execute(C, &json!({"ids": [a.0], "scheme": "gray", "min": 30, "max": 30})).unwrap(); + assert_eq!(fills(&s, &[a, b, c, group, inner]), members, "{blocked}"); + if blocked == "none" { + assert_eq!(r["count"], json!(1)); + assert_eq!(fill(&s, outer), Paint::solid(Color::gray(0.3))); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + } else { + assert_eq!(r["count"], json!(0), "{blocked}"); + assert_eq!(steps(&s), n, "{blocked}"); + } + assert!(*s.doc().unwrap().doc == *before, "{blocked}"); + } +} + +#[test] +fn an_invalid_series_index_keeps_ordinary_subgroups_reachable() { + let mut s = session(); + let graph = NodeId( + s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let series = s.doc().unwrap().doc.node(graph).unwrap().children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); + let group = series.id; + let marks: Vec = series.children().unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).map(|n| n.id).collect(); + assert!(!marks.is_empty()); + select(&mut s, &marks); + s.execute("object.group", &json!({})).unwrap(); + s.edit("Set series index", |d, _| { + d.node_mut(group).unwrap().extras_mut().series_index = Some(u32::MAX); + Ok(()) + }) + .unwrap(); + let before = fills(&s, &marks); + let r = s.execute(C, &json!({"ids": [group.0], "scheme": "gray", "min": 30, "max": 30})).unwrap(); + assert_eq!(r["count"], json!(marks.len())); + assert!(fills(&s, &marks).iter().all(|p| *p == Paint::solid(Color::gray(0.3)))); + assert_ne!(fills(&s, &marks), before); + assert!(s.doc().unwrap().doc.node(graph).unwrap().extras().graph.as_ref().unwrap().series_paints.is_empty()); +} + +#[test] +fn a_tint_swatch_with_a_deleted_base_is_refused_without_a_change() { + let mut s = session(); + let ids = rects(&mut s, 2); + select(&mut s, &ids); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap(); + let tint = s.execute("swatch.new", &json!({"name": "Pale", "swatch": "Ink", "tint": 40})).unwrap()["name"].as_str().unwrap().to_string(); + s.execute("swatch.delete", &json!({"name": "Ink", "unlink": false})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.swatch("Ink").is_none()); + assert_eq!(d.swatch_link(&tint), Some(("Ink".to_string(), 0.4))); + let before = d.clone(); + let n = steps(&s); + let e = s.execute(C, &json!({"scheme": "tint", "swatch": tint, "min": 10, "max": 80})).unwrap_err().to_string(); + assert!(e.contains("base swatch `Ink`"), "{e}"); + assert!(*s.doc().unwrap().doc == *before); + assert_eq!(steps(&s), n); +} + +#[test] +fn an_inverted_range_that_rounds_to_equal_f32_bounds_is_refused() { + let mut s = session(); + let a = rect(&mut s, 0.0); + select(&mut s, &[a]); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + for p in [json!({"scheme": "gray", "min": 50.0000001, "max": 50}), json!({"scheme": "tint", "swatch": "Ink", "min": 50.0000001, "max": 50})] { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains("`min` is greater than `max`"), "{p}: {e}"); + assert!(*s.doc().unwrap().doc == *before); + assert_eq!(steps(&s), n); + } +} + #[test] fn no_undo_step_when_no_fill_changes() { let mut s = session(); diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 06fb062e50..f348a97f3c 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -54,8 +54,8 @@ pub(crate) use series::{ capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_styles_given, capture_label_text, capture_line_changes, capture_line_fill_stroke_rows, capture_line_kind_rows, capture_line_paint_writes, capture_line_row_writes, capture_line_rows, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades, graph_part_members, is_design_art, - is_graph_line, label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, - series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades, + is_graph_line, is_series_group, label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks, + series_group_marks_where, series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/graph/columns.rs b/crates/engine/src/cmd/graph/columns.rs index 6c87143618..ad7f145af0 100644 --- a/crates/engine/src/cmd/graph/columns.rs +++ b/crates/engine/src/cmd/graph/columns.rs @@ -328,7 +328,9 @@ pub(super) fn column_art( } parts.push(Arc::new(d.reid(&crate::cmd::place::transformed(n, by)))); } - Some(Arc::new(Node::group(d.alloc_id(), parts))) + let mut n = Node::group(d.alloc_id(), parts); + n.extras_mut().graph_design_art = true; + Some(Arc::new(n)) }; let mut parts = vec![]; let (mut label, mut sliding) = (fit_affine(frame, rect), None); diff --git a/crates/engine/src/cmd/graph/labels.rs b/crates/engine/src/cmd/graph/labels.rs index b5d5632356..b5faf1ccf8 100644 --- a/crates/engine/src/cmd/graph/labels.rs +++ b/crates/engine/src/cmd/graph/labels.rs @@ -271,7 +271,9 @@ impl Gen<'_> { /// A copy of design art drawn in a series: a single path gets a group of its own, as painting a series paints the /// paths directly inside its group and the design keeps its own paint. fn design_copy(&mut self, n: Arc) -> Arc { - if matches!(n.kind, NodeKind::Path { .. }) { Arc::new(Node::group(self.d.alloc_id(), vec![n])) } else { n } + let mut n = if matches!(n.kind, NodeKind::Path { .. }) { Arc::new(Node::group(self.d.alloc_id(), vec![n])) } else { n }; + Arc::make_mut(&mut n).extras_mut().graph_design_art = true; + n } /// A series group. Empty series are omitted by the caller; the index is stored on the group /// so later paint edits find the series without counting siblings. diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index 3ea811392d..7371961c20 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -204,7 +204,7 @@ pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: i /// Whether `n` is a graph series group: a child of a graph with one of the graph's series indexes ([`series_members`]). /// It is looked up through its parent, with no pass over the document: the panels call this while they draw. -fn is_series_group(doc: &Document, n: &Node) -> bool { +pub(crate) fn is_series_group(doc: &Document, n: &Node) -> bool { let Some(index) = n.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false }; let graph = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref()); graph.is_some_and(|spec| index < series_count(spec)) diff --git a/docs/mcp.md b/docs/mcp.md index 3b341caa6e..b51ea5d626 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17265,7 +17265,7 @@ on the object or on one of its fills or strokes; a group carrying one is selecte `count` selected. `addon.color.randomFill {scheme?, swatch?, min?, max?, seed?, ids?}` (Object › Plug-ins › Color Effects › Randomize -Fill Colors…) gives each selected filled path and compound path, and each one inside the selected groups and clipping +Fill Colors…) gives each selected filled path, compound path and live compound shape, and each one inside the selected groups and clipping groups, a top fill color of its own, picked at random and evenly, as one undo step (none when no fill changes): | `scheme` | Each fill becomes | @@ -17275,13 +17275,15 @@ groups, a top fill color of its own, picked at random and evenly, as one undo st | `gray` | A gray from `min` to `max` percent black | `min` and `max` are 0 to 100 (0 and 100 when left out) and go with `tint` and `gray` only; `swatch` goes with `tint` -only and is needed there (a tint swatch gives tints of its base). The same `seed` (a whole number, 0 when left out), -objects and settings give the same colors. Paths and compound paths with no fill, clipping paths (a compound path that -clips included), hidden and locked objects and the objects in hidden or locked groups and layers or on a locked artboard (also when `ids` names them; new art made there while it is still selected takes a color), type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill is replaced by +only and is needed there (a tint swatch gives tints of its base, which must still support tints). The same `seed` (a whole number, 0 when left out), +objects and settings give the same colors. Compound paths and live compound shapes take one color and keep their members' fills. +An id naming a nested member targets the outermost compound. +Paths, compound paths and live compound shapes with no fill, clipping paths (a compound path that +clips included), hidden and locked objects and the objects in hidden or locked groups and layers or on a locked artboard (also when `ids` names them; new art made there while it is still selected takes a color), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill is replaced by the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, so after the redraw every mark of the series has that one color. It returns the `count` of objects whose fill changed. An unknown scheme, `min` or `max` with `color`, `swatch` without `tint`, a -percent outside 0 to 100, `min` above `max`, a missing or process swatch and a seed that is not a whole number are +percent outside 0 to 100, `min` above `max`, a missing or process swatch, a tint swatch whose base cannot produce tints and a seed that is not a whole number are errors, and the document is left as it was. The dialog's seed starts new whenever the document has changed, and its Swatch choice lists the document's global and spot swatches. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7e33bb042f..671fd127b6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3129,7 +3129,7 @@ add-on. ## Color Effects add-on: Randomize Fill Colors (2026-11-29) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Color Effects › Randomize Fill Colors… gives each selected filled path and compound path, and each one inside the selected groups and clipping groups, its own top fill color, picked at random and evenly: any color in the document's color mode, a linked tint of a global or spot swatch, or a gray, the tints and grays between a minimum and a maximum percent. A seed repeats a result exactly, and the dialog starts with a new one whenever the document has changed. Paths without a fill, clipping paths, hidden and locked objects, type, images, symbol instances, blends and envelopes keep their fills. One undo step, none when no fill changes; bad params are refused without a change. Tests: `cmd::addons::color::random_fill::tests` in `vectorcraft-engine` (each scheme and its range, the seed, groups, compound paths and clipping groups entered, unfilled, hidden and locked objects left alone, CMYK documents, one undo step or none, bad params refused), `addons::color::random_fill::tests` and the add-on dialog family test in `vectorcraft-ui-egui` (typed values preview, OK and Cancel, the Swatch choice), and `command_sweep`. Commands: `docs/mcp.md` › Color Effects add-on. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Color Effects › Randomize Fill Colors… gives each selected filled path, compound path and live compound shape, and each one inside the selected groups and clipping groups, its own top fill color, picked at random and evenly: any color in the document's color mode, a linked tint of a global or spot swatch, or a gray, the tints and grays between a minimum and a maximum percent. Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. A seed repeats a result exactly, and the dialog starts with a new one whenever the document has changed. Objects without a fill, clipping paths, hidden and locked objects, objects inside hidden or locked groups and layers or on a locked artboard, generated graph design art, type, images, symbol instances, blends and envelopes keep their fills. New art made on a locked artboard takes a color while it is still selected. The command records one undo step when a fill changes and rejects bad params without a change. Tests: `cmd::addons::color::random_fill::tests` in `vectorcraft-engine` (each scheme and its range, the seed, groups, compound paths, live compound shapes and clipping groups entered, unfilled, hidden and locked objects left alone, CMYK documents, one undo step or none, bad params refused), `addons::color::random_fill::tests` and the add-on dialog family test in `vectorcraft-ui-egui` (typed values preview, OK and Cancel, the Swatch choice), and `command_sweep`. Commands: `docs/mcp.md` › Color Effects add-on. ## Arrange Tools add-on (2026-10-31) From 094f59566c024a363abfead0916650e99843f0c4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 18:05:25 -0800 Subject: [PATCH 38/72] Arrange Tools: Group by Row refuses parts of live groups and graphs and leaves layers alone Group by Row now also refuses direct children of Objects on Path and Live Paint groups and objects inside a live graph, while a whole live group or graph can still be grouped with other art. Selected layers and sublayers stay selected and are not grouped. --- crates/engine/src/cmd/addons/arrange.rs | 33 +++-- crates/engine/src/cmd/addons/arrange/tests.rs | 129 ++++++++++++++++++ docs/mcp.md | 2 +- 3 files changed, 151 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 1d6d57b0cc..7768b4f62e 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -104,7 +104,7 @@ pub fn specs() -> Vec { "Group by Row", ["Object", "Plug-ins", "Arrange Tools"], None, - "{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\" when omitted; null is invalid)} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. Parameters must be an object. An object joins a row when its visual bounds overlap the row's extent across it. Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, and clipping masks stay in place. The command rejects selections of editable objects whose parent is neither a layer nor a group, including live blend keys, and direct children of Shaper groups or live compound shapes. An object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}", + "{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\" when omitted; null is invalid)} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. Parameters must be an object. An object joins a row when its visual bounds overlap the row's extent across it. Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, clipping masks, layers, and sublayers stay in place. Every grouping candidate must have a parent that is a layer or group. The command rejects selections containing editable live blend keys, direct children of Shaper groups, live compound shapes, Objects on Path groups, or Live Paint groups, and any descendants of live graphs. Complete live groups and graphs can be grouped with other artwork. An object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}", has_multi, group_rows ), @@ -471,26 +471,33 @@ fn group_rows(s: &mut Session, p: &Value) -> Result { let d = &s.doc()?.doc; let editable_roots: Vec<_> = { let editable = d.editable(); - roots.iter().copied().filter(|id| editable(*id)).collect() + roots.iter().copied().filter(|id| editable(*id) && d.node(*id).is_some_and(|n| !n.is_layer())).collect() }; for id in &editable_roots { - if d.parent_of(*id).and_then(|parent| d.node(parent)).is_some_and(|n| { - !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.is_compound_shape() || n.extras().shaper.is_some() - }) { + let parent = d.parent_of(*id); + let valid_parent = parent.and_then(|parent| d.node(parent)).is_some_and(|n| { + matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) + && !n.is_compound_shape() + && n.extras().shaper.is_none() + && n.extras().objects_on_path.is_none() + && !vectorcraft_tools::builder::is_live_paint(n) + }); + let in_graph = parent + .and_then(|parent| d.ancestry(parent)) + .is_some_and(|ancestors| ancestors.iter().any(|ancestor| d.node(*ancestor).is_some_and(|n| n.extras().graph.is_some()))); + if !valid_parent || in_graph { return Err(bad(C, "selected objects must be in a layer or group without live structural roles")); } } // Each object's row key (its parent and its artboard) and its extent across the rows. - type Keyed = ((Option, usize), (f64, f64)); + type Keyed = ((NodeId, usize), (f64, f64)); let symbols = d.symbol_boxes(); let items: Vec<(NodeId, Keyed)> = editable_roots .iter() .filter_map(|id| { - let parent = d.parent_of(*id); - if parent - .and_then(|parent| d.node(parent)) - .is_some_and(|n| n.clips() && n.children().and_then(|c| c.first()).is_some_and(|c| c.id == *id)) - { + let parent = d.parent_of(*id)?; + let container = d.node(parent)?; + if container.clips() && container.children().and_then(|c| c.first()).is_some_and(|c| c.id == *id) { return None; } let b = effects::preview::visual_bounds(&symbols.unmeasured(), d.node(*id)?)?; @@ -500,7 +507,9 @@ fn group_rows(s: &mut Session, p: &Value) -> Result { .collect(); let keyed: Vec<_> = items.iter().map(|(_, k)| *k).collect(); let sets: Vec> = rows_of(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect(); - group_each(s, if rows { "Group by Row" } else { "Group by Column" }, &roots, sets) + let mut selection = roots; + selection.extend(s.doc()?.selection.objects.iter().copied().filter(|id| d.node(*id).is_some_and(|n| n.is_layer()))); + group_each(s, if rows { "Group by Row" } else { "Group by Column" }, &selection, sets) } /// Put each of `sets` (two or more of the selected top-level objects `roots`, each in stacking order) into a diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 5416687473..6f50164c0c 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -616,6 +616,135 @@ fn group_rows_keeps_clipping_masks_first_in_groups_and_layers() { } } +#[test] +fn group_rows_leaves_selected_layers_and_sublayers_in_place() { + for sublayers in [false, true] { + let mut s = session(); + let parent = s.doc().unwrap().doc.layers[0].id; + let mut layers = vec![]; + for _ in 0..2 { + let command = if sublayers { "layer.newSublayer" } else { "layer.new" }; + let params = if sublayers { json!({"parent": parent.0}) } else { json!({"top": true}) }; + let layer = NodeId(s.execute(command, ¶ms).unwrap()["id"].as_u64().unwrap()); + rect(&mut s, 10.0, 10.0, 20.0, 20.0); + layers.push(layer); + } + s.execute("layer.setCurrent", &json!({"id": parent.0})).unwrap(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0); + for direction in ["row", "column"] { + select(&mut s, &layers); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap(); + assert_eq!(r["grouped"], json!(0), "layers must not become ordinary group members"); + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before); + select(&mut s, &[layers[0], layers[1], a, b]); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap(); + assert_eq!(r["grouped"], json!(2)); + let groups = ids_of(&r["groups"]); + assert_eq!(children(&s, groups[0]), [a, b]); + for layer in &layers { + assert_eq!(s.doc().unwrap().doc.parent_of(*layer), sublayers.then_some(parent)); + assert!(s.doc().unwrap().selection.objects.contains(layer)); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert!(*s.doc().unwrap().doc == *before); + } + } +} + +#[test] +fn group_rows_refuses_objects_without_a_parent() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0); + s.edit("Set root objects", |d, _| { + for id in [a, b] { + let node = d.remove(id)?; + d.layers.push(node); + } + Ok(()) + }) + .unwrap(); + select(&mut s, &[a, b]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": "row"}), json!({"direction": "column"})]); +} + +fn refuse_row_parts_and_group_whole(s: &mut Session, group: NodeId, parts: &[Vec]) { + let center = bounds(s, group).center(); + let a = rect(s, center.x - 10.0, center.y - 10.0, 20.0, 20.0); + let b = rect(s, center.x - 5.0, center.y - 5.0, 20.0, 20.0); + let members = children(s, group); + for direction in ["row", "column"] { + for selected in parts { + select(s, selected); + let selection = s.doc().unwrap().selection.clone(); + refuses(s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + assert_eq!(s.doc().unwrap().selection, selection); + let mut mixed = selected.clone(); + mixed.extend([a, b]); + select(s, &mixed); + refuses(s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + assert_eq!(children(s, group), members); + } + select(s, &[group, a, b]); + let before = s.doc().unwrap().doc.clone(); + let n = steps(s); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap(); + assert_eq!(r["grouped"], json!(3)); + let groups = ids_of(&r["groups"]); + assert_eq!(children(s, groups[0]), [group, a, b]); + assert_eq!(children(s, group), members); + assert_eq!(steps(s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(*s.doc().unwrap().doc == *before); + } +} + +#[test] +fn group_rows_refuses_objects_on_path_children_but_groups_the_whole_group() { + let mut s = session(); + let path = rect(&mut s, 20.0, 20.0, 100.0, 100.0); + let member = rect(&mut s, 30.0, 30.0, 20.0, 20.0); + let group = NodeId(s.execute("object.objectsOnPath.attach", &json!({"path": path.0, "ids": [member.0]})).unwrap()["id"].as_u64().unwrap()); + refuse_row_parts_and_group_whole(&mut s, group, &[vec![path, member]]); + assert!(s.doc().unwrap().doc.node(group).unwrap().extras().objects_on_path.is_some()); +} + +#[test] +fn group_rows_refuses_live_paint_faces_and_edges_but_groups_the_whole_group() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + select(&mut s, &[a, b]); + let group = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let node = s.doc().unwrap().doc.node(group).unwrap(); + let faces: Vec<_> = vectorcraft_tools::builder::faces(node).iter().map(|n| n.id).collect(); + let edges: Vec<_> = vectorcraft_tools::builder::edges(node).iter().map(|n| n.id).collect(); + assert!(faces.len() >= 2); + assert!(edges.len() >= 2); + refuse_row_parts_and_group_whole(&mut s, group, &[faces.clone(), edges.clone()]); + let node = s.doc().unwrap().doc.node(group).unwrap(); + assert_eq!(vectorcraft_tools::builder::faces(node).iter().map(|n| n.id).collect::>(), faces); + assert_eq!(vectorcraft_tools::builder::edges(node).iter().map(|n| n.id).collect::>(), edges); +} + +#[test] +fn group_rows_refuses_live_graph_descendants_but_groups_the_whole_graph() { + let mut s = session(); + let params = json!({"type": "column", "x": 20, "y": 20, "width": 200, "height": 200, "csv": ",Series\nA,3\nB,5"}); + let graph = NodeId(s.execute("graph.create", ¶ms).unwrap()["id"].as_u64().unwrap()); + let node = s.doc().unwrap().doc.node(graph).unwrap(); + let series = node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); + let marks: Vec<_> = series.children().unwrap().iter().take(2).map(|n| n.id).collect(); + assert_eq!(marks.len(), 2); + let direct = children(&s, graph); + refuse_row_parts_and_group_whole(&mut s, graph, &[marks, direct]); + assert!(s.doc().unwrap().doc.node(graph).unwrap().extras().graph.is_some()); +} + #[test] fn group_rows_refuses_explicitly_selected_live_blend_keys() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 3543a70ff2..dfaf15c8b0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17582,7 +17582,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | -| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid). Parameters must be an object. | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, and clipping masks stay in place. The command rejects selections of editable objects whose parent is neither a layer nor a group, including live blend keys, and direct children of Shaper groups or live compound shapes. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | +| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid). Parameters must be an object. | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, clipping masks, layers, and sublayers stay in place. Every grouping candidate must have a parent that is a layer or group. The command rejects selections containing editable live blend keys, direct children of Shaper groups, live compound shapes, Objects on Path groups, or Live Paint groups, and any descendants of live graphs. Complete live groups and graphs can be grouped with other artwork. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | From cd1c3e8c9f9936c94dec8e723a05eb18c9904da3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 20:16:33 -0800 Subject: [PATCH 39/72] Docs: name Group by Row among the Arrange Tools visual-bounds exceptions The Arrange Tools overview said every command except Arrange in Grid and Offset Objects measures as object.setBounds does. Group by Row always uses visual bounds, with strokes and vector effects included and raster effects left out, so the overview now names it and points to its row. --- docs/mcp.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 17d78bcf03..d0521ef3a2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17572,7 +17572,8 @@ images and patterns keep their colours. → `{changed, swatches: [the document s Arrange Tools is a built-in add-on that lays out, swaps, replaces and sizes selected objects: its commands are `addon.arrange.*`, and in the desktop app it lives in Object › Plug-ins › Arrange Tools. Each command acts on the top-level selected objects and is one undo step; a run that moves nothing makes no step. Places and sizes are measured -as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid and Offset Objects, which use visual bounds. +as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid and Offset Objects, which use visual bounds, and Group by Row, which always uses visual bounds +with strokes and vector effects included and raster effects left out (see its row). | Command | Parameters (default) | Does | |---|---|---| From 845544618c8ae140201b9c8dea69658df1069edd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 21:56:00 -0800 Subject: [PATCH 40/72] Color Effects: Randomize Fill Colors documents that colors follow the ids order The MCP guide and the command help now say that colors are drawn in the order ids lists the objects, so the same seed can give each object a different color when the order changes. The graph design test also covers copies that keep the design flag while the series no longer names a design, so the flag alone keeps their fills. --- crates/engine/src/cmd/addons/color.rs | 2 +- .../src/cmd/addons/color/random_fill/tests.rs | 23 ++++++++++++++++--- docs/mcp.md | 4 +++- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index bd07f1552f..a9f1b48166 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Randomize Fill Colors", ["Object", "Plug-ins", "Color Effects"], None, - "{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base, which must still support tints), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors), ids?: [id…] (default: the selection)} give each selected filled path, compound path and live compound shape, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}", + "{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base, which must still support tints), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors; colors are drawn in the order of ids, a repeated id counting once and an id inside a listed group taking its color with that group's objects, so another order can give each object a different color), ids?: [id…] (default: the selection)} give each selected filled path, compound path and live compound shape, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}", has_selection, random_fill::run ), diff --git a/crates/engine/src/cmd/addons/color/random_fill/tests.rs b/crates/engine/src/cmd/addons/color/random_fill/tests.rs index 1c66e7cde4..11b4f989be 100644 --- a/crates/engine/src/cmd/addons/color/random_fill/tests.rs +++ b/crates/engine/src/cmd/addons/color/random_fill/tests.rs @@ -440,7 +440,10 @@ fn grouped_paths_in_a_graph_series_keep_their_fills_as_for_paint_set_fill() { #[test] fn generated_compound_design_copies_in_a_graph_series_keep_their_fills() { - for (kind, legacy) in ["column", "line", "scatter"].into_iter().flat_map(|kind| [false, true].map(|legacy| (kind, legacy))) { + // `legacy` clears the design flags and keeps the series' design reference; `flag_only` keeps the flags and clears the + // reference, so each check keeps the copies' fills on its own. + let modes = [(false, false), (true, false), (false, true)]; + for (kind, (legacy, flag_only)) in ["column", "line", "scatter"].into_iter().flat_map(|kind| modes.map(|mode| (kind, mode))) { let mut s = session(); let marks = rects(&mut s, 2); select(&mut s, &marks); @@ -483,10 +486,24 @@ fn generated_compound_design_copies_in_a_graph_series_keep_their_fills() { }) .unwrap(); } + if flag_only { + s.edit("Clear series design reference", |d, _| { + let mut extras = d.node_mut(graph).unwrap().extras_mut(); + let spec = extras.graph.as_deref_mut().unwrap(); + spec.series_columns.iter_mut().for_each(|c| *c = None); + spec.series_markers.iter_mut().for_each(|m| *m = None); + Ok(()) + }) + .unwrap(); + for id in &copies { + assert!(s.doc().unwrap().doc.node(*id).unwrap().extras().graph_design_art, "{kind}"); + } + } let before = fills(&s, &art); - for ids in [vec![graph], vec![group], copies] { + let runs = if flag_only { vec![copies.clone()] } else { vec![vec![graph], vec![group], copies] }; + for ids in runs { s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); - assert_eq!(fills(&s, &art), before, "{kind}, legacy: {legacy}: {ids:?}"); + assert_eq!(fills(&s, &art), before, "{kind}, legacy: {legacy}, flag only: {flag_only}: {ids:?}"); } } } diff --git a/docs/mcp.md b/docs/mcp.md index b51ea5d626..5551ed6813 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17276,7 +17276,9 @@ groups, a top fill color of its own, picked at random and evenly, as one undo st `min` and `max` are 0 to 100 (0 and 100 when left out) and go with `tint` and `gray` only; `swatch` goes with `tint` only and is needed there (a tint swatch gives tints of its base, which must still support tints). The same `seed` (a whole number, 0 when left out), -objects and settings give the same colors. Compound paths and live compound shapes take one color and keep their members' fills. +objects and settings give the same colors. The colors are drawn in the order `ids` lists the objects, a repeated id counting once and an id inside a listed group +taking its color when that group's objects are colored, +so with the ids in another order the same seed can give each object a different color. Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths (a compound path that clips included), hidden and locked objects and the objects in hidden or locked groups and layers or on a locked artboard (also when `ids` names them; new art made there while it is still selected takes a color), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill is replaced by From 0b469bb7b663b23e8006a114f7af3fdd13a2f82d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 00:14:10 -0800 Subject: [PATCH 41/72] Plug-ins: typed values reach the preview and the rows they show A plug-in's parameter dialog did not bind its values to the host fields that the preview and the rows' visibleWhen read, so a check box or a typed number stayed in the form: checking a box did not show the rows that depend on it, and the preview kept running with the opening values. The dialog now binds its values with Bind::bound(fields), as Set Corners and the Arrange dialogs do. --- crates/ui-egui/src/dialogs/plugin.rs | 4 +- .../src/dialogs/tests_plugin_fields.rs | 64 +++++++++++++++++++ 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 8b6606e068..18d650e4bc 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -42,7 +42,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; use craft::menu::Node; -use craft::ui::contract::Show as _; +use craft::ui::contract::{Bind, Show as _}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, Prompt, StackDialog, dialog_id}; use craft::ui::display::{Shade, Text}; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog}; @@ -564,7 +564,7 @@ fn build(key: &'static str, m: Manifest, all: Arc<[Param]>, look: Look) -> impl rows.push(Param::read_only_text("description", "", look.description.clone()).full_width()); } rows.extend(all.iter().filter(|p| shown.contains(p.key.as_str())).cloned()); - let mut dialog = ParamDialog::new(key, look.heading(), Cow::Owned(rows)).previews(look.previews); + let mut dialog = ParamDialog::new(key, look.heading(), Cow::Owned(rows)).values(Bind::bound(fields)).previews(look.previews); if let Some(ok) = look.ok { dialog = dialog.ok_label(ok.into()); } diff --git a/crates/ui-egui/src/dialogs/tests_plugin_fields.rs b/crates/ui-egui/src/dialogs/tests_plugin_fields.rs index c02363e9f5..795c540b64 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_fields.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_fields.rs @@ -257,3 +257,67 @@ fn an_open_plugin_dialog_follows_a_change_of_language() { assert_eq!(shown, (false, true), "the label in German"); assert_eq!(values.unwrap()["size"].as_f64(), Some(7.0), "the value set before"); } + +/// The width of every path in the active document together, in points. +fn paths_width(app: &VectorcraftApp) -> Option { + let doc = &app.session.doc().ok()?.doc; + let mut ids = Vec::new(); + doc.walk(|n| { + if n.path_data().is_some() { + ids.push(n.id); + } + }); + doc.bounds_of(&ids, false).map(|r| r.x1 - r.x0) +} + +/// Values typed and clicked in a plug-in's dialog reach the plug-in: a check box shows the row +/// whose `visibleWhen` it meets, the number typed there previews on the canvas, and OK runs the +/// filter with it as one undo step. +#[test] +fn typed_plugin_values_show_rows_and_reach_the_preview_and_the_run() { + use crate::tests::panel_harness::Panel; + let id = "test.ui.fields.typed"; + let manifest = format!( + r#"{{"id":"{id}","name":"Typed Values","version":"1","kind":"filter","params":{{ + "grow":{{"type":"bool","default":false,"label":"Grow"}}, + "n":{{"type":"int","min":0,"max":10,"default":3,"label":"Count","visibleWhen":{{"grow":[true]}}}}}}}}"# + ); + // A 30 pt wide triangle when the filter is given `n` 7, a 50 pt square otherwise. + let triangle = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[30,0]},{"p":[15,20]}]}]}}]}"#; + let square = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[50,0]},{"p":[50,50]},{"p":[0,50]}]}]}}]}"#; + let wasm = wat::parse_str(tpl::when_given_else(&manifest, tpl::Given::Params, r#""n":7"#, triangle, square)).unwrap(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm)})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.app().run("plugin.dialog", json!({"id": id})).unwrap(); + panel.frame(); + panel.frame(); + assert!(!panel.shows("Count"), "Count is hidden while Grow is off"); + panel.click("Grow"); + panel.frame(); + assert_eq!(fields(&panel.app())["grow"], json!(true), "the click reaches the dialog's values"); + assert!(panel.shows("Count"), "checking Grow shows Count"); + panel.click("Count"); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("7"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); + panel.frame(); + let typed = fields(&panel.app())["n"].clone(); + let previewed = paths_width(&panel.app()); + let undo = panel.app().session.doc().unwrap().history.undo.len(); + panel.click("OK"); + panel.frame(); + panel.frame(); + let (closed, steps, ran) = { + let app = panel.app(); + (!app.any_dialog_open(), app.session.doc().unwrap().history.undo.len(), paths_width(&app)) + }; + panel.app().run("plugin.remove", json!({"id": id})).unwrap(); + assert_eq!(typed.as_f64(), Some(7.0), "the typed count reaches the dialog's values"); + assert_eq!(previewed, Some(30.0), "the typed count previewed"); + assert!(closed, "OK closed the dialog"); + assert_eq!(steps, undo + 1, "one undo step"); + assert_eq!(ran, Some(30.0), "the filter ran with the typed count"); +} From 0c13a1edb2705176fb3e134d420989b20752c3e8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 14:54:47 -0800 Subject: [PATCH 42/72] Scripts: close the review gaps in print, saveAs, File paths and presets - The 1000% scale limit applies only when Fit to Page is off, since the scale factors are not used with it on. - A script run clears the print command allowance when it ends, so a panic inside print cannot leave file.print open to later runs. - saveAs without options takes the format from the path the script names, so a link at that path cannot change it. - A File the host gives back charges its path to the heap. - DocumentPreset.typename throws for a preset from an earlier run. - Documents.addDocumentNoUI throws that it is not available yet. - The print tests remove their folders when an assertion fails. --- crates/engine/src/script/dom.rs | 13 ++++- crates/engine/src/script/dom/print.rs | 17 ++++-- crates/engine/src/script/dom/save_open.rs | 6 +++ crates/engine/src/script/mod.rs | 4 ++ crates/engine/src/tests/script_dom.rs | 6 +++ crates/engine/src/tests/script_print.rs | 53 ++++++++++++++++++- crates/engine/src/tests/script_save_open.rs | 18 +++++++ .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/js/src/file_classes.rs | 17 ++++++ 9 files changed, 126 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index ab9680112b..51c229ac3e 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1644,6 +1644,12 @@ fn check_preset_value(key: &str, value: &Data) -> std::result::Result<(), HostEr } } +/// `DocumentPreset.typename`: throws for a preset from an earlier run, as its settings do. +fn preset_typename(h: &Host, a: &[Data]) -> Answer { + preset_of(h, arg(a, 0)).ok_or_else(|| HostError::Type("this is not a DocumentPreset".into()))?; + Ok(text("DocumentPreset")) +} + /// The getter and setter of the `DocumentPreset` setting `key`: an unset one reads `undefined`. The /// setter checks the kind and size of a value ([`check_preset_value`]) and keeps the old value when /// it throws; `addDocument` checks the ranges. @@ -2964,7 +2970,7 @@ fn classes(link: &Link) -> Vec { new_preset(&h) }); let mut members = vec![ - ("typename".to_string(), typename_of("DocumentPreset"), typed("string")), + ("typename".to_string(), get(link, preset_typename), typed("string")), ("toString".to_string(), class_text("DocumentPreset"), returns("string", &[])), ]; members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k), typed(preset_type(k))))); @@ -3004,7 +3010,10 @@ fn classes(link: &Link) -> Vec { returns("Document", &[("startupPreset", "string"), ("presetSettings", "DocumentPreset"), ("showOptionsDialog", "boolean")]), ), ("toString", class_text("Documents"), returns("string", &[])), - ]), + ]) + .into_iter() + .chain([later(l, "Documents", "addDocumentNoUI")]) + .collect(), Some(function(l, docs_at)), ), ]; diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index 55c9c87e28..abac466aa0 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -732,17 +732,20 @@ fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<( let set = assigned(h, slot); let value = |name: &str| set.iter().find(|(k, _)| *k == name).map(|(_, v)| v); let (hs, vs) = (value("horizontalScale").map(number_of), value("verticalScale").map(number_of)); - for (name, n) in [("horizontalScale", hs), ("verticalScale", vs)] { - if n.is_some_and(|n| n > MAX_PRINT_SCALE) { - return Err(HostError::Error(format!("PrintCoordinateOptions.{name} above {MAX_PRINT_SCALE} is not available yet"))); - } - } let tiling = value("tiling").map(|v| match member_of(v) { "TILEFULLPAGES" => "tileFull", "TILEIMAGEABLEAREAS" => "tileImageable", _ => "none", }); let fit = value("fitToPage").map(flag); + // With Fit to Page on, the scale factors are not used, so only a job that uses them is limited. + if fit != Some(true) { + for (name, n) in [("horizontalScale", hs), ("verticalScale", vs)] { + if n.is_some_and(|n| n > MAX_PRINT_SCALE) { + return Err(HostError::Error(format!("PrintCoordinateOptions.{name} above {MAX_PRINT_SCALE} is not available yet"))); + } + } + } let scaled = hs.is_some() || vs.is_some(); let scaling = if fit == Some(true) { Some("fit") @@ -1079,6 +1082,10 @@ const PRINT: &str = "file.print"; /// checked its params: only `id` passes the fence, and only while `run` runs. fn unfenced(h: &Host, id: &'static str, run: impl FnOnce() -> std::result::Result) -> std::result::Result { h.session.borrow_mut().script_unfenced = Some(id); + #[cfg(test)] + if crate::script::PANIC_WHILE_UNFENCED.with(std::cell::Cell::get) { + panic!("a command past the fence failed"); + } let r = run(); h.session.borrow_mut().script_unfenced = None; r diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index b973be7988..0a74903c87 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -596,6 +596,12 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { p.insert("options".into(), Value::Object(q)); } } + // The path the script names decides the format, as it does for `file.saveAs`: its extension, + // else the document's own format. A link at that path does not change it. + if !p.contains_key("format") { + let own = super::with_doc(h, doc, |_, st| st.format); + p.insert("format".into(), json!(crate::cmd::fileio::format_for_name(path).map_or(own, |f| f.id))); + } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index e76575a800..cc1a6f5b3c 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2938,6 +2938,8 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result> = const { Cell::new(None) }; /// Tests: makes the next slice panic. pub(crate) static PANIC_IN_SLICE: Cell = const { Cell::new(false) }; + /// Tests: makes the next command a member runs past the script fence panic before it runs. + pub(crate) static PANIC_WHILE_UNFENCED: Cell = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. pub(crate) static TEST_GROWTH: Cell> = const { Cell::new(None) }; /// Tests: the bytes a run may keep in place of [`GROWTH_BYTES`]. diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 14878904fb..5c12f0bb33 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1313,6 +1313,8 @@ fn page_item_members_not_built_yet_throw_on_read_and_assignment() { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); + let e = failure(&mut s, "app.documents.addDocumentNoUI('Print');"); + assert!(e.contains("Documents.addDocumentNoUI is not available yet"), "{e}"); // A deleted item or an earlier run's document is stale first. let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.isIsolated;"); assert!(e.contains("Stale page item"), "{e}"); @@ -1380,6 +1382,10 @@ fn a_document_preset_is_an_instance_of_its_class() { let mut s = Session::new(); let out = log(&mut s, "var p = new DocumentPreset(); vc.log(p instanceof DocumentPreset); vc.log(p.typename); vc.log(p.width);"); assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]); + // A named engine keeps the preset, but in a later run its type name throws, as its settings do. + run(&mut s, "#targetengine keep\nvar held = new DocumentPreset();").unwrap(); + let e = failure(&mut s, "#targetengine keep\nheld.typename;"); + assert!(e.contains("this is not a DocumentPreset"), "{e}"); } /// The values the presets hold count against the run's heap, a value assigned again in place of diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index 6fcf309feb..1c15b3e9f0 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -10,13 +10,36 @@ use crate::*; const DENIED: &str = "Script file access denied"; +/// A test's folder, removed when the test ends, a failed assertion included. +struct Workspace(PathBuf); + +impl std::ops::Deref for Workspace { + type Target = Path; + + fn deref(&self) -> &Path { + &self.0 + } +} + +impl AsRef for Workspace { + fn as_ref(&self) -> &Path { + &self.0 + } +} + +impl Drop for Workspace { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + /// A fresh folder for test `name`, by its real path, with `main` for the script. -fn folder(name: &str) -> PathBuf { +fn folder(name: &str) -> Workspace { let base = std::env::temp_dir().join(format!("vc-script-print-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&base); std::fs::create_dir_all(base.join("main")).unwrap(); std::fs::create_dir_all(base.join("outside")).unwrap(); - std::fs::canonicalize(&base).unwrap() + Workspace(std::fs::canonicalize(&base).unwrap()) } /// A session whose scripts keep their data folders in `base/settings/Script Data`, with a @@ -434,9 +457,35 @@ fn options_that_are_not_available_throw() { assert!(e.contains(part), "{case}: {e}"); } assert!(!dir.join("x.pdf").exists(), "nothing printed"); + // With Fit to Page on, the scale factors are not used, so a factor above 1000 does not stop the job. + let out = logged( + &mut s, + &base, + &format!( + "{prefix} {file} var c = o.coordinateOptions; c.horizontalScale = 2000; c.verticalScale = 2000; c.fitToPage = true;\ + app.activeDocument.print(o); vc.log(true);" + ), + ); + assert_eq!(out, json!([true])); + assert!(dir.join("x.pdf").exists(), "the fitted job printed"); let _ = std::fs::remove_dir_all(base); } +/// A panic while `print` has the fence open for `file.print` closes it again for the next run. +#[test] +fn a_panic_while_printing_leaves_the_fence_closed() { + let base = folder("panic-unfenced"); + let mut s = session(&base); + let print = "var o = new PrintOptions(); o.jobOptions.file = new File(Folder.userData.fsName + '/p.pdf'); app.activeDocument.print(o);"; + crate::script::PANIC_WHILE_UNFENCED.with(|p| p.set(true)); + let r = run(&mut s, &base, print); + crate::script::PANIC_WHILE_UNFENCED.with(|p| p.set(false)); + let e = r.map(|r| panic!("the print ran: {r}")).unwrap_err().to_string(); + assert!(e.contains("a command past the fence failed"), "the run ends at the panic: {e}"); + let e = failure(&mut s, &base, "vc.run('file.print', {});"); + assert!(e.contains("a script cannot run"), "{e}"); +} + #[test] fn print_writes_only_where_the_script_may() { let base = folder("refused"); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 67be990c00..56a2b35e03 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -424,6 +424,24 @@ fn a_link_out_of_the_granted_folder_is_refused() { let _ = std::fs::remove_dir_all(base); } +/// Without options, `saveAs` takes the format from the path the script names, not from the file a +/// link at that path leads to. +#[cfg(unix)] +#[test] +fn save_as_takes_the_format_of_the_named_path_through_a_link() { + let base = folder("link-format"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + std::fs::write(dir.join("target.pdf"), "old").unwrap(); + std::os::unix::fs::symlink(dir.join("target.pdf"), dir.join("drawing.svg")).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("drawing.svg")))); + let written = std::fs::read(dir.join("target.pdf")).unwrap(); + assert!(!written.starts_with(b"%PDF"), "the named .svg path writes SVG, not PDF"); + assert!(String::from_utf8_lossy(&written).contains(" JsResult { let Some(proto) = self.files.as_ref().map(|c| c.file_proto) else { return Err(self.type_error("File is not available")) }; + // The path's string is charged to the heap, as a string the host gives back is. + let bytes = string_bytes(path.encode_utf16().count()); + self.reserve_heap(bytes)?; + self.heap.bytes = self.heap.bytes.saturating_add(bytes); instance(self, proto, Value::str(path)) } } @@ -1193,6 +1197,19 @@ mod xmp_run_tests { assert!(matches!(fields.get(&key("__vcXmpPending")), Some(Value::Undefined))); assert!(matches!(fields.get(&key("__vcXmpPath")), Some(Value::String(path)) if path.to_rust_string() == "kept.xmp")); } + + #[test] + fn a_file_the_host_gives_back_charges_its_path_to_the_heap() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + let host = interp.heap.alloc_object(Object::new(Class::Ordinary, None)); + interp.files = Some(Classes { file_proto: host, folder_proto: host, host, current: Value::str("start"), run: 0.0 }); + let path = format!("/{}", "p".repeat(100_000)); + let before = interp.heap.bytes; + let file = interp.rooted(&[Value::Object(host)], |i| i.write_file_ref(&path)).unwrap(); + assert!(matches!(file, Value::Object(_))); + let added = interp.heap.bytes - before; + assert!(added >= string_bytes(path.len()), "the path's {} bytes are charged: {added}", string_bytes(path.len())); + } } /// Adds `File` and `Folder` to the global object, their work done by the host functions in From 4082035b82d0688ed5a1d132f01081dc46e62a02 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 15:51:02 -0800 Subject: [PATCH 43/72] Scripts: locked artboards stop path edits, and move and zOrder respect clipping paths - PathItem point, paint, stroke and transform changes on a path on a locked artboard now throw `Cannot edit` and change nothing, as the PageItem setters do. `pathItems.removeAll()` deletes nothing when a path is on a locked artboard, as `pageItems.removeAll()` does; it used to delete them. - `move` and `duplicate` with `PLACEAFTER` and the clipping path of a clip group or clipping layer as the relative object throw instead of putting the object above the clipping path, or reporting success without moving it. - `zOrder` counts the art above a clipping path and below the layer's ruler guides, as the Arrange commands do, so a method that leaves the object where it is runs no command. Docs: docs/mcp.md. --- crates/engine/src/script/dom.rs | 31 +++++--- crates/engine/src/script/dom/paths.rs | 46 ++++++++---- crates/engine/src/tests/script_dom.rs | 79 +++++++++++++++++++++ crates/engine/src/tests/script_dom_paths.rs | 28 ++++++++ docs/mcp.md | 14 ++-- 5 files changed, 170 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index d8d01956f4..04285a3ca5 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2657,6 +2657,14 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result:: (parent, Some(target)) } }; + // The clipping path stays at the bottom of its clip group or clipping layer. + if how == Placement::Below + && target != item.id + && d.node(parent).is_some_and(crate::doc::Node::clips) + && d.position(target).is_some_and(|(_, i, _)| i == 0) + { + return Err(HostError::Error("an object cannot go below a clipping mask".into())); + } if !editable(d, parent) { return Err(HostError::Error("the layer or group is hidden or locked".into())); } @@ -2784,17 +2792,22 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { } refuse_protected_edit(h, item)?; selection_ids(h, item.doc, arg(a, 0))?; - let (before, after) = with_doc(h, item.doc, |_, st| { - let at = st.doc.position(item.id); - let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); - (at.map(|(_, i, _)| i), count) + // The Arrange commands keep a clipping path at the bottom of its parent and the art below the + // parent's ruler guides, so the item's place is counted among the art above the clipping path. + let (before, floor, art) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let at = d.position(item.id); + let parent = at.and_then(|(p, ..)| p); + let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips)); + let art = at.and_then(|(p, ..)| d.children(p)).map_or(0, |c| crate::doc::Node::guide_run_start(c)); + (at.map(|(_, i, _)| i), floor, art) }); let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) }; - let top = i + 1 >= after; - let unchanged = match id { - "object.arrange.bringToFront" | "object.arrange.bringForward" => top, - _ => i == 0, - }; + let unchanged = i < floor + || match id { + "object.arrange.bringToFront" | "object.arrange.bringForward" => i + 1 >= art, + _ => i <= floor, + }; if !unchanged { edit_item(h, item, id, &json!({"ids": [item.id.0]}))?; } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index e4f6bb203e..274edf78a1 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, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked +//! artboard. //! - 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,18 @@ 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)) } +/// Refuses a change to the path `id` that is hidden or locked, is in a hidden or locked layer or +/// group ([`cannot_edit`]), or is on a locked artboard, as the PageItem setters refuse one. +fn refuse_path_edit(h: &super::Host, st: &DocState, id: NodeId) -> std::result::Result<(), HostError> { + if !editable(&st.doc, id) { + return Err(cannot_edit(id)); + } + if super::on_locked_artboard(h, st, id) { + return Err(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0))); + } + Ok(()) +} + /// 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)?; @@ -234,7 +248,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 ([`refuse_path_edit`]), 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 { forget_waiting_starts(h); @@ -246,15 +260,13 @@ 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) + (pd.subpaths == subs, refuse_path_edit(h, st, item.id), aligned) })?; if !same { - if !ok { - return Err(cannot_edit(item.id)); - } + refused?; *h.dom.pending.borrow_mut() = Some((item, subs)); if aligned { flush(h)?; @@ -337,15 +349,12 @@ fn drawing_normally(h: &super::Host, f: impl FnOnce() -> T) -> T { } /// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which -/// must be one the user could edit. +/// must be one the user could edit ([`refuse_path_edit`]). /// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the /// 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)); - } + with_doc(h, item.doc, |_, st| refuse_path_edit(h, st, item.id))?; if let Some(o) = params.as_object_mut() { o.entry("ids").or_insert_with(|| json!([item.id.0])); } @@ -434,18 +443,25 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { } /// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked -/// path, or one in a hidden or locked layer or group, stops it before anything is deleted. +/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before +/// anything is deleted, as `PageItems.removeAll()` does. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = path_items(h, st); let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); - (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 paths: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 14878904fb..eb5a2ff667 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -895,6 +895,85 @@ fn a_path_inside_a_compound_path_is_not_reordered() { assert_eq!(out, vec![json!([1, 2])]); } +/// [`doc`] with `a`, `b` and a rectangle `c` on top made into a clip group `g`, clipped by `c`. The +/// page items are `g`, `b`, `a` and `c`, topmost first. +fn clip_group() -> (Session, NodeId, NodeId, NodeId, NodeId) { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 0.0, 0.0, 200.0, 200.0); + s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(children_of(&s, g), [c, a, b], "the clipping path is at the bottom"); + (s, g, a, b, c) +} + +/// The ids of the children of `id`, bottom first. +fn children_of(s: &Session, id: NodeId) -> Vec { + s.active().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect() +} + +#[test] +fn nothing_is_placed_below_a_clipping_path() { + let (mut s, g, a, b, c) = clip_group(); + let d = rect(&mut s, 300.0, 10.0, 5.0, 5.0); + s.execute("select.none", &json!({})).unwrap(); + let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); + // From outside the group, from above the clipping path inside it, and a copy. + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, mask = p[4], out = [];\ + var tries = [function () { p[0].move(mask, ElementPlacement.PLACEAFTER); },\ + function () { p[3].move(mask, ElementPlacement.PLACEAFTER); },\ + function () { p[0].duplicate(mask, ElementPlacement.PLACEAFTER); }];\ + for (var i = 0; i < tries.length; i++) { try { tries[i](); out.push('ran'); } catch (e) { out.push(e.message); } }\ + vc.log(out);", + ); + let messages = out[0].as_array().cloned().unwrap_or_default(); + assert_eq!(messages.len(), 3, "{out:?}"); + for m in &messages { + assert!(m.as_str().is_some_and(|m| m.contains("an object cannot go below a clipping mask")), "{out:?}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); + // Directly above the clipping path is allowed, and so is moving the clipping path beside itself. + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[4], ElementPlacement.PLACEBEFORE);"); + assert_eq!(children_of(&s, g), [c, d, a, b]); + let steps = undo_steps(&s); + log(&mut s, "var p = app.activeDocument.pageItems; p[4].move(p[4], ElementPlacement.PLACEAFTER);"); + assert_eq!((children_of(&s, g), undo_steps(&s)), (vec![c, d, a, b], steps)); +} + +#[test] +fn zorder_that_leaves_an_object_in_place_runs_no_command() { + // The topmost art of a layer with a ruler guide above it. + let (mut s, a, b) = doc(); + let layer = s.active().unwrap().doc.layers[0].id; + s.execute("guide.add", &json!({"vertical": true, "pos": 50, "layer": layer.0})).unwrap(); + let kids = s.active().unwrap().doc.layers[0].children().unwrap().clone(); + assert!(kids.len() == 3 && kids[2].is_ruler_guide(), "the guide is above the art"); + let steps = undo_steps(&s); + let r = + run(&mut s, "var p = app.activeDocument.pageItems; p[0].zOrder(ZOrderMethod.BRINGTOFRONT); p[0].zOrder(ZOrderMethod.BRINGFORWARD);").unwrap(); + assert_eq!((&r["slowestCommands"], undo_steps(&s)), (&json!([]), steps)); + assert_eq!(layer_order(&s)[..2], [a, b]); + // The lowest object above a clipping path, and the clipping path itself. + let (mut s, g, a, b, c) = clip_group(); + let steps = undo_steps(&s); + let r = run( + &mut s, + "var p = app.activeDocument.pageItems, ways = [ZOrderMethod.BRINGTOFRONT, ZOrderMethod.BRINGFORWARD,\ + ZOrderMethod.SENDBACKWARD, ZOrderMethod.SENDTOBACK];\ + p[2].zOrder(ZOrderMethod.SENDBACKWARD); p[2].zOrder(ZOrderMethod.SENDTOBACK);\ + for (var k = 0; k < ways.length; k++) p[3].zOrder(ways[k]);", + ) + .unwrap(); + assert_eq!((&r["slowestCommands"], undo_steps(&s)), (&json!([]), steps)); + assert_eq!(children_of(&s, g), [c, a, b]); + // A change still runs the command. + log(&mut s, "app.activeDocument.pageItems[1].zOrder(ZOrderMethod.SENDTOBACK);"); + assert_eq!((children_of(&s, g), undo_steps(&s)), (vec![c, b, a], steps + 1)); +} + #[test] fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() { let (mut s, a, b) = doc(); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 87f1c4f9ab..8988c042eb 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1480,6 +1480,34 @@ fn assigning_guides_refuses_paths_that_cannot_be_selected() { assert_eq!((is_guide(&s, a), undo_steps(&s)), (true, steps), "the guide stays a guide"); } +#[test] +fn path_changes_refuse_paths_on_a_locked_artboard() { + let (mut s, a, _) = doc(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let (before, steps) = (art(&s), undo_steps(&s)); + // Points (waiting and written at once), paint, stroke and a transform. + for change in [ + "p.closed = false;", + "p.pathPoints[0].anchor = [1, 2];", + "p.setEntirePath([[0, 0], [10, 10]]);", + "p.filled = false;", + "p.strokeWidth = 7;", + "p.translate(5, 5);", + ] { + let e = failure(&mut s, &format!("var p = app.activeDocument.pathItems[0]; {change}")); + assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", a.0)), "{change}: {e}"); + } + let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard"), "{e}"); + assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps)); + // A value the path has changes nothing and does not throw, and the path changes once the + // artboard is unlocked. + log(&mut s, "app.activeDocument.pathItems[0].closed = true;"); + s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].strokeWidth = 7;"); + assert_ne!(art(&s), before); +} + fn is_guide(s: &Session, id: NodeId) -> bool { matches!(node(s, id).kind, NodeKind::Path { guide: true, .. }) } diff --git a/docs/mcp.md b/docs/mcp.md index 3b647e4c7b..87a42a3e15 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3026,14 +3026,19 @@ through `$`: `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's or a group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` - directly below it. An object of another document throws `Cross-document placement is not available`, and when + directly below it. The clipping path of a clip group or clipping layer stays at its bottom: `PLACEATEND` puts the + object directly above the clipping path, and `PLACEAFTER` with the clipping path as the relative object throws + `an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). An object of + another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `hidden`, `locked`, `opacity`, `blendingMode`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer or on a locked artboard throws `Cannot edit` and changes nothing, even when the value is the one the object has, and `zOrder()` on such - an object throws `Cannot edit` too. The one exception is `opacity` or `blendingMode` given the value the object already has, which + an object throws `Cannot edit` too. `zOrder()` that would leave the object where it is runs no command: bringing + forward the topmost art of a layer whose ruler guides are above it, sending backward the lowest object above a + clipping path, or any method on the clipping path itself. The one exception is `opacity` or `blendingMode` given the value the object already has, which changes nothing and does not throw; on a graph's mark or label whose series or kind keeps another opacity or blend mode, that value would still change the graph, so it throws `Cannot edit` as well. Its `name` and `note` still change, and an object that is hidden or locked itself takes `hidden`, `locked`, `opacity` and `blendingMode` (VectorCraft's own rule). Position, @@ -3271,8 +3276,9 @@ 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, and `pathItems.removeAll()` when any path is on a locked artboard throws + `cannot delete objects on a locked artboard` and deletes nothing. 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` and the gradient stops are not available yet. From 1feb6c7f3884461aa6280c6eb8d54a2a029de396 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 18:18:59 -0800 Subject: [PATCH 44/72] Scripts: duplicate refuses a copy of a clipping path below itself mask.duplicate(mask, ElementPlacement.PLACEAFTER) put the copy directly above the clipping path without an error. A copy now goes through the same refusal as other objects; move of the clipping path below itself still leaves it where it is. --- crates/engine/src/script/dom.rs | 14 ++++++++------ crates/engine/src/tests/script_dom.rs | 8 +++++--- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 04285a3ca5..a041427e46 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2623,8 +2623,9 @@ struct Destination { /// The object a relative object of `move` or `duplicate` names: a page item or a layer of the /// same document as `item`. An object may go directly above or below itself: a copy goes there, as -/// `layer.move` puts copies, and a move there leaves the object where it is. -fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::Result { +/// `layer.move` puts copies, and a move there leaves the object where it is. A copy (`copy`) of a +/// clipping path cannot go below it. +fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result { let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); @@ -2657,9 +2658,10 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result:: (parent, Some(target)) } }; - // The clipping path stays at the bottom of its clip group or clipping layer. + // The clipping path stays at the bottom of its clip group or clipping layer. Moving the + // clipping path below itself leaves it where it is. if how == Placement::Below - && target != item.id + && (target != item.id || copy) && d.node(parent).is_some_and(crate::doc::Node::clips) && d.position(target).is_some_and(|(_, i, _)| i == 0) { @@ -2719,7 +2721,7 @@ fn item_move(h: &Host, a: &[Data]) -> Answer { if matches!(arg(a, 1), Data::Undefined) { return Err(HostError::Type("move needs a relative object".into())); } - let to = destination(h, item, arg(a, 1), arg(a, 2))?; + let to = destination(h, item, arg(a, 1), arg(a, 2), false)?; if to.beside != Some(item.id) { place(h, item.doc, item.id, &to)?; } @@ -2760,7 +2762,7 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { } None } - target => Some(destination(h, item, target, arg(a, 2))?), + target => Some(destination(h, item, target, arg(a, 2), true)?), }; let id = atomically(h, |h| { let (_, made) = on_doc(h, item.doc.uid, true, |h| command_value(h, "edit.duplicate", &json!({"ids": [item.id.0]})))?; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index eb5a2ff667..e7b53f8759 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -918,18 +918,20 @@ fn nothing_is_placed_below_a_clipping_path() { let d = rect(&mut s, 300.0, 10.0, 5.0, 5.0); s.execute("select.none", &json!({})).unwrap(); let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); - // From outside the group, from above the clipping path inside it, and a copy. + // From outside the group, from above the clipping path inside it, a copy, and a copy of the + // clipping path below itself. let out = log( &mut s, "var p = app.activeDocument.pageItems, mask = p[4], out = [];\ var tries = [function () { p[0].move(mask, ElementPlacement.PLACEAFTER); },\ function () { p[3].move(mask, ElementPlacement.PLACEAFTER); },\ - function () { p[0].duplicate(mask, ElementPlacement.PLACEAFTER); }];\ + function () { p[0].duplicate(mask, ElementPlacement.PLACEAFTER); },\ + function () { mask.duplicate(mask, ElementPlacement.PLACEAFTER); }];\ for (var i = 0; i < tries.length; i++) { try { tries[i](); out.push('ran'); } catch (e) { out.push(e.message); } }\ vc.log(out);", ); let messages = out[0].as_array().cloned().unwrap_or_default(); - assert_eq!(messages.len(), 3, "{out:?}"); + assert_eq!(messages.len(), 4, "{out:?}"); for m in &messages { assert!(m.as_str().is_some_and(|m| m.contains("an object cannot go below a clipping mask")), "{out:?}"); } From ab051030b760e0093ec4cda74391eb05f63e0ba5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 18:52:55 -0800 Subject: [PATCH 45/72] Docs: a clipping path moved below itself stays where it is --- docs/mcp.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 45b8f7a119..5be728a873 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3034,7 +3034,9 @@ through `$`: group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` directly below it. The clipping path of a clip group or clipping layer stays at its bottom: `PLACEATEND` puts the object directly above the clipping path, and `PLACEAFTER` with the clipping path as the relative object throws - `an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). An object of + `an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). The one exception + is `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself, which succeeds and leaves the + document unchanged; `mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or From aabae2d4b045084d65dbc4719bee8e1d579d7f7b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 19:45:32 -0800 Subject: [PATCH 46/72] Properties: show No Selection above the Document section instead of a second Document title With nothing selected, the panel heading and the first section were both titled Document. The heading now reads No Selection, and a test checks that Document is shown once. --- crates/ui-egui/src/panels/properties.rs | 5 +++-- crates/ui-egui/src/panels/properties/tests.rs | 13 +++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 70973df597..3ee8c24ce5 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -338,12 +338,13 @@ pub(crate) fn multi_color(app: &mut VectorcraftApp) -> bool { } /// The panel's heading: what the sections are for (the artboards with the Artboard tool, the -/// selected ruler guides, the document with nothing selected), else the selection's kind. +/// selected ruler guides), No Selection with nothing selected (the Document section follows it), else the +/// selection's kind. fn heading(first: Option<&vectorcraft_doc::Node>, n_sel: usize, editing_artboards: bool, guides: bool) -> String { match (first, n_sel) { _ if editing_artboards => tl!("Artboard").to_string(), (None, _) if guides => tl!("Guides").to_string(), - (None, _) => tl!("Document").to_string(), + (None, _) => tl!("No Selection").to_string(), (_, n) if n > 1 => crate::i18n::tn(n as u64, "{n} Object", "{n} Objects"), (Some(n), _) if crate::panels::image_trace::is_trace(n) => tl!("Image Tracing").to_string(), (Some(n), _) => tl!(n.kind_label()).to_string(), diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 96e9fc2cb0..97c9f1e9bb 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1605,6 +1605,19 @@ fn a_symbol_instance_turns_about_its_registration_point() { assert!(near(bx.reference_point(8), vectorcraft_geom::Point::new(200.0, 160.0)), "the registration point moved to {:?}", bx.reference_point(8)); } +/// With nothing selected the panel's heading is No Selection and "Document" appears once, as the +/// Document section's title, not also as the heading above it. +#[test] +fn nothing_selected_shows_document_once() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let mut panel = Panel::new(app, show); + panel.frame(); + assert!(panel.shows("No Selection")); + let documents = panel.texts().iter().filter(|(text, _)| text == "Document").count(); + assert_eq!(documents, 1, "\"Document\" is shown once"); +} + /// Ruler guides selected on their own (a click on one) show a Guides heading and a Transform /// section, where X moves the vertical ones and Y the horizontal ones; with art selected too, the /// panel shows the art's sections. From 947b74c9e9b62510a722eafa963e8d0e31a24323 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 20:30:09 -0800 Subject: [PATCH 47/72] Windows: a floating document window moves by its title bar and its tab closes it Where the app draws the window frame (Windows, and Linux with the integrated title bar), a document dragged out of the tab strip opened in an OS window with no title bar: the tab filled the top edge, so the window could only be resized, never moved. Its tab also had no close button. The floating window's tab now sits in a title bar. Dragging the bar's free area moves the window, and the bar shows the window's caption buttons. The tab keeps its close button, and a middle click on it closes the window as it does under the main strip. Windows with a system title bar, and the in-app window on the web and Wayland, keep their own title bars. --- crates/ui-egui/src/chrome/tabs.rs | 12 ++-- crates/ui-egui/src/doc_windows.rs | 17 ++++- crates/ui-egui/src/doc_windows/tests.rs | 86 ++++++++++++++++++++++++- 3 files changed, 106 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 4ba5c01293..c9b14eef54 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -158,11 +158,13 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { } /// The tab at the top of window `w`'s floating OS window ([`crate::doc_windows`]): a strip with the -/// window's tab, without its ×. Dragged onto the main strip it docks there ([`doc_tabs`]); the -/// window moves by its title bar, so a tear-off is ignored. → the strip's response. -pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, w: Win) -> egui::Response { - let tabs = [DocumentTab::new(w, document_window_title(app, w).unwrap_or_default()).closable(false)]; - DocumentTabs::new(tl!("Window"), &tabs).selected(w).reorderable(true).tear_off(true).large(app.session.prefs.large_tabs).show(ui).response +/// window's tab and its ×, as the tab has under the main strip. Dragged onto the main strip it +/// docks there ([`doc_tabs`]); the window moves by its title bar, so a tear-off is ignored. → +/// whether the tab's × or a middle click asked to close the window. +pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, w: Win) -> bool { + let tabs = [DocumentTab::new(w, document_window_title(app, w).unwrap_or_default())]; + let strip = DocumentTabs::new(tl!("Window"), &tabs).selected(w).reorderable(true).tear_off(true).large(app.session.prefs.large_tabs); + strip.show(ui).events.into_iter().any(|event| matches!(event, DocumentTabsEvent::CloseRequested(x) if x == w)) } /// Makes document `i` the current one, as a click on its tab does: the Home screen closes, and diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index b0b1a7c7d9..eb4e0b6522 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -18,7 +18,8 @@ use craft::ui::contract::{Props as _, ShowContainer as _}; use craft::ui::runtime::windows::WindowHost; -use craft::ui::shell::DocumentWindow; +use craft::ui::shell::{DocumentWindow, Frame, TitleBar}; +use craft::ui::style::SurfaceKind; use serde_json::{Value, json}; use crate::VectorcraftApp; @@ -446,6 +447,7 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let is_current = views::current(app) == Some(win); let live = is_current && !crate::menus::home_showing(app); let mut pressed = false; + let mut tab_close = false; let mut found = (None, None, false); let window = DocumentWindow::new(title).id_salt((w.uid, w.number, w.generation)).first_placed(w.place.translate(origin)); let window = if raise == Some((w.uid, w.view)) { window.raise() } else { window }; @@ -456,7 +458,16 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { } // A press anywhere on the window, its title bar and tab included, makes its document current. pressed = pressed_on_layer(ui); - crate::chrome::window_tab(app, ui, win); + // Where the app draws the OS window's frame, the tab sits in a title bar: its free area moves the + // window and its captions act on it. The fallback layer has a title row of its own. + let app_frame = !matches!(WindowHost::of(ui.ctx()).frame(), Frame::Native); + if ui.ctx().viewport_id() != egui::ViewportId::ROOT && app_frame { + let tab = |ui: &mut egui::Ui, _: &mut craft::ui::contract::BodyCx<'_>| tab_close |= crate::chrome::window_tab(app, ui, win); + let bar = TitleBar::new().surface(SurfaceKind::Background).show_fitted(ui, tab, |_, _| {}); + tab_close |= bar.close_requested; + } else { + tab_close = crate::chrome::window_tab(app, ui, win); + } let areas = [(win, ui.available_rect_before_wrap())]; let unfitted = crate::canvas::panes::refit_resized(app, &areas); // The display that shows the window, the size of its body and whether its view fits it in this frame. @@ -479,7 +490,7 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { x.place = placed.translate(-origin); } } - if out.close_requested.is_some() { + if out.close_requested.is_some() || tab_close { close = Some(win); } else if (out.focus_gained || pressed) && !is_current && !app.any_dialog_open() { activate = Some(win); diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 4e7905cb9f..2e86cf9552 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -602,12 +602,15 @@ fn a_document_made_current_in_presentation_mode_comes_to_the_front_after_it() { /// A stand-in for the window system of the documents' OS windows: it runs each one's frame and asks /// each to close while `close` is set. Each /// window is 500 × 400 points with its top-left corner at `origin` on the screen, and its next -/// frame takes `events`. +/// frame takes `events`. `commands` gathers the commands the windows' frames sent, and `strip` is where the last +/// window drew its tab strip, in its own points. #[derive(Default)] struct Host { close: bool, origin: Pos2, events: Vec, + commands: Vec, + strip: Option, } fn native_host() -> std::rc::Rc> { @@ -638,6 +641,14 @@ fn native_host() -> std::rc::Rc> { let input = egui::RawInput { viewport_id: id, viewports, screen_rect: Some(rect), events, ..Default::default() }; let mut full = ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui)); full.textures_delta.clear(); + let mut shared = shared.borrow_mut(); + shared.commands.extend(full.viewport_output.values().flat_map(|out| out.commands.iter().cloned())); + let nodes = full.platform_output.accesskit_update.as_ref().map_or(&[][..], |u| &u.nodes[..]); + let strip = + nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::TabList && n.label() == Some("Window")).and_then(|(_, n)| n.bounds()); + if let Some(b) = strip { + shared.strip = Some(egui::Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32))); + } }); host } @@ -666,6 +677,79 @@ fn closing_an_os_window_keeps_it_while_its_unsaved_document_stays_open() { assert_eq!(app.ui.floating.len(), 1, "its window is still shown"); } +/// [`crate::testing::ui_context`] with the frame the desktop host gives a window on Windows: no OS title bar, so the +/// app draws the title bar and its caption buttons. +fn integrated_frame_context() -> egui::Context { + use craft::window::policy::{Backend, Desktop, Os, Runtime, TitleBarPref, WindowKind, decide}; + let desktop = Desktop::detect(Backend::X11); + let decision = decide(Os::Windows, Runtime::Native, Backend::X11, &desktop, WindowKind::Main, TitleBarPref::Integrated, None); + assert!(matches!(decision.frame, Frame::Integrated(_)), "{:?}", decision.frame); + let ctx = egui::Context::default(); + craft::ui::shell::embed::install(&ctx, craft::ui::testing::install_spec().frame(decision), &crate::ui_fonts()).expect("the runtime installs"); + craft::ui::testing::windows::set_os(&ctx, Os::Windows); + let prefs = vectorcraft_engine::Prefs::default(); + let print = crate::state::print_ppi(prefs.display_print_size, None); + craft::ui::runtime::frame::set_input(&ctx, craft::ui::runtime::frame::FrameInput::new(crate::app::root_env(&prefs, 1.0, print))); + ctx +} + +/// A floating document's OS window without an OS title bar moves when the free part of the bar holding its tab is +/// dragged. +#[test] +fn a_floating_os_window_without_an_os_title_bar_moves_by_the_bar_of_its_tab() { + let host = native_host(); + let ctx = integrated_frame_context(); + ctx.set_embed_viewports(false); + let mut app = app_with(2); + if !WindowHost::of(&ctx).viewports_available() { + // Wayland: the windows are inside the main window, where the layer's title row moves them. + return; + } + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatInWindow", json!({"index": 1})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + host.borrow_mut().commands.clear(); + // Just right of the tab strip, on the bar's free band, in the window's own points. + let strip = host.borrow().strip.expect("the window drew its tab strip"); + let at = pos2(strip.right() + 8.0, strip.center().y); + let mut commands = Vec::new(); + for events in [ + vec![egui::Event::PointerMoved(at)], + vec![button(at, true)], + vec![egui::Event::PointerMoved(at + vec2(10.0, 4.0))], + vec![egui::Event::PointerMoved(at + vec2(30.0, 12.0))], + vec![button(at + vec2(30.0, 12.0), false)], + ] { + host.borrow_mut().events = events; + let out = run_frame(&mut app, &ctx, vec![]); + commands.extend(out.viewport_output.values().flat_map(|v| v.commands.iter().cloned())); + } + commands.append(&mut host.borrow_mut().commands); + assert!(commands.contains(&egui::ViewportCommand::StartDrag), "the drag moves the window: {commands:?}"); + assert!(is_floating(&app, 1), "the document still floats"); +} + +/// A floating document's tab keeps its close button: a middle click on it, as on a tab under the main strip, closes +/// the window and its document. +#[test] +fn a_floating_documents_tab_closes_its_window() { + let mut app = app_with(2); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatInWindow", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + let shapes = frame(&mut app, &ctx, vec![]); + let title = app.session.documents()[0].title(); + let tab = window_tab_at(&shapes, &title, window_of(&app, &ctx, 0)); + let middle = |pressed| egui::Event::PointerButton { pos: tab, button: egui::PointerButton::Middle, pressed, modifiers: egui::Modifiers::NONE }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(tab), middle(true)]); + frame(&mut app, &ctx, vec![middle(false)]); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.session.documents().len(), 1, "its document closed"); + assert!(app.ui.floating.is_empty(), "its window closed"); +} + /// The update prompt, opening on its own, takes the keyboard once from a document's OS window that /// has it, and leaves the keyboard alone when none of those windows has it. #[test] From 340bf84cb84ce4709968559a3509bf25dd1200df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 21:11:36 -0800 Subject: [PATCH 48/72] xtask: test-lint reports census tests A new report-only rule, census, lists tests that loop over a whole table (a SCREAMING_CASE constant, Type::ALL, Type::iter(), or a call named like a catalog such as presets() or all_swatches()) and assert only that each entry is present, non-empty, or parses back to itself. Such tests walk every color, swatch or preset and check a property each entry has by construction. Loops over a few entries (take, skip, filter, a slice), loops that call an asserting helper, and comparisons with an expected value written in the table are not reported. cargo xtask test-lint --all lists 53 census hits on main. --- xtask/src/test_lint.rs | 180 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 178 insertions(+), 2 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 8609ace2f5..0cb56cc31e 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -38,7 +38,13 @@ //! reads do not; //! * `sleep`: `thread::sleep` in test code, or a bare `sleep(…)` in a file that imports it; //! * `reads-source`: test code that reads Rust source (`include_str!` of a `.rs` file, or a walk -//! that keeps files ending in `.rs`), outside the source audits in [`SOURCE_AUDITS`]. +//! that keeps files ending in `.rs`), outside the source audits in [`SOURCE_AUDITS`]; +//! * `census`: a test that loops over a whole table (a `SCREAMING_CASE` constant, `Type::ALL`, +//! `Type::iter()`, or a call named `all`, `catalog`, `registry`, `presets`, `swatches`, +//! `entries`, `variants`, `commands`, `builtins` or `palette`, or ending or starting with one of +//! those after `_`) where every assertion in the loop only checks presence (`is_some`, `is_ok`, +//! `is_empty`, `contains`, `starts_with`, `is_finite`, `len() > 0`) or compares with a lookup or +//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table. //! //! Test code is a test file (`tests.rs`, `tests_*.rs`, `*_tests.rs`, a file in a `tests` or //! `benches` folder, `crates/testkit`), an item under `#[cfg(test)]` or `#[cfg(all(test, …))]`, @@ -120,10 +126,11 @@ pub enum Rule { EnvGateUnset, Sleep, ReadsSource, + Census, } impl Rule { - pub const ALL: [Rule; 10] = [ + pub const ALL: [Rule; 11] = [ Rule::AllUnguarded, Rule::OnlyWeak, Rule::SelfCompare, @@ -134,6 +141,7 @@ impl Rule { Rule::EnvGateUnset, Rule::Sleep, Rule::ReadsSource, + Rule::Census, ]; pub fn id(self) -> &'static str { @@ -148,6 +156,7 @@ impl Rule { Rule::EnvGateUnset => "env-gate-unset", Rule::Sleep => "sleep", Rule::ReadsSource => "reads-source", + Rule::Census => "census", } } @@ -163,6 +172,7 @@ impl Rule { Rule::EnvGateUnset => "set the variable in a CI leg, or make the test run without it", Rule::Sleep => "wait on a handshake (channel, barrier) or a controllable clock", Rule::ReadsSource => "test the behavior, or add the file to SOURCE_AUDITS in xtask/src/test_lint.rs if it audits the source tree", + Rule::Census => "test one or a few representative entries and the edge cases (or generate inputs), not every entry of the table", } } @@ -1230,6 +1240,7 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { hits.extend(self_compare(&v)); hits.extend(early_returns(&v)); hits.extend(env_gates(&v, ctx)); + hits.extend(census(&v, helpers)); hits.extend([only_weak(&v), exit_status_only(&v), no_assertion(&v)].into_iter().flatten()); hits } @@ -1320,6 +1331,134 @@ fn all_unguarded(v: &View) -> Vec { .collect() } +/// A loop over a whole table (`for x in TABLE`, `for c in Color::ALL`, `assert!(presets().iter().all(…))`) +/// whose assertions only check presence, non-emptiness or a round trip. +fn census(v: &View, helpers: &HashSet) -> Vec { + let m = &v.file.exec; + let weak_in = |from: usize, to: usize, var: &str| { + let inside: Vec<&MacroCall> = v.asserts.iter().filter(|a| a.at > from && a.at < to).collect(); + let helper = calls(m, from, to).iter().any(|(n, method)| !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)); + !helper + && !inside.is_empty() + && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm(&m[f..t])).collect::>(), var)) + }; + for at in words(m, b"for", v.t.open, v.t.close) { + let Some(&kw) = words(m, b"in", at, v.t.close).first() else { continue }; + let Some(open) = loop_open(m, kw + 2, v.t.close) else { continue }; + let Some(close) = matching(m, open) else { continue }; + let pattern = String::from_utf8_lossy(&m[at + 3..kw]); + let var = pattern.split_whitespace().last().unwrap_or("").trim_start_matches('&'); + if whole_table(&norm(&m[kw + 2..open])) && weak_in(open, close, var) { + return vec![v.whole(Rule::Census, "loops over every entry of a table and checks only presence or a round trip".into())]; + } + } + for a in v.asserts.iter().filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())) { + let cond = v.first_arg(a); + let Some(i) = cond.find(".all(") else { continue }; + let receiver = cond[..i].trim_end_matches(".iter()").trim_end_matches(".into_iter()"); + let rest = &cond[i + ".all(".len()..]; + let pred = &rest[..arg_end(rest)]; + if whole_table(receiver) && weak_predicate(pred) { + return vec![v.whole(Rule::Census, "checks .all(…) over every entry of a table for presence only".into())]; + } + } + vec![] +} + +/// The `{` that opens a `for` loop's body: the first one outside brackets after `from`. +fn loop_open(m: &[u8], from: usize, to: usize) -> Option { + let mut i = from; + while i < to { + match m[i] { + b'{' => return Some(i), + b'(' | b'[' => i = matching(m, i)? + 1, + b';' => return None, + _ => i += 1, + } + } + None +} + +/// Calls whose name says they return a whole table. +const TABLE_CALLS: &[&str] = &["all", "catalog", "registry", "presets", "swatches", "entries", "variants", "commands", "builtins", "palette"]; + +/// Whether a (whitespace-free) loop source names a whole table: a `SCREAMING_CASE` constant, an +/// `ALL`, `all()`, `iter()` or `variants()` on a type, or a call named like a catalog. +fn whole_table(src: &str) -> bool { + let src = src.trim_start_matches('&'); + let head: &str = src.split(['.', '(', '[']).next().unwrap_or(""); + let restricted = [".take(", ".skip(", ".filter(", ".step_by(", ".nth(", ".first(", ".last(", ".rev().take(", "["]; + if restricted.iter().any(|r| src[head.len()..].contains(r)) { + return false; + } + let last = head.rsplit("::").next().unwrap_or(""); + let screaming = last.len() > 1 + && last.bytes().any(|c| c.is_ascii_uppercase()) + && last.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_'); + let segments: Vec<&str> = head.split("::").collect(); + let on_type = segments.len() > 1 && segments[segments.len() - 2].starts_with(|c: char| c.is_ascii_uppercase()); + let type_table = on_type && matches!(last, "ALL" | "all" | "iter" | "variants" | "VARIANTS" | "value_variants"); + let named = src[head.len()..].starts_with("()") + && TABLE_CALLS.iter().any(|n| last == *n || last.ends_with(&format!("_{n}")) || last.starts_with(&format!("{n}_"))); + screaming || type_table || named +} + +/// Predicates and comparisons that every entry passes by construction. +const PRESENCE: &[&str] = &[".is_some()", ".is_ok()", ".is_empty()", ".contains(", ".contains_key(", ".len()>0", ".starts_with(", ".is_finite()"]; + +/// Calls on one side of an equality that turn an entry back into itself. +const ROUND_TRIP: &[&str] = &["parse", "from_str", "from_id", "from_name", "from_key", "by_id", "by_name", "lookup", "find"]; + +/// Whether every operand of a (whitespace-free) condition or closure is a presence check alone. +fn weak_predicate(pred: &str) -> bool { + let pred = pred.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(pred, |(_, body)| body); + if pred.starts_with('(') && matching(pred.as_bytes(), 0) == Some(pred.len() - 1) { + return weak_predicate(&pred[1..pred.len() - 1]); + } + if let Some(at) = boolean_split(pred) { + return weak_predicate(&pred[..at]) && weak_predicate(&pred[at + 2..]); + } + let pred = pred.trim_start_matches('!'); + if let Some(list) = pred.strip_suffix(".len()>0") { + return !list.contains(['=', '<', '>']); + } + let compares = pred.contains("==") || pred.contains("!=") || pred.contains(['<', '>']) && !pred.contains("::<"); + !compares + && PRESENCE.iter().any(|p| match p.strip_suffix('(') { + Some(call) => pred.rfind(p).is_some_and(|at| matching(pred.as_bytes(), at + call.len()) == Some(pred.len() - 1)), + None => pred.ends_with(p), + }) +} + +/// Whether an assertion in a loop over entries bound to `var` checks only presence, or compares +/// a lookup or parse with the entry itself. +fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { + match guard_arg_count(name) { + 1 => args.first().is_some_and(|a| weak_predicate(a)), + 2 => match args { + [a, b, ..] => (round_trip_call(a) && is_entry(b, var)) || (round_trip_call(b) && is_entry(a, var)), + _ => false, + }, + _ => false, + } +} + +/// Whether a (whitespace-free) operand calls one of [`ROUND_TRIP`] by its whole name. +fn round_trip_call(op: &str) -> bool { + ROUND_TRIP.iter().any(|r| op.match_indices(&format!("{r}(")).any(|(at, _)| !op.as_bytes()[..at].last().copied().is_some_and(is_ident))) +} + +/// Whether an operand is the loop entry itself: `x`, `*x`, `&x`, `Some(x)`, `Ok(x)` or `x.clone()`. +fn is_entry(op: &str, var: &str) -> bool { + let mut op = op.trim_start_matches(['&', '*']); + for wrap in ["Some(", "Ok("] { + if let Some(inner) = op.strip_prefix(wrap).and_then(|r| r.strip_suffix(')')) { + op = inner.trim_start_matches(['&', '*']); + } + } + !var.is_empty() && op.trim_end_matches(".clone()") == var +} + /// The number of condition or compared operands in a standard assertion macro. fn guard_arg_count(name: &str) -> usize { match name { @@ -2618,6 +2757,43 @@ mod tests { assert_eq!(hits(mixed), [(3, "all-unguarded")]); } + #[test] + fn census_loops_over_whole_tables_are_reported() { + let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let consts = "#[test]\nfn t() {\n for c in COLORS.iter() {\n assert!(!c.name.is_empty());\n }\n}\n"; + assert_eq!(census(consts), [(2, "census")]); + let round = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id()), Some(k));\n }\n}\n"; + assert_eq!(census(round), [(2, "census")]); + let call = "#[test]\nfn t() {\n for p in builtin_presets() {\n assert!(lookup(&p.name).is_some());\n }\n}\n"; + assert_eq!(census(call), [(2, "census")]); + let all = "#[test]\nfn t() {\n assert!(Swatch::iter().all(|s| s.rgb().is_some()));\n}\n"; + assert_eq!(census(all), [(2, "census")]); + let behavior = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(apply(k, 2), 4);\n }\n}\n"; + assert_eq!(census(behavior), [], "a computed result for each entry is a real check"); + let mixed = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some());\n assert_eq!(blend(c), WHITE);\n }\n}\n"; + assert_eq!(census(mixed), [], "one real assertion in the loop keeps it"); + let joined = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some() && blend(c) == WHITE);\n }\n assert!(Swatch::iter().all(|s| s.rgb().is_some() && s.rgb() != BLACK));\n}\n"; + assert_eq!(census(joined), [], "a presence guard joined to a real check"); + let both = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some() && !c.name.is_empty());\n }\n}\n"; + assert_eq!(census(both), [(2, "census")]); + let few = "#[test]\nfn t() {\n for c in COLORS.iter().take(2) {\n assert!(c.is_some());\n }\n for c in &COLORS[..2] {\n assert!(c.is_some());\n }\n}\n"; + assert_eq!(census(few), [], "a few representative entries"); + let expected = "#[test]\nfn t() {\n for case in CASES {\n assert_eq!(parse(case.input), case.expected);\n assert_eq!(sparse(case), case);\n }\n}\n"; + assert_eq!(census(expected), [], "an expected value written in the table, and a name that only ends in parse"); + let helper = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some());\n check_render(c);\n }\n}\n"; + assert_eq!(census(helper), [], "an asserting helper in the loop"); + let local = "#[test]\nfn t() {\n for x in xs.iter() {\n assert!(x.is_some());\n }\n}\n"; + assert_eq!(census(local), [], "a local collection is not a table"); + let allowed = "// test-lint: allow census every command needs a menu path\n#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c).is_some());\n }\n}\n"; + assert_eq!(census(allowed), []); + } + + #[test] + fn census_is_report_only() { + assert!(!Rule::Census.fails()); + assert_eq!(Rule::from_id("census"), Some(Rule::Census)); + } + #[test] fn all_equality_guards_match_each_receiver() { for assertion in ["assert_eq", "debug_assert_eq", "prop_assert_eq"] { From aa44d2a3a0a5fd3746f31d82576baa279d204fcc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 21:53:52 -0800 Subject: [PATCH 49/72] xtask: census skips inequalities, derived values and subset loops - assert_ne!, debug_assert_ne! and prop_assert_ne! in a table loop are not round trips. - A round trip counts only when the compared operand is the parsed or looked-up entry itself, optionally unwrapped, borrowed or wrapped in Some(...); parse(..).unwrap().children.len() is a real check. - An .all(...) presence check over a table is reported only when the whole condition holds on presence checks: joined by && to a real check it is not reported, while an || that lets the presence branch pass alone still is. - filter_map, take_while, skip_while and map_while pick a subset, as do a bounded iterator zipped in or returned by flat_map. Adapters inside a closure on the outer chain do not count. --- xtask/src/test_lint.rs | 166 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 156 insertions(+), 10 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 0cb56cc31e..2a839af6be 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1353,18 +1353,47 @@ fn census(v: &View, helpers: &HashSet) -> Vec { } } for a in v.asserts.iter().filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())) { - let cond = v.first_arg(a); - let Some(i) = cond.find(".all(") else { continue }; - let receiver = cond[..i].trim_end_matches(".iter()").trim_end_matches(".into_iter()"); - let rest = &cond[i + ".all(".len()..]; - let pred = &rest[..arg_end(rest)]; - if whole_table(receiver) && weak_predicate(pred) { + if census_condition(&v.first_arg(a), 0) == (true, true) { return vec![v.whole(Rule::Census, "checks .all(…) over every entry of a table for presence only".into())]; } } vec![] } +/// For a (whitespace-free) assertion condition: whether it holds on presence checks alone, and +/// whether one of those is a [`weak_table_all`]. Operands joined by `&&` all have to be weak, while +/// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions +/// nested deeper than 64 operators are not judged. +fn census_condition(cond: &str, depth: usize) -> (bool, bool) { + if depth > 64 || !cond.contains(".all(") { + return (false, false); + } + if cond.starts_with('(') && matching(cond.as_bytes(), 0) == Some(cond.len() - 1) { + return census_condition(&cond[1..cond.len() - 1], depth + 1); + } + let or = top_level_at(cond, "||").first().copied(); + if let Some(at) = or.or_else(|| top_level_at(cond, "&&").first().copied()) { + let side = |s: &str| if s.contains(".all(") { census_condition(s, depth + 1) } else { (weak_predicate(s), false) }; + let (l, r) = (side(&cond[..at]), side(&cond[at + 2..])); + return if or.is_some() { + if l == (true, true) || r == (true, true) { (true, true) } else { (l.0 || r.0, false) } + } else { + (l.0 && r.0, l.1 || r.1) + }; + } + let table = weak_table_all(cond); + (table || weak_predicate(cond), table) +} + +/// Whether a (whitespace-free) operand is exactly `TABLE.iter().all(…)` with a presence-only predicate. +fn weak_table_all(op: &str) -> bool { + let Some(&i) = top_level_at(op, ".all(").last() else { return false }; + let receiver = op[..i].trim_end_matches(".iter()").trim_end_matches(".into_iter()"); + let rest = &op[i + ".all(".len()..]; + let end = arg_end(rest); + rest[end..] == *")" && whole_table(receiver) && weak_predicate(&rest[..end]) +} + /// The `{` that opens a `for` loop's body: the first one outside brackets after `from`. fn loop_open(m: &[u8], from: usize, to: usize) -> Option { let mut i = from; @@ -1387,8 +1416,31 @@ const TABLE_CALLS: &[&str] = &["all", "catalog", "registry", "presets", "swatche fn whole_table(src: &str) -> bool { let src = src.trim_start_matches('&'); let head: &str = src.split(['.', '(', '[']).next().unwrap_or(""); - let restricted = [".take(", ".skip(", ".filter(", ".step_by(", ".nth(", ".first(", ".last(", ".rev().take(", "["]; - if restricted.iter().any(|r| src[head.len()..].contains(r)) { + let restricted = [ + ".take(", + ".skip(", + ".filter(", + ".filter_map(", + ".take_while(", + ".skip_while(", + ".map_while(", + ".step_by(", + ".nth(", + ".first(", + ".last(", + ".rev().take(", + "[", + ]; + let chain = &src[head.len()..]; + // A `zip` stops at its shorter side and a `flat_map` yields what its closure's iterator yields, + // so a restricted iterator inside either bounds the loop too. + let bounded_inside = [".zip(", ".flat_map("].iter().any(|adapter| { + top_level_at(chain, adapter).into_iter().any(|at| { + let open = at + adapter.len() - 1; + matching(chain.as_bytes(), open).is_none_or(|close| restricted.iter().any(|r| chain[open + 1..close].contains(r))) + }) + }); + if bounded_inside || restricted.iter().any(|r| top_level_contains(chain, r)) { return false; } let last = head.rsplit("::").next().unwrap_or(""); @@ -1403,6 +1455,30 @@ fn whole_table(src: &str) -> bool { screaming || type_table || named } +/// Whether `pat` starts at a position of `s` outside every bracket, so an adapter inside a closure +/// does not count as one on the outer iterator chain. +fn top_level_contains(s: &str, pat: &str) -> bool { + !top_level_at(s, pat).is_empty() +} + +/// The byte offsets where `pat` starts in `s` outside every bracket. +fn top_level_at(s: &str, pat: &str) -> Vec { + let (s, pat) = (s.as_bytes(), pat.as_bytes()); + let mut depth = 0i32; + let mut found = vec![]; + for (i, c) in s.iter().enumerate() { + if depth == 0 && s[i..].starts_with(pat) { + found.push(i); + } + depth += match c { + b'(' | b'[' | b'{' => 1, + b')' | b']' | b'}' => -1, + _ => 0, + }; + } + found +} + /// Predicates and comparisons that every entry passes by construction. const PRESENCE: &[&str] = &[".is_some()", ".is_ok()", ".is_empty()", ".contains(", ".contains_key(", ".len()>0", ".starts_with(", ".is_finite()"]; @@ -1435,6 +1511,7 @@ fn weak_predicate(pred: &str) -> bool { fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { match guard_arg_count(name) { 1 => args.first().is_some_and(|a| weak_predicate(a)), + 2 if name.ends_with("_ne") => false, 2 => match args { [a, b, ..] => (round_trip_call(a) && is_entry(b, var)) || (round_trip_call(b) && is_entry(a, var)), _ => false, @@ -1443,9 +1520,43 @@ fn weak_census_check(name: &str, args: &[String], var: &str) -> bool { } } -/// Whether a (whitespace-free) operand calls one of [`ROUND_TRIP`] by its whole name. +/// Whether a (whitespace-free) operand is the result of one of [`ROUND_TRIP`], called by its whole +/// name and followed only by unwrapping (`.unwrap()`, `.ok()`, `.expect(…)`, `?` and the like), so +/// the operand is the parsed or looked-up entry itself and not a value derived from it. fn round_trip_call(op: &str) -> bool { - ROUND_TRIP.iter().any(|r| op.match_indices(&format!("{r}(")).any(|(at, _)| !op.as_bytes()[..at].last().copied().is_some_and(is_ident))) + let mut op = op.trim_start_matches(['&', '*']); + loop { + let wraps = |w: &&str| op.starts_with(*w) && matching(op.as_bytes(), w.len() - 1) == Some(op.len() - 1); + let inner = ["Some(", "Ok(", "("].iter().find(|w| wraps(w)).map(|w| &op[w.len()..op.len() - 1]); + match inner { + Some(inner) => op = inner.trim_start_matches(['&', '*']), + None => break, + } + } + ROUND_TRIP.iter().any(|r| { + op.match_indices(&format!("{r}(")).any(|(at, _)| { + let open = at + r.len(); + !op.as_bytes()[..at].last().copied().is_some_and(is_ident) + && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..])) + }) + }) +} + +/// Whether a (whitespace-free) call suffix only unwraps or copies the call's result. +fn only_unwraps(mut rest: &str) -> bool { + const UNWRAPS: &[&str] = &[".unwrap()", ".ok()", ".copied()", ".cloned()", ".clone()", ".as_ref()", ".as_deref()", "?"]; + loop { + let next = match UNWRAPS.iter().find_map(|s| rest.strip_prefix(s)) { + Some(r) => Some(r), + None if rest.starts_with(".expect(") => matching(rest.as_bytes(), ".expect".len()).map(|close| &rest[close + 1..]), + None => None, + }; + match next { + _ if rest.is_empty() => break true, + Some(r) => rest = r, + None => break false, + } + } } /// Whether an operand is the loop entry itself: `x`, `*x`, `&x`, `Some(x)`, `Ok(x)` or `x.clone()`. @@ -2786,6 +2897,41 @@ mod tests { assert_eq!(census(local), [], "a local collection is not a table"); let allowed = "// test-lint: allow census every command needs a menu path\n#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c).is_some());\n }\n}\n"; assert_eq!(census(allowed), []); + for ne in ["assert_ne!(Kind::from_id(k.id()), Some(k))", "debug_assert_ne!(lookup(k), k)", "prop_assert_ne!(Kind::parse(k.name()), Ok(k))"] { + let rejects = format!("#[test]\nfn t() {{\n for k in Kind::ALL {{\n {ne};\n }}\n}}\n"); + assert_eq!(census(&rejects), [], "an inequality is not a round trip: {ne}"); + } + let borrowed = "#[test]\nfn t() {\n for k in &Kind::ALL {\n assert_eq!(Kind::from_id(k.id()).as_ref(), Some(k));\n }\n}\n"; + assert_eq!(census(borrowed), [(2, "census")]); + let both_all = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) && LABELS.iter().all(|s| !s.is_empty()));\n}\n"; + assert_eq!(census(both_all), [(2, "census")]); + let either = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) || actual == expected);\n}\n"; + assert_eq!(census(either), [(2, "census")], "an || lets the presence branch pass alone"); + let long = format!( + "#[test]\nfn t() {{\n assert!(COLORS.iter().all(|c| c.is_some()){});\n}}\n", + "&&COLORS.iter().all(|c|c.is_some())".repeat(200) + ); + assert_eq!(census(&long), [], "a chain deeper than the limit is not judged"); + let inner = "#[test]\nfn t() {\n for a in COLORS.iter().map(|c| c.aliases.iter().filter_map(|a| a.id()).next()) {\n assert!(a.is_some());\n }\n}\n"; + assert_eq!(census(inner), [(2, "census")]); + let accented = "#[test]\nfn t() {\n for c in COLORS.iter().clonés() {\n assert!(c.is_some());\n }\n}\n"; + assert_eq!(census(accented), [(2, "census")], "a non-ASCII method name is read without panicking"); + let zipped = "#[test]\nfn t() {\n for (c, l) in COLORS.iter().zip(labels.iter().take(2)) {\n assert!(c.is_some());\n }\n}\n"; + assert_eq!(census(zipped), [], "a bounded iterator zipped in bounds the loop"); + let flat = "#[test]\nfn t() {\n for e in GROUPS.iter().flat_map(|g| g.es.iter().take(1)) {\n assert!(e.is_some());\n }\n}\n"; + assert_eq!(census(flat), [], "a bounded iterator returned by flat_map bounds the loop"); + let nested = "#[test]\nfn t() {\n assert!(COLORS.iter().map(|c| c.parts.iter().all(|p| p.ok)).all(|c| c.is_some()));\n}\n"; + assert_eq!(census(nested), [(2, "census")]); + let wrapped = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Some(Kind::parse(k.name()).unwrap()), Some(k));\n }\n}\n"; + assert_eq!(census(wrapped), [(2, "census")]); + let derived = "#[test]\nfn t() {\n for n in COUNTS {\n assert_eq!(parse(&src(n)).unwrap().children.len(), n);\n }\n}\n"; + assert_eq!(census(derived), [], "a value derived from the parsed entry is a real check"); + let unwrapped = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::parse(k.name()).unwrap(), k);\n }\n}\n"; + assert_eq!(census(unwrapped), [(2, "census")]); + let all_joined = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) && actual == expected);\n}\n"; + assert_eq!(census(all_joined), [], "an .all(…) presence check joined to a real check"); + let subsets = "#[test]\nfn t() {\n for c in COLORS.iter().filter_map(|c| c.alt) {\n assert!(c.is_some());\n }\n for c in COLORS.iter().take_while(|c| c.light) {\n assert!(c.is_some());\n }\n for c in COLORS.iter().skip_while(|c| c.light) {\n assert!(c.is_some());\n }\n for c in COLORS.iter().map_while(|c| c.alt) {\n assert!(c.is_some());\n }\n}\n"; + assert_eq!(census(subsets), [], "subset adapters pick a few entries"); } #[test] From 2a2d8e1cabcb9c1e213caac4cb1fbf6b7da064df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 21:59:52 -0800 Subject: [PATCH 50/72] Tests: Color Effects history names check two adjustments in two languages history_names_a_filter_step_as_the_panel_names_its_adjustment walked every adjustment through the panel in every language. It now checks Levels, which has fields and whose German panel and menu names differ, and Desaturate, which has none, in English and German. --- crates/ui-egui/src/addons/color/tests.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/addons/color/tests.rs b/crates/ui-egui/src/addons/color/tests.rs index 506327e399..faaaca43fa 100644 --- a/crates/ui-egui/src/addons/color/tests.rs +++ b/crates/ui-egui/src/addons/color/tests.rs @@ -64,10 +64,13 @@ fn every_adjustment_offered_is_a_colour_adjustment_with_its_defaults() { } /// Apply as Filter records a step that History and Edit › Undo name as the panel names the -/// adjustment, in every language (German's plain `Levels` row and its Effect menu row differ). +/// adjustment: Levels, which has fields, and Desaturate, which has none, in English and German +/// (German's plain `Levels` row and its Effect menu row differ). #[test] fn history_names_a_filter_step_as_the_panel_names_its_adjustment() { - for (i, (id, _, fields)) in ADJUSTMENTS.iter().enumerate() { + let pick = |want: &str| ADJUSTMENTS.iter().position(|a| a.0 == want).expect("an adjustment"); + for i in [pick("adjust.levels"), pick("addon.color.desaturate")] { + let (id, _, fields) = &ADJUSTMENTS[i]; let mut app = app(); app.run("paint.setFill", json!({"color": "#806040"})).unwrap(); let (_, mut params) = Picked { index: i, ..Picked::default() }.params(); @@ -82,7 +85,7 @@ fn history_names_a_filter_step_as_the_panel_names_its_adjustment() { let shown = std::rc::Rc::clone(&app); let mut fixture = craft::ui::testing::Fixture::new(move |ui| super::show(&mut shown.borrow_mut(), ui)); fixture.room(egui::vec2(320.0, 700.0)); - for lang in crate::i18n::Lang::all() { + for lang in [crate::i18n::Lang::EN, crate::i18n::Lang::from_code("de").expect("German")] { crate::i18n::set_current(lang); let step = crate::panels::history::shown(&h); fixture.settle(); From 0ef22709c16b492cce4871f54aa8a8e4a5a619c7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 22:29:00 -0800 Subject: [PATCH 51/72] Cursors: tool cursors keep their size under UI Scaling unless Scale Cursor Proportional to UI is on The Scale Cursor Proportional to UI preference was never passed to the interface, so painted tool cursors always grew with UI Scaling and showed twice as large at 200%. The preference now decides it, and it is off by default. --- crates/ui-egui/src/app.rs | 2 ++ crates/ui-egui/src/canvas/tests_ui_scaling.rs | 11 +++++++++++ 2 files changed, 13 insertions(+) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 34bad16a79..30569c59d5 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -776,6 +776,8 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print let (theme, mode, accent) = theme::root_theme(prefs); let scaling = applied_ui_scaling(prefs.ui_scaling); let mut root = RootEnv::new().theme(theme).mode(mode).accent(accent).scale(Scale::new(scaling)).tooltips(prefs.show_tool_tips); + // Painted tool cursors grow with UI Scaling only when Scale Cursor Proportional to UI is on. + root = root.cursor_follows_zoom(prefs.scale_cursor_with_ui); root.sizes = theme::app_sizes(); root.values.set(view::zoom_scheme(print, native_ppp)); root.values.set(if prefs.scrub_numeric_fields { ScrubDrags::LabelOnly } else { ScrubDrags::Off }); diff --git a/crates/ui-egui/src/canvas/tests_ui_scaling.rs b/crates/ui-egui/src/canvas/tests_ui_scaling.rs index 64dca524b3..52f2247f42 100644 --- a/crates/ui-egui/src/canvas/tests_ui_scaling.rs +++ b/crates/ui-egui/src/canvas/tests_ui_scaling.rs @@ -93,6 +93,17 @@ fn pixel_preview_compares_a_document_pixel_with_a_device_pixel() { } } +/// Painted tool cursors keep their size under UI Scaling unless Scale Cursor Proportional to UI +/// is on. +#[test] +fn tool_cursors_follow_ui_scaling_only_with_the_cursor_preference() { + let mut prefs = vectorcraft_engine::Prefs { ui_scaling: 2.0, ..vectorcraft_engine::Prefs::default() }; + assert!(!prefs.scale_cursor_with_ui, "the preference starts off"); + assert!(!crate::app::root_env(&prefs, 1.0, None).cursor_follows_zoom, "off: the cursor keeps its size at 200%"); + prefs.scale_cursor_with_ui = true; + assert!(crate::app::root_env(&prefs, 1.0, None).cursor_follows_zoom, "on: the cursor grows with the interface"); +} + #[test] fn out_of_range_saved_ui_scaling_keeps_actual_size_correct() { let (a, b) = (Point::new(100.0, 100.0), Point::new(228.0, 100.0)); From 7f6ff4d60e46f2399e5fdf7d5b86302179b4cd21 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 22:43:05 -0800 Subject: [PATCH 52/72] xtask: census counts rejections and asserting helpers as checks A loop over a table that also calls unwrap_err or expect_err checks that some inputs are rejected, so it is no longer reported as census. Calls in failure messages do not count, and a panic! that only enforces success does not exempt the loop. An asserting helper called in an .all(...) predicate also counts as a check, unless a presence check can pass without the helper running (the other side of an ||). Helpers called with a turbofish are matched too. --- xtask/src/test_lint.rs | 125 +++++++++++++++++++++++++++++++++-------- 1 file changed, 103 insertions(+), 22 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 2a839af6be..205724eee0 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1335,10 +1335,21 @@ fn all_unguarded(v: &View) -> Vec { /// whose assertions only check presence, non-emptiness or a round trip. fn census(v: &View, helpers: &HashSet) -> Vec { let m = &v.file.exec; + // Failure messages run only after an assertion has failed, so a check there does not count. + let unmessaged = v.body_without_messages(); + let helpers_in = |from: usize, to: usize| -> Vec { + calls(&unmessaged, from - v.t.open, to - v.t.open) + .into_iter() + .filter(|(n, method)| !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)) + .map(|(n, _)| n) + .collect() + }; let weak_in = |from: usize, to: usize, var: &str| { let inside: Vec<&MacroCall> = v.asserts.iter().filter(|a| a.at > from && a.at < to).collect(); - let helper = calls(m, from, to).iter().any(|(n, method)| !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)); - !helper + let body = &unmessaged[from - v.t.open..to - v.t.open]; + let rejects = contains(body, b".unwrap_err()") || contains(body, b".expect_err("); + helpers_in(from, to).is_empty() + && !rejects && !inside.is_empty() && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm(&m[f..t])).collect::>(), var)) }; @@ -1353,7 +1364,8 @@ fn census(v: &View, helpers: &HashSet) -> Vec { } } for a in v.asserts.iter().filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())) { - if census_condition(&v.first_arg(a), 0) == (true, true) { + let called = a.args.first().map(|&(f, t)| helpers_in(f, t)).unwrap_or_default(); + if census_condition(&v.first_arg(a), 0, &called) == (true, true) { return vec![v.whole(Rule::Census, "checks .all(…) over every entry of a table for presence only".into())]; } } @@ -1363,35 +1375,73 @@ fn census(v: &View, helpers: &HashSet) -> Vec { /// For a (whitespace-free) assertion condition: whether it holds on presence checks alone, and /// whether one of those is a [`weak_table_all`]. Operands joined by `&&` all have to be weak, while /// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions -/// nested deeper than 64 operators are not judged. -fn census_condition(cond: &str, depth: usize) -> (bool, bool) { - if depth > 64 || !cond.contains(".all(") { - return (false, false); - } - if cond.starts_with('(') && matching(cond.as_bytes(), 0) == Some(cond.len() - 1) { - return census_condition(&cond[1..cond.len() - 1], depth + 1); - } +/// nested deeper than 64 operators are not judged. An operand that calls one of `helpers` (asserting +/// helpers called in the condition) is not a presence check, and a weak right side of an `||` does +/// not count when the left side calls one, since the left side always runs. +fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool) { let or = top_level_at(cond, "||").first().copied(); - if let Some(at) = or.or_else(|| top_level_at(cond, "&&").first().copied()) { - let side = |s: &str| if s.contains(".all(") { census_condition(s, depth + 1) } else { (weak_predicate(s), false) }; - let (l, r) = (side(&cond[..at]), side(&cond[at + 2..])); - return if or.is_some() { - if l == (true, true) || r == (true, true) { (true, true) } else { (l.0 || r.0, false) } - } else { - (l.0 && r.0, l.1 || r.1) + if depth > 64 || !cond.contains(".all(") { + (false, false) + } else if cond.starts_with('(') && matching(cond.as_bytes(), 0) == Some(cond.len() - 1) { + census_condition(&cond[1..cond.len() - 1], depth + 1, helpers) + } else if let Some(at) = or.or_else(|| top_level_at(cond, "&&").first().copied()) { + let side = |s: &str| { + if s.contains(".all(") { census_condition(s, depth + 1, helpers) } else { (weak_predicate(s) && !calls_any(s, helpers), false) } }; + let (l, r) = (side(&cond[..at]), side(&cond[at + 2..])); + let r = if or.is_some() && calls_any(&cond[..at], helpers) { (false, false) } else { r }; + if or.is_none() { + (l.0 && r.0, l.1 || r.1) + } else if l == (true, true) || r == (true, true) { + (true, true) + } else { + (l.0 || r.0, false) + } + } else { + let table = weak_table_all(cond, helpers); + (table || weak_predicate(cond) && !calls_any(cond, helpers), table) + } +} + +/// Whether `s` calls a function or method named in `names`, with or without a turbofish. +fn calls_any(s: &str, names: &[String]) -> bool { + names.iter().any(|n| { + [format!("{n}("), format!("{n}::<")] + .iter() + .any(|call| s.match_indices(call.as_str()).any(|(at, _)| at == 0 || !is_ident(s.as_bytes()[at - 1]))) + }) +} + +/// Whether a (whitespace-free) `.all(…)` predicate checks only presence. A predicate that calls one +/// of `helpers` is weak only when a presence check can pass without the helper running: a weak left +/// side of an `||`, a weak right side after a left side that calls no helper, or weak operands on +/// both sides of an `&&`. +fn presence_only(pred: &str, helpers: &[String], depth: usize) -> bool { + let body = pred.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(pred, |(_, body)| body); + let (or, and) = (top_level_at(body, "||").first().copied(), top_level_at(body, "&&").first().copied()); + if !calls_any(pred, helpers) { + weak_predicate(pred) + } else if depth > 64 { + false + } else if body.starts_with('(') && matching(body.as_bytes(), 0) == Some(body.len() - 1) { + presence_only(&body[1..body.len() - 1], helpers, depth + 1) + } else if let Some(at) = or { + let left = &body[..at]; + presence_only(left, helpers, depth + 1) || !calls_any(left, helpers) && presence_only(&body[at + 2..], helpers, depth + 1) + } else if let Some(at) = and { + presence_only(&body[..at], helpers, depth + 1) && presence_only(&body[at + 2..], helpers, depth + 1) + } else { + false } - let table = weak_table_all(cond); - (table || weak_predicate(cond), table) } /// Whether a (whitespace-free) operand is exactly `TABLE.iter().all(…)` with a presence-only predicate. -fn weak_table_all(op: &str) -> bool { +fn weak_table_all(op: &str, helpers: &[String]) -> bool { let Some(&i) = top_level_at(op, ".all(").last() else { return false }; let receiver = op[..i].trim_end_matches(".iter()").trim_end_matches(".into_iter()"); let rest = &op[i + ".all(".len()..]; let end = arg_end(rest); - rest[end..] == *")" && whole_table(receiver) && weak_predicate(&rest[..end]) + rest[end..] == *")" && whole_table(receiver) && presence_only(&rest[..end], helpers, 0) } /// The `{` that opens a `for` loop's body: the first one outside brackets after `from`. @@ -2934,6 +2984,37 @@ mod tests { assert_eq!(census(subsets), [], "subset adapters pick a few entries"); } + #[test] + fn census_counts_rejections_and_helpers_as_checks() { + let census_in = |src: &str, ctx: &Ctx| hits_in("crates/x/src/tests.rs", src, ctx).into_iter().filter(|h| h.1 == "census").collect::>(); + let rejected = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).unwrap_err();\n }\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).expect_err(\"rejects\");\n }\n}\n"; + assert_eq!(census_in(rejected, &ctx()), [], "an unwrap_err or expect_err in the loop checks a rejection"); + let only_ok = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n }\n}\n"; + assert_eq!(census_in(only_ok, &ctx()), [(2, "census")]); + let all_helper = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| exercise(c).is_some()));\n}\nfn exercise(c: &Color) -> Option<()> {\n assert_eq!(blend(c), WHITE);\n Some(())\n}\n"; + let files = [("crates/x/src/tests.rs".to_owned(), all_helper.to_owned())]; + let with_helpers = Ctx { helpers: asserting_helpers(&files), ..ctx() }; + assert_eq!(census_in(all_helper, &with_helpers), [], "an asserting helper in the .all(…) predicate"); + assert_eq!(census_in(all_helper, &ctx()), [(2, "census")], "a predicate whose call does not assert"); + let message = + "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok(),\"{:?}\", probe().unwrap_err());\n }\n}\n"; + assert_eq!(census_in(message, &ctx()), [(2, "census")], "an unwrap_err in a failure message runs only after a failure"); + let skipped = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) || verify_fallback());\n}\n"; + assert_eq!(census_in(skipped, &ctx()), [(2, "census")], "a helper on the other side of an || can be skipped"); + let inner = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some() || verify_fallback(c).is_some()));\n}\n"; + assert_eq!(census_in(inner, &ctx()), [(2, "census")], "a helper inside the predicate behind an || can be skipped"); + let outer = "#[test]\nfn t() {\n assert!(verify_entry() || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(outer, &ctx()), [], "a helper on the left of an outer || always runs"); + let in_message = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some(), \"{:?}\", verify_entry(c));\n }\n}\n"; + assert_eq!(census_in(in_message, &ctx()), [(2, "census")], "a helper in a failure message runs only after a failure"); + let first = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| verify_entry(c) || c.is_some()));\n}\n"; + assert_eq!(census_in(first, &ctx()), [], "a helper on the left of an || always runs"); + let generic = all_helper.replace("exercise(c)", "exercise::(c)"); + assert_eq!(census_in(&generic, &with_helpers), [], "a helper called with a turbofish"); + let enforced = "#[test]\nfn t() {\n for case in CASES {\n assert!(!case.is_empty());\n let Ok(_) = parse(case) else { panic!(\"parse failed\") };\n }\n}\n"; + assert_eq!(census_in(enforced, &ctx()), [(2, "census")], "a panic that only enforces success"); + } + #[test] fn census_is_report_only() { assert!(!Rule::Census.fails()); From 7dde2f0310f1285ea959acf7b368dc3da4d11ed7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 01:48:16 -0800 Subject: [PATCH 53/72] Color Effects: ui.menuDialog lists Randomize Fill Colors ui.menuDialog opens the Randomize Fill Colors dialog, so its params text and the generated MCP catalog list addon.color.randomFill. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 2c8f54eb6e..8fd116233b 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5681df62bf..79a7f74a8d 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", From e14ee7032645c058bb0ffa5e513f1f1b0b49ee08 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 01:53:59 -0800 Subject: [PATCH 54/72] Tests: exact expectations for gradients, brush pressure, Smart Blur and effects Seven render, brush and effects tests accepted results well away from the value the code is meant to give: - The two linear gradient tests now expect the value at the pixel center (126 of 255, red 126 and blue 129) within 2 levels, instead of 12 or 20 around 128. - The trimmed bristle strand test bounds the width ratio on both sides. - The calligraphic roundness test expects the 0.1 pt hairline within 1e-6 pt. - Pucker & Bloat expects the corner anchor at (12.5, 12.5) and (-12.5, -12.5), not only the sign of the move. - Exposure's offset and gamma checks expect the sRGB value within 1e-5. - Smart Blur's checksums of earlier output are replaced by a 4 pixel row whose averages are worked out by hand. Each new assertion fails when the code it covers is changed (the gradient stops shifted, the pressure, roundness, pucker, offset or gamma factor changed, or the blur threshold widened). --- crates/brush/src/tests.rs | 5 +++-- crates/effects/src/addons/color.rs | 8 ++++++-- crates/effects/src/pixel/tests.rs | 29 ++++++++++++++++++++--------- crates/effects/src/tests.rs | 5 +++-- crates/render/src/tests.rs | 3 ++- crates/render/tests/it/golden.rs | 3 ++- 6 files changed, 36 insertions(+), 17 deletions(-) diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index c5d13cd0fa..01821a08f1 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -894,7 +894,7 @@ fn trimmed_bristle_strands_read_pressure_where_they_begin() { } let (_, neutral_width) = start(neutral); let expected = 0.5 + x / 80.0; - assert!(width / neutral_width > expected - 0.08, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}"); + assert!((width / neutral_width - expected).abs() < 0.02, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}"); checked = true; } assert!(checked, "at least one strand begins past the pressure ramp's first eighth"); @@ -1967,7 +1967,8 @@ fn pressure_varies_angle_and_roundness() { let b = Brush { name: "r".into(), kind: BrushKind::Calligraphic(vertical.clone()) }; bounds(&stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 0.0, 100.0), &pressed(vec![(0.0, p), (1.0, p)]))).width() }; - assert!(near(wide(0.0), 0.1, 0.05), "{}", wide(0.0)); + // Roundness 1% of the 10 pt size. + assert!(near(wide(0.0), 0.1, 1e-6), "{}", wide(0.0)); assert!(near(wide(1.0), 10.0, 0.05), "{}", wide(1.0)); // The angle turns on past 180°: 170 + 40 is 210°, the nib at 30° (not stopped at 180°). let turned = Calligraphic { angle: 170.0, roundness: 10.0, variation: [40.0, 0.0, 0.0], ..c([Pressure, Fixed, Fixed]) }; diff --git a/crates/effects/src/addons/color.rs b/crates/effects/src/addons/color.rs index 07627dd8d7..d6edf5f576 100644 --- a/crates/effects/src/addons/color.rs +++ b/crates/effects/src/addons/color.rs @@ -122,8 +122,12 @@ mod tests { // One stop doubles the light: sRGB 0.5 (linear 0.214) becomes linear 0.428, sRGB 0.686. assert!(close(map(EXPOSURE, json!({"exposure": 1})).apply_rgb(grey), [0.686; 3])); assert!(close(map(EXPOSURE, json!({"exposure": -20})).apply_rgb([1.0; 3]), [0.0; 3])); - assert!(map(EXPOSURE, json!({"offset": 0.1})).apply_rgb([0.0; 3])[0] > 0.3, "the offset lifts the shadows"); - assert!(map(EXPOSURE, json!({"gamma": 2})).apply_rgb(grey)[0] > 0.6); + // The offset adds linear light: linear 0.1 is sRGB 0.349. + let lifted = map(EXPOSURE, json!({"offset": 0.1})).apply_rgb([0.0; 3]); + assert!(lifted.iter().all(|c| (c - 0.349_190_2).abs() < 1e-5), "the offset lifts the shadows: {lifted:?}"); + // Gamma 2 takes the square root of linear 0.214 (sRGB 0.5): linear 0.463, sRGB 0.710. + let raised = map(EXPOSURE, json!({"gamma": 2})).apply_rgb(grey); + assert!(raised.iter().all(|c| (c - 0.710_196).abs() < 1e-5), "{raised:?}"); assert!(close(map(EXPOSURE, json!({"exposure": 1e300, "gamma": 0})).apply_rgb(grey), [1.0; 3]), "out of range values are clamped"); } diff --git a/crates/effects/src/pixel/tests.rs b/crates/effects/src/pixel/tests.rs index 6dd7942e5e..f2f66b2dd4 100644 --- a/crates/effects/src/pixel/tests.rs +++ b/crates/effects/src/pixel/tests.rs @@ -694,11 +694,6 @@ fn smart_blur_smooths_noise_and_keeps_edges() { assert_eq!(at(&all, w, 20, 10)[0], 255, "a 155-level step is still past 100"); } -/// FNV-1a of `bytes`. -fn digest(bytes: &[u8]) -> u64 { - bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) -} - #[test] fn smart_blur_normal_mode_keeps_its_pixels() { let (w, h) = (48, 40); @@ -706,7 +701,6 @@ fn smart_blur_normal_mode_keeps_its_pixels() { let a = if x > 4 && y < 36 { 255 } else { 128 }; [((x * 5 + y) as u8).min(a), ((y * 6) as u8).min(a), (((x * y) % 97) as u8).min(a), a] }); - let mut sums = Vec::new(); for p in [json!({}), json!({"radius": 2, "threshold": 10, "quality": "high"}), json!({"radius": 12, "threshold": 40, "quality": "low"})] { let mut d = src.clone(); fx("blur.smart", p.clone()).apply(&mut d, w, h, &space(w, h)); @@ -715,10 +709,27 @@ fn smart_blur_normal_mode_keeps_its_pixels() { p["blurMode"] = json!("normal"); fx("blur.smart", p).apply(&mut normal, w, h, &space(w, h)); assert_eq!(d, normal); - sums.push(digest(&d)); } - // The pixels Smart Blur gave before it had a mode. - assert_eq!(sums, [11495339692959753241, 14281410954765351056, 5111933201350526354]); +} + +/// Smart Blur at radius 1 averages each pixel with the neighbours whose channels, alpha included, +/// all lie within the threshold: grays 100 and 110 average to 105 each, 200 is 90 levels from 110 +/// and stays, and the half-covered pixel next to it differs in alpha and stays too. +#[test] +fn smart_blur_averages_only_the_neighbours_within_the_threshold() { + let (w, h) = (4, 1); + let src = image(w, h, |x, _| match x { + 0 => [100, 100, 100, 255], + 1 => [110, 110, 110, 255], + 2 => [200, 200, 200, 255], + _ => [100, 100, 100, 128], + }); + let mut d = src.clone(); + fx("blur.smart", json!({"radius": 1, "threshold": 20})).apply(&mut d, w, h, &space(w, h)); + assert_eq!(at(&d, w, 0, 0), [105, 105, 105, 255]); + assert_eq!(at(&d, w, 1, 0), [105, 105, 105, 255]); + assert_eq!(at(&d, w, 2, 0), [200, 200, 200, 255]); + assert_eq!(at(&d, w, 3, 0), at(&src, w, 3, 0)); } /// Smart Blur's test image: grays 56 and 64 in a checkerboard for x < 3 and 66 and 74 for x in 3..6 diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 07efb0c8bd..aa77e45b2f 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -1343,10 +1343,11 @@ fn transform_copies_of_images_stop_at_the_reach_limit() { fn pucker_bloat_moves_anchors_in_opposite_directions() { let bloat = run("distort.puckerBloat", json!({"amount": 50}), &square()); let a = bloat.subpaths[0].anchors[0].p; - assert!(a.x > 0.0 && a.y > 0.0, "bloat pulls corners in: {a:?}"); + // Half the amount of the way to the centre (50, 50): 25% of 50 pt. + assert!((a.x - 12.5).abs() < 1e-9 && (a.y - 12.5).abs() < 1e-9, "bloat pulls corners in: {a:?}"); let pucker = run("distort.puckerBloat", json!({"amount": -50}), &square()); let a = pucker.subpaths[0].anchors[0].p; - assert!(a.x < 0.0 && a.y < 0.0, "pucker pushes corners out: {a:?}"); + assert!((a.x + 12.5).abs() < 1e-9 && (a.y + 12.5).abs() < 1e-9, "pucker pushes corners out: {a:?}"); assert_eq!(run("distort.puckerBloat", json!({"amount": 0}), &square()), square()); } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index eddc139ebb..99ee9a5f0c 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -190,7 +190,8 @@ fn linear_gradient_goes_white_to_black() { assert!(r.pixel(2, 50)[0] > 240); assert!(r.pixel(97, 50)[0] < 15); let m = r.pixel(50, 50)[0] as i32; - assert!((m - 128).abs() < 12, "{m}"); + // Pixel centre x = 50.5: 255 · (1 - 0.505) = 126. + assert!((m - 126).abs() <= 2, "{m}"); } #[test] diff --git a/crates/render/tests/it/golden.rs b/crates/render/tests/it/golden.rs index a9dcb7af63..1a9fc61948 100644 --- a/crates/render/tests/it/golden.rs +++ b/crates/render/tests/it/golden.rs @@ -49,7 +49,8 @@ fn linear_gradient_left_to_right() { assert_rgb(&img, 1, 50, [255, 0, 0], 12); assert_rgb(&img, 98, 50, [0, 0, 255], 12); let mid = img.over_white(50, 50); - assert!(mid[0].abs_diff(128) < 20 && mid[2].abs_diff(128) < 20 && mid[1] < 10, "mid {mid:?}"); + // Pixel centre x = 50.5: red 255 · 0.495 = 126, blue 255 · 0.505 = 129. + assert!(mid[0].abs_diff(126) <= 2 && mid[2].abs_diff(129) <= 2 && mid[1] <= 2, "mid {mid:?}"); // Red decreases monotonically along x; rows are identical (horizontal gradient). let reds: Vec = (0..100).step_by(5).map(|x| img.over_white(x, 50)[0]).collect(); assert!(reds.windows(2).all(|w| w[1] <= w[0]), "{reds:?}"); From 78eb2f4afb6adc0bb844c07ad59ccbce1522322d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:09:48 -0800 Subject: [PATCH 55/72] Arrange Tools: list Group by Row among the dialogs ui.menuDialog opens ui.menuDialog opens the Group by Row dialog, so its params text and the MCP UI catalog name addon.arrange.groupRows with the other Arrange Tools dialogs. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 2c8f54eb6e..ca3e348b7c 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5681df62bf..67dabfc392 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", From 540d0fad700b7ff90dfdc6a5d04166e4b1e10a73 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:11:16 -0800 Subject: [PATCH 56/72] Plug-ins: list Mark Bounds of Each in ui.menuDialog's params text ui.menuDialog opens the Mark Bounds of Each dialog, so its command list and the generated MCP catalog now name addon.arrange.markBounds. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 2c8f54eb6e..d3d44c9f15 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5681df62bf..f497b0dd08 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", From 8f5eb5435f03933fb558cc0b4cf7cd402522925e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:13:46 -0800 Subject: [PATCH 57/72] Tests: assert exact columns, padding and corner span in js and tools tests Five assertions accepted any positive value, so a wrong result could pass: - host_tests: the evaluator site column and the thrown error's column are now 3, where the indented call and throw start. - promise_tests: rejections relayed through Promise.all, Promise.race and a catch handler report column 3, not any column above 0. - xmp_tests: the sample packet's padding is exactly 1. - corners tests: a 10 pt radius at a 120 degree polygon corner spans 10 pt, within 1e-6, instead of anything in (5, 10.5]. --- crates/js/src/host_tests.rs | 4 ++-- crates/js/src/promise_tests.rs | 4 ++-- crates/js/src/xmp_tests.rs | 2 +- crates/tools/src/corners/tests.rs | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 308188daea..40a29ba77d 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -476,7 +476,7 @@ fn an_evaluator_with_site_is_told_where_it_is_called() { assert_eq!(given.len(), 2, "{given:?}"); assert_eq!(given[0].len(), 4, "{given:?}"); assert_eq!((&given[0][..2], &given[0][3]), (&[Data::Number(tag), Data::Number(3.0)][..], &Data::String("x".into())), "{given:?}"); - assert!(matches!(given[0][2], Data::Number(c) if c >= 1.0), "{given:?}"); + assert_eq!(given[0][2], Data::Number(3.0), "{given:?}"); assert_eq!(given[1], vec![Data::String("y".into())]); } @@ -615,7 +615,7 @@ fn an_error_says_where_in_the_source_it_was_raised() { r.start("var a = 1;\n throw new TypeError('no');").unwrap(); let e = finish(&mut r, 1).0.unwrap_err(); assert_eq!((e.kind, e.line), (RunErrorKind::Thrown, 2)); - assert!(e.column >= 3, "{}", e.column); + assert_eq!(e.column, 3); assert_eq!(e.message, "TypeError: no"); } diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 51b1e990f1..1fbdb5c003 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -369,7 +369,7 @@ fn combinator_rejection_relays_keep_the_input_location() { let reported = r.unhandled_rejections(); assert_eq!(reported.len(), 1, "{method}: {reported:?}"); assert_eq!(reported[0].line, 2, "{method}: {:?}", reported[0]); - assert!(reported[0].column > 0); + assert_eq!(reported[0].column, 3, "{method}: {:?}", reported[0]); assert_eq!(reported[0].tag, r.script_tag()); } let mut r = realm(); @@ -377,7 +377,7 @@ fn combinator_rejection_relays_keep_the_input_location() { .unwrap(); assert_eq!(r.unhandled_rejections().len(), 1); assert_eq!(r.unhandled_rejections()[0].line, 3); - assert!(r.unhandled_rejections()[0].column > 0); + assert_eq!(r.unhandled_rejections()[0].column, 3); let mut r = realm(); r.run("eval(\"Promise.reject('eval')\"); Function(\"Promise.reject('function')\")();").unwrap(); let reported = r.unhandled_rejections(); diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 5aee375abd..d1fdb6aefc 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -113,7 +113,7 @@ fn explicit_empty_and_named_rdf_subjects_cannot_be_merged() { fn packet_padding_requires_an_actual_wrapper_trailer() { let packet = r#""#; assert_eq!(xmp::pad_size(packet), 0); - assert!(xmp::pad_size(PACKET) > 0); + assert_eq!(xmp::pad_size(PACKET), 1); let prefixed = format!("\n\n{PACKET}"); assert_eq!(xmp::pad_size(&prefixed), xmp::pad_size(PACKET)); assert_eq!(xmp::pad_size(&format!("{PACKET}")), xmp::pad_size(PACKET)); diff --git a/crates/tools/src/corners/tests.rs b/crates/tools/src/corners/tests.rs index 1e90ce72c7..8094e88209 100644 --- a/crates/tools/src/corners/tests.rs +++ b/crates/tools/src/corners/tests.rs @@ -899,7 +899,7 @@ fn a_polygons_widget_gives_its_cut_and_a_hidden_widget_gives_none() { assert_eq!(got, id); // The arc of a 10 pt radius at a 120° corner spans 10 pt between its ends. let (wide, high) = (b[2] - b[0], b[3] - b[1]); - assert!(wide.max(high) <= 10.5 && wide.max(high) > 5.0, "{b:?}"); + assert!((wide.max(high) - 10.0).abs() < 1e-6, "{b:?}"); let centre = Point::new((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0); assert!(centre.distance(at) < 15.0, "{b:?} {at:?}"); // Sheared by 30°: the rectangle's 120° corners (1 and 3) hide above 100°. From 64846b227420848384f961f414aa9b6dc0549bad Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:48:58 +0530 Subject: [PATCH 58/72] Canvas: offer Create Outlines for selected text --- crates/ui-egui/src/menus/context.rs | 3 ++ crates/ui-egui/src/tests/contextmenu.rs | 46 +++++++++++++++++++++++++ docs/ui-parity.md | 2 +- 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index 06d9a22523..06f1a6900b 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -118,6 +118,9 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { if any(|k| matches!(k, NodeKind::Compound { .. })) { v.push(c("Release Compound Path", "object.compoundPath.release")); } + if any(|k| matches!(k, NodeKind::Text(_))) { + v.push(c("Create Outlines", "type.createOutlines")); + } // The paragraphs of the selected type, or those the Type tool's selection touches. if crate::panels::character::text_style(app).is_some() { v.push(sub("Bullets and Numbering", vec![c("Apply Bullets", "type.applyBullets"), c("Apply Numbers", "type.applyNumbers")])); diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index b8c6972dee..4ed9e3d47d 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -681,6 +681,52 @@ impl CanvasMenu { } } +#[test] +fn create_outlines_from_the_canvas_menu_converts_selected_text_in_one_undo_step() { + let mut app = app(); + let path = rect(&mut app, 50.0, 50.0); + assert!(!has(&app, "Create Outlines"), "a path alone has no text to outline"); + app.run("select.none", json!({})).unwrap(); + assert!(!has(&app, "Create Outlines"), "an empty selection has no text to outline"); + + let point = app.run("text.create", json!({"x": 180, "y": 80, "text": "One"})).unwrap()["id"].as_u64().unwrap(); + assert!(has(&app, "Create Outlines"), "point text offers the action"); + let area = + app.run("text.create", json!({"x": 180, "y": 100, "text": "Two", "area": {"width": 120, "height": 80}})).unwrap()["id"].as_u64().unwrap(); + assert!(has(&app, "Create Outlines"), "area text offers the action"); + app.run("select.set", json!({"ids": [path.0, point, area]})).unwrap(); + + let mut canvas = CanvasMenu::new(app); + canvas.right_click(100.0, 100.0); + let tree = canvas.fixture.tree(); + let item = canvas + .fixture + .by_role(craft::ui::contract::Role::MENU_ITEM) + .into_iter() + .find(|item| tree.name_of(item.node).is_some_and(|name| name.starts_with("Create Outlines"))) + .expect("the rendered canvas menu offers Create Outlines"); + canvas.fixture.click(&item); + crate::testing::fixture_input(&mut canvas.app.borrow_mut(), &mut canvas.fixture); + canvas.frame(vec![]); + + let mut app = canvas.app.borrow_mut(); + let st = app.session.active().unwrap(); + assert!(st.doc.node(path).is_some()); + for id in [point, area] { + assert!(st.doc.node(NodeId(id)).is_none(), "the original text was replaced"); + } + assert_eq!( + st.selection.objects.iter().filter(|&&id| matches!(st.doc.node(id).map(|n| &n.kind), Some(NodeKind::Group { .. }))).count(), + 2, + "both text objects became selected groups" + ); + app.run("edit.undo", json!({})).unwrap(); + let doc = &app.session.active().unwrap().doc; + for id in [point, area] { + assert!(matches!(doc.node(NodeId(id)).map(|n| &n.kind), Some(NodeKind::Text(_))), "one Undo restored both text objects"); + } +} + /// #5267: a right-click on a stroked object offers Outline Stroke, which runs /// `object.path.outlineStroke` (the Object › Path item) and leaves filled art; an object with no /// stroke to outline has no such item. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d131053a67..170549ae4c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -530,7 +530,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Pathfinder panel › Pathfinder Options…: Precision, Remove Redundant Points, Divide and Outline Will Remove Unpainted Artwork | done | #3426; `object.pathfinder.options`, kept in the preferences; defaults (0.01 pt, both off) keep the earlier results; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html) | | Cmd/Ctrl+4 repeats the last successful Shape Mode or Pathfinder operation on the selection | done | Panel operations, direct `object.pathfinder.*` commands and `command.batch` steps (Actions playback) set history; `action.batch`, Trap, compound-shape edits and live effects do not. Repeat uses current Pathfinder Options; [key spec](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), [menu spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html) | | Pathfinder panel: compound shapes (Make, Release and Expand Compound Shape in the panel menu, Alt-click a Shape Mode, a Shape Mode for selected members, the Expand button) | partial | #4522; `object.compoundShape.make`/`setMode`/`release`/`expand`; members stay editable, the area draws, exports and saves; the button of the members' shared mode is lit, and members in different modes put a question mark on each Shape Mode button; blends, envelopes and warped objects are members as they draw; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html); missing: hit-testing by the area | -| Canvas context menu | done | Right-clicking type opens the canvas menu, with Bullets and Numbering and Spelling. Right-clicking a path offers Object › Path › Simplify… and Smooth…, each opening what its menu item opens (#8344). A selection with a visible stroke to outline (a path, compound path or group holding one; not type) adds Outline Stroke (`object.path.outlineStroke`, the Object › Path item, no shortcut), after the path operations (#5267). Artboard rows, library groups and items, the rulers and floating toolbar grips have menus too. Gaps: other panels have none | +| Canvas context menu | done | Right-clicking type opens the canvas menu, with Bullets and Numbering and Spelling. The menu offers Create Outlines when at least one text object is selected, with the same shortcut and undoable command as Type › Create Outlines (#9022). The Menu key and Shift+F10 open the menu for the current selection. Right-clicking a path offers Object › Path › Simplify… and Smooth…, each opening what its menu item opens (#8344). A selection with a visible stroke to outline (a path, compound path or group holding one; not type) adds Outline Stroke (`object.path.outlineStroke`, the Object › Path item, no shortcut), after the path operations (#5267). Artboard rows, library groups and items, the rulers and floating toolbar grips have menus too. Gaps: other panels have none | | Layers panel row context menu | done | Right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export; right-clicking a ruler guide row shows Hide/Show, Lock/Unlock, Release Guides, Delete and Locate Object; right-clicking a blend spine row shows Select, Blend Options…, Reverse Spine, Reverse Front to Back, Expand, Release and Locate Object (#8592). | | Swatches item context menu (G12) | done | List and thumbnail items offer Swatch Options…, Duplicate Swatch and Delete Swatch for the clicked item. Right-click selects without applying paint; reserved/missing items disable actions. All 39 Swatches tests pass, including all five views and Undo; the regression fails with the menu hooks removed. Rendered headless menus inspected. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. | | History panel row context menu (G12) | done | New Document from State, Step to This State, and Clear History; current-row stepping and empty-history clearing are disabled. Snapshot identity is checked after pending tool edits, and jumps settle typing before counting undo/redo. A state discarded while an edit settles reports that it is unavailable. Shift+F10 opens the focused row menu; Escape returns focus to the row. Switching documents dismisses the menu. Headless tests: `panels::history::tests`. | From fc5b42e30428b3bb7675b27b7d4723a041a3139e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:14:08 -0800 Subject: [PATCH 59/72] xtask: census counts rejections in .all() and bounded zip ranges An .all(...) predicate that calls unwrap_err or expect_err on a branch that always runs now checks a rejection, like an asserting helper. A zip with a bounded range (zip(0..2)) bounds the loop, while an open-ended range (zip(0..)) still visits every entry. Rejection calls are matched with whitespace inside them (unwrap_err ()) at every site. --- xtask/src/test_lint.rs | 58 +++++++++++++++++++++++++++++++----------- 1 file changed, 43 insertions(+), 15 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 205724eee0..6b40bf8423 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -965,10 +965,7 @@ fn is_helper_call(name: &str, method: bool, helpers: &HashSet) -> bool { /// `expect_err`. fn checks_itself(m: &[u8], from: usize, to: usize) -> bool { let body = &m[from..to]; - contains(body, b"panic!") - || contains(body, b".unwrap_err()") - || contains(body, b".expect_err(") - || macro_calls(m, from, to).iter().any(|c| is_assert_macro(&c.name)) + contains(body, b"panic!") || rejects(body) || macro_calls(m, from, to).iter().any(|c| is_assert_macro(&c.name)) } /// `tests.rs`, `tests_*.rs`, `*_tests.rs`, files in a `tests` or `benches` folder, and @@ -1347,9 +1344,8 @@ fn census(v: &View, helpers: &HashSet) -> Vec { let weak_in = |from: usize, to: usize, var: &str| { let inside: Vec<&MacroCall> = v.asserts.iter().filter(|a| a.at > from && a.at < to).collect(); let body = &unmessaged[from - v.t.open..to - v.t.open]; - let rejects = contains(body, b".unwrap_err()") || contains(body, b".expect_err("); helpers_in(from, to).is_empty() - && !rejects + && !rejects(body) && !inside.is_empty() && inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm(&m[f..t])).collect::>(), var)) }; @@ -1389,7 +1385,7 @@ fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool if s.contains(".all(") { census_condition(s, depth + 1, helpers) } else { (weak_predicate(s) && !calls_any(s, helpers), false) } }; let (l, r) = (side(&cond[..at]), side(&cond[at + 2..])); - let r = if or.is_some() && calls_any(&cond[..at], helpers) { (false, false) } else { r }; + let r = if or.is_some() && (calls_any(&cond[..at], helpers) || rejects(&cond.as_bytes()[..at])) { (false, false) } else { r }; if or.is_none() { (l.0 && r.0, l.1 || r.1) } else if l == (true, true) || r == (true, true) { @@ -1441,7 +1437,15 @@ fn weak_table_all(op: &str, helpers: &[String]) -> bool { let receiver = op[..i].trim_end_matches(".iter()").trim_end_matches(".into_iter()"); let rest = &op[i + ".all(".len()..]; let end = arg_end(rest); - rest[end..] == *")" && whole_table(receiver) && presence_only(&rest[..end], helpers, 0) + // A rejection call checks something only on the branches that run it, like an asserting helper. + let checks: Vec = helpers.iter().cloned().chain(["unwrap_err".into(), "expect_err".into()]).collect(); + rest[end..] == *")" && whole_table(receiver) && presence_only(&rest[..end], &checks, 0) +} + +/// Whether `body` calls `.unwrap_err()` or `.expect_err(`, with any whitespace inside the call. +fn rejects(body: &[u8]) -> bool { + let tight: Vec = body.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect(); + contains(&tight, b".unwrap_err()") || contains(&tight, b".expect_err(") } /// The `{` that opens a `for` loop's body: the first one outside brackets after `from`. @@ -1483,11 +1487,16 @@ fn whole_table(src: &str) -> bool { ]; let chain = &src[head.len()..]; // A `zip` stops at its shorter side and a `flat_map` yields what its closure's iterator yields, - // so a restricted iterator inside either bounds the loop too. + // so a restricted iterator inside either bounds the loop too, as does a range zipped in. let bounded_inside = [".zip(", ".flat_map("].iter().any(|adapter| { top_level_at(chain, adapter).into_iter().any(|at| { let open = at + adapter.len() - 1; - matching(chain.as_bytes(), open).is_none_or(|close| restricted.iter().any(|r| chain[open + 1..close].contains(r))) + matching(chain.as_bytes(), open).is_none_or(|close| { + let inner = &chain[open + 1..close]; + let range = unparenthesized(inner.trim_end_matches(',')); + restricted.iter().any(|r| inner.contains(r)) + || *adapter == ".zip(" && top_level_at(range, "..").first().is_some_and(|&at| !range[at + 2..].trim_start_matches('=').is_empty()) + }) }) }); if bounded_inside || restricted.iter().any(|r| top_level_contains(chain, r)) { @@ -2520,7 +2529,7 @@ fn only_weak(v: &View) -> Option { let all_weak = v.asserts.iter().all(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && is_weak(&v.first_arg(a))); // Failure messages run only after an assertion has failed, so a check there does not count. let body = v.body_without_messages(); - let other = contains(&body, b"panic!") || contains(&body, b".unwrap_err()") || contains(&body, b".expect_err("); + let other = contains(&body, b"panic!") || rejects(&body); if v.asserts.is_empty() || !all_weak || other || v.delegates || v.should_panic { return None; } @@ -2966,10 +2975,6 @@ mod tests { assert_eq!(census(inner), [(2, "census")]); let accented = "#[test]\nfn t() {\n for c in COLORS.iter().clonés() {\n assert!(c.is_some());\n }\n}\n"; assert_eq!(census(accented), [(2, "census")], "a non-ASCII method name is read without panicking"); - let zipped = "#[test]\nfn t() {\n for (c, l) in COLORS.iter().zip(labels.iter().take(2)) {\n assert!(c.is_some());\n }\n}\n"; - assert_eq!(census(zipped), [], "a bounded iterator zipped in bounds the loop"); - let flat = "#[test]\nfn t() {\n for e in GROUPS.iter().flat_map(|g| g.es.iter().take(1)) {\n assert!(e.is_some());\n }\n}\n"; - assert_eq!(census(flat), [], "a bounded iterator returned by flat_map bounds the loop"); let nested = "#[test]\nfn t() {\n assert!(COLORS.iter().map(|c| c.parts.iter().all(|p| p.ok)).all(|c| c.is_some()));\n}\n"; assert_eq!(census(nested), [(2, "census")]); let wrapped = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Some(Kind::parse(k.name()).unwrap()), Some(k));\n }\n}\n"; @@ -2984,11 +2989,34 @@ mod tests { assert_eq!(census(subsets), [], "subset adapters pick a few entries"); } + #[test] + fn census_skips_loops_bounded_by_zip_or_flat_map() { + let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let zipped = "#[test]\nfn t() {\n for (c, l) in COLORS.iter().zip(labels.iter().take(2)) {\n assert!(c.is_some());\n }\n}\n"; + assert_eq!(census(zipped), [], "a bounded iterator zipped in bounds the loop"); + let ranged = "#[test]\nfn t() {\n for (c, i) in COLORS.iter().zip(0..2) {\n assert!(c.is_some());\n }\n}\n"; + assert_eq!(census(ranged), [], "a range zipped in bounds the loop"); + for range in ["0..", "0..,", "(0..)", "((0..)),", "std::iter::repeat(0..2)"] { + let open = format!("#[test]\nfn t() {{\n for (c, i) in COLORS.iter().zip({range}) {{\n assert!(c.is_some());\n }}\n}}\n"); + assert_eq!(census(&open), [(2, "census")], "an open-ended range zipped in visits every entry: {range}"); + } + let flat = "#[test]\nfn t() {\n for e in GROUPS.iter().flat_map(|g| g.es.iter().take(1)) {\n assert!(e.is_some());\n }\n}\n"; + assert_eq!(census(flat), [], "a bounded iterator returned by flat_map bounds the loop"); + } + #[test] fn census_counts_rejections_and_helpers_as_checks() { let census_in = |src: &str, ctx: &Ctx| hits_in("crates/x/src/tests.rs", src, ctx).into_iter().filter(|h| h.1 == "census").collect::>(); let rejected = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).unwrap_err();\n }\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).expect_err(\"rejects\");\n }\n}\n"; assert_eq!(census_in(rejected, &ctx()), [], "an unwrap_err or expect_err in the loop checks a rejection"); + let spaced = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).unwrap_err ();\n }\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).expect_err (\"rejects\");\n }\n}\n"; + assert_eq!(census_in(spaced, &ctx()), [], "whitespace inside the rejection call"); + let all_rejects = "#[test]\nfn t() {\n assert!(CASES.iter().all(|c| parse(c.bad).unwrap_err().contains(\"bad\")));\n assert!(CASES.iter().all(|c| parse(c.bad).expect_err(\"rejects\").contains(\"bad\")));\n}\n"; + assert_eq!(census_in(all_rejects, &ctx()), [], "an unwrap_err or expect_err in the .all(…) predicate checks a rejection"); + let skips = "#[test]\nfn t() {\n assert!(CASES.iter().all(|c| c.is_some() || parse(c.bad).unwrap_err().contains(\"bad\")));\n}\n"; + assert_eq!(census_in(skips, &ctx()), [(2, "census")], "a rejection after a presence check on an || can be skipped"); + let first = "#[test]\nfn t() {\n assert!(parse(invalid).unwrap_err().contains(\"bad\") || CASES.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(first, &ctx()), [], "a rejection on the left of an || always runs"); let only_ok = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n }\n}\n"; assert_eq!(census_in(only_ok, &ctx()), [(2, "census")]); let all_helper = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| exercise(c).is_some()));\n}\nfn exercise(c: &Color) -> Option<()> {\n assert_eq!(blend(c), WHITE);\n Some(())\n}\n"; From 6ea1132e5c345f8b726589f4151f4c9d5f7758d1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:27:00 -0800 Subject: [PATCH 60/72] Tests: tighten loose bounds in color and text tests Five assertions accepted wrong results: - Freeform: a point split half way along a Catmull-Rom segment must be at x = 43.75, not anywhere between the two ends. - Diamond gradient pixels: the center is exactly white and the corners exactly black, instead of a bound that accepted white scaled to 220. - Ruby: the default reading is half the base size (ratio 0.5), where the old bound accepted 70%. - Caret Up/Down: the caret lands on the stop nearest the column, where the old 12 pt tolerance accepted a neighboring stop. - Hyphenation defaults: a frozen hash of line breaks is replaced with explicit breaks ("The lan-" / "guage", "The gar-" / "den") and hyphen flags for both composers, ragged and justified. Each new assertion fails when the behavior it checks is broken. --- crates/color/src/freeform.rs | 4 ++- crates/color/src/gradient/tests.rs | 2 +- crates/text/src/tests/ruby.rs | 2 +- crates/text/src/tests/typo.rs | 51 ++++++++++++++++-------------- 4 files changed, 32 insertions(+), 27 deletions(-) diff --git a/crates/color/src/freeform.rs b/crates/color/src/freeform.rs index 11884d5c6c..9ea2af3e15 100644 --- a/crates/color/src/freeform.rs +++ b/crates/color/src/freeform.rs @@ -685,7 +685,9 @@ mod tests { let mid = f.split_line(0, 0, 0.5).unwrap(); assert_eq!((mid, &f.lines[0]), (3, &vec![0, 3, 1, 2])); let p = f.points[3]; - assert!(p.at.y.abs() < 1e-9 && p.at.x > 0.0 && p.at.x < 100.0 && (p.opacity - 0.75).abs() < 1e-6, "on the curve, half way: {p:?}"); + // The Catmull-Rom segment from (0, 0) to (100, 0), with (200, 0) after it, is at x = 43.75 + // half way, not at the straight line's 50. + assert!(p.at.y.abs() < 1e-9 && (p.at.x - 43.75).abs() < 1e-9 && (p.opacity - 0.75).abs() < 1e-6, "on the curve, half way: {p:?}"); assert!(f.remove_point(1)); assert_eq!(f.lines, vec![vec![0, 2, 1]]); assert!(f.add_line(vec![0, 9]).is_err() && f.add_line(vec![0]).is_err()); diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index 25451aa3d7..4d5c84c01f 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -1379,7 +1379,7 @@ fn diamond_pixels_follow_the_squares() { g.geom = Some(diamond_at(Point::new(2.5, 2.5), 2.5, 1.0)); let px: Vec<[u8; 4]> = g.pixels(b, b, 5, 5, false, &Color::to_rgb).collect(); // White at the center, black in the corners, and the same on each side of it. - assert!(px[2 * 5 + 2][0] > 200 && px[0][0] < 10 && px[24][0] < 10, "{px:?}"); + assert_eq!((px[2 * 5 + 2], px[0], px[24]), ([255, 255, 255, 255], [0, 0, 0, 255], [0, 0, 0, 255]), "{px:?}"); assert_eq!(px[2 * 5 + 1], px[2 * 5 + 3]); assert_eq!(px[5 + 2], px[3 * 5 + 2]); assert_eq!(px[2 * 5 + 1], px[5 + 2]); diff --git a/crates/text/src/tests/ruby.rs b/crates/text/src/tests/ruby.rs index e7a7cfc1fb..b041b81e5d 100644 --- a/crates/text/src/tests/ruby.rs +++ b/crates/text/src/tests/ruby.rs @@ -104,7 +104,7 @@ fn ruby_is_half_the_base_size_by_default_and_size_follows_the_span() { whole.ruby[0].size_percent = 100.0; let half = ruby_ink(&layout(db(), &half)); let whole = ruby_ink(&layout(db(), &whole)); - assert!(half.height() < whole.height() * 0.75, "{} vs {}", half.height(), whole.height()); + assert!((half.height() / whole.height() - 0.5).abs() < 1e-6, "{} vs {}", half.height(), whole.height()); } #[test] diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index aff68bafd4..1d452fe72f 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -562,8 +562,13 @@ fn caret_up_down_keeps_column() { let (top, _) = caret_position(&l, b); let down = caret_vertical(&l, b, 1, top.x); assert_eq!(l.line_of(down), 3); + // The caret lands on the stop of line 3 nearest the column, not on a neighbor. let (t2, _) = caret_position(&l, down); - assert!((t2.x - top.x).abs() < 12.0, "{} vs {}", t2.x, top.x); + let nearest = (l.lines[3].start..=l.lines[3].end) + .filter(|&i| COPY.is_char_boundary(i) && l.line_of(i) == 3) + .map(|i| (caret_position(&l, i).0.x - top.x).abs()) + .fold(f64::INFINITY, f64::min); + assert!(((t2.x - top.x).abs() - nearest).abs() < 1e-6, "{} vs {} (nearest stop {nearest} away)", t2.x, top.x); let up = caret_vertical(&l, down, -1, top.x); assert_eq!(up, b); assert_eq!(caret_vertical(&l, b, -10, top.x), 0); @@ -1267,34 +1272,32 @@ fn hyphenation_zone_breaks_before_the_word_with_the_single_line_composer() { assert_eq!(line_texts(&every, &layout(db(), &every)), without); } -/// The default Hyphenation options keep the line breaks of hyphenated text: the copy twice over -/// at three widths, ragged and justified, with either composer. The constant is an FNV-1a hash of -/// each line's end and whether it ends with a hyphen. It changed once since: justified lines -/// follow the default Justification options (word spacing up to 133%, where the composer used -/// to stretch spaces to 150%), and the every-line composer no longer gives up on loose lines. +/// With the default Hyphenation options, ragged and justified, with either composer: "The +/// language" in a frame that holds "The lan-" breaks as "The lan-" and "guage", only the first +/// line ends with a hyphen. The 6-letter "garden" (longer than the default 5 letters) breaks the +/// same way, as "The gar-" and "den". #[test] fn default_hyphenation_options_keep_the_line_breaks() { - let mut hash: u64 = 0xcbf2_9ce4_8422_2325; - let mut mix = |v: u64| { - for b in v.to_le_bytes() { - hash = (hash ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3); - } + let ends_with_hyphen = |l: &TextLayout| -> Vec { + l.lines.iter().map(|li| li.glyph_end > li.glyph_start && l.glyphs.get(li.glyph_end - 1).is_some_and(|g| g.len == 0)).collect() }; - for width in [150.0, 190.0, 240.0] { - for justify in [Justify::Left, Justify::JustifyLeft] { - for composer in [Composer::SingleLine, Composer::EveryLine] { - let mut t = area(©.repeat(2), style(12.0), Rect::new(0.0, 0.0, width, 4000.0), justify); - t.para.hyphenate = true; - t.para.composer = composer; - let l = layout(db(), &t); - for li in &l.lines { - let hyphenated = li.glyph_end > li.glyph_start && l.glyphs.get(li.glyph_end - 1).is_some_and(|g| g.len == 0); - mix(li.end as u64 * 2 + u64::from(hyphenated)); - } - } + for justify in [Justify::Left, Justify::JustifyLeft] { + for composer in [Composer::SingleLine, Composer::EveryLine] { + let mut t = the_language("language", composer); + t.para.justify = justify; + let l = layout(db(), &t); + assert_eq!(line_texts(&t, &l), ["The lan", "guage"], "{justify:?} {composer:?}"); + assert_eq!(ends_with_hyphen(&l), [true, false], "{justify:?} {composer:?}"); + let w = natural_width("The gar-", 12.0).max(natural_width("garden", 12.0)) + 1.0; + assert!(w < natural_width("The garden", 12.0)); + let mut t = area("The garden", style(12.0), Rect::new(0.0, 0.0, w, 400.0), justify); + t.para.hyphenate = true; + t.para.composer = composer; + let l = layout(db(), &t); + assert_eq!(line_texts(&t, &l), ["The gar", "den"], "{justify:?} {composer:?}"); + assert_eq!(ends_with_hyphen(&l), [true, false], "{justify:?} {composer:?}"); } } - assert_eq!(hash, 4_188_642_633_634_327_633); } /// The longest run of consecutive lines of `l` that end with a hyphen. From 7da87711394b06ab06bd7e8b872da27f68f11bfa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:34:00 -0800 Subject: [PATCH 61/72] Tests: check Affinity pixels and DXF goldens against the formats The Affinity raster tests compared decoded pixels with CRCs captured from the reader's own output, so a decoding error present when the CRC was taken would pass. They now read the image's tiles straight from the archive (256-byte by 256-row planes, states 2 and 4), interleave them, scale 16-bit samples with rounding, and compare the whole buffer. The Affinity 3 signatures drop the CRC of the model's Debug output and keep the feature counts. The DXF golden test no longer rewrites its expected files when WRITE_DXF_GOLDENS is set. Each golden file is first checked against the drawing it should hold (rectangle corners, circle center, radius and bulges, ACI and true colors, lineweights), and a mismatch saves the output to the temp directory for review. --- Cargo.lock | 1 - crates/affinity/Cargo.toml | 1 - crates/affinity/tests/it/raster.rs | 81 +++++++++++++++++-- .../tests/support/affinity3-signatures.txt | 66 +++++++-------- crates/affinity/tests/support/features.rs | 15 +--- crates/cad/src/tests.rs | 60 ++++++++++++-- 6 files changed, 164 insertions(+), 60 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 772196967a..9a3010412f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8573,7 +8573,6 @@ version = "0.25.1" dependencies = [ "craft-affinity", "craft-image-codecs", - "crc32fast", "proptest", "vectorcraft-affinity", ] diff --git a/crates/affinity/Cargo.toml b/crates/affinity/Cargo.toml index 80876c409a..820437c6ff 100644 --- a/crates/affinity/Cargo.toml +++ b/crates/affinity/Cargo.toml @@ -19,7 +19,6 @@ craft-affinity = { workspace = true } [dev-dependencies] proptest = { workspace = true } # The tests build containers and decode previews. -crc32fast = { workspace = true } craft-image-codecs = { workspace = true } # tests/it's `import_limits`, `outline_limits` and `text` modules need `synth`, also when this crate # is tested without vectorcraft-engine (`cargo xtask ci shard`). diff --git a/crates/affinity/tests/it/raster.rs b/crates/affinity/tests/it/raster.rs index 46e96c2013..2fac84f74b 100644 --- a/crates/affinity/tests/it/raster.rs +++ b/crates/affinity/tests/it/raster.rs @@ -41,6 +41,70 @@ fn source(bytes: &[u8]) -> Vec { block.bytes(block.root, b"Data").unwrap().to_vec() } +/// The fixture's one tiled bitmap read straight from its archive entries, interleaved: RGBA8 for +/// RGBA layers (16-bit samples scaled to 8 bits with rounding) and C, M, Y, K, alpha for CMYK. +/// Each channel is a grid of 256-byte × 256-row tiles in row-major order; state 2 is a tile of +/// 0xFF, state 4 a stored tile (the next `Idx` entry), and any other state a tile of zeros. +fn tiled_pixels(bytes: &[u8]) -> (u32, u32, Vec) { + const TILE: usize = 256; + let mut archive = Archive::open(bytes, Limits::default()).unwrap(); + let doc = stream::parse(&archive.read("doc.dat").unwrap()).unwrap(); + // The bitmap the image layer (`ImgN`) holds as `Bitm`; the document's other bitmaps are masks. + let bitmaps: Vec = (0..doc.objects.len()) + .filter(|&o| doc.is(o, b"ImgN")) + .filter_map(|o| doc.obj(o, b"Bitm")) + .filter(|&b| doc.is(b, b"DyBm") && doc.field(b, b"Sta1").is_some()) + .collect(); + assert_eq!(bitmaps.len(), 1, "one tiled image bitmap"); + let bitmap = bitmaps[0]; + let width = usize::try_from(doc.int(bitmap, b"BmpW").unwrap()).unwrap(); + let height = usize::try_from(doc.int(bitmap, b"BmpH").unwrap()).unwrap(); + let (channels, bps) = match doc.enumeration(bitmap, b"Frmt").unwrap().0 { + 0 => (4, 1), + 1 => (4, 2), + 4 => (5, 1), + other => panic!("format {other}"), + }; + let row = width * bps; + let across = row.div_ceil(TILE); + let mut planes = Vec::new(); + for c in 1..=channels { + let digit = b'0' + c as u8; + let Some(stream::Value::Array(states)) = doc.field(bitmap, &[b'S', b't', b'a', digit]) else { panic!("states of channel {c}") }; + let mut stored = doc.objs(bitmap, &[b'I', b'd', b'x', digit]).into_iter(); + let mut plane = vec![0u8; row * height]; + for (t, state) in states.iter().enumerate().take(across * height.div_ceil(TILE)) { + let tile: Vec = match state { + stream::Value::UInt(2) => vec![0xFF; TILE * TILE], + stream::Value::UInt(4) => { + let name = doc.entry(stored.next().unwrap(), b"Data").unwrap().to_string(); + let data = archive.read(&name).unwrap(); + assert_eq!(data.len(), TILE * TILE, "{name}"); + data + } + _ => continue, + }; + let (ox, oy) = ((t % across) * TILE, (t / across) * TILE); + for y in oy..(oy + TILE).min(height) { + for x in ox..(ox + TILE).min(row) { + plane[y * row + x] = tile[(y - oy) * TILE + x - ox]; + } + } + } + planes.push(plane); + } + let sample = |c: usize, i: usize| -> u8 { + if bps == 1 { + planes[c][i] + } else { + let v = u32::from(u16::from_le_bytes([planes[c][2 * i], planes[c][2 * i + 1]])); + u8::try_from((v * 255 + 32767) / 65535).unwrap() + } + }; + let pixels = (0..width * height).flat_map(|i| (0..channels).map(move |c| (c, i))).map(|(c, i)| sample(c, i)).collect(); + (u32::try_from(width).unwrap(), u32::try_from(height).unwrap(), pixels) +} + #[test] fn source_backed_tiles_retain_the_embedded_jpeg_pixels() { let Some((bytes, doc, images)) = read_fixture("patchy-embedded-jpeg.af") else { return }; @@ -68,8 +132,8 @@ fn lazy_placed_images_keep_the_original_encoded_bytes() { #[test] fn eight_and_sixteen_bit_channels_retain_the_same_pixel_pattern() { - let Some((_, doc8, images8)) = read_fixture("patchy-rgba8.af") else { return }; - let (_, doc16, images16) = read_fixture("patchy-rgba16.af").unwrap(); + let Some((bytes8, doc8, images8)) = read_fixture("patchy-rgba8.af") else { return }; + let (bytes16, doc16, images16) = read_fixture("patchy-rgba16.af").unwrap(); assert!(doc8.warnings.is_empty()); assert!(doc16.warnings.is_empty()); assert_eq!(images8.len(), 1); @@ -80,13 +144,13 @@ fn eight_and_sixteen_bit_channels_retain_the_same_pixel_pattern() { assert_eq!(&pixels[..4], &[0, 0, 0, 128]); assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[3] < 255)); assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[0] != p[1])); - // Frozen pixel-retention baseline, including every alpha sample. It is not a render oracle. - assert_eq!(crc32fast::hash(pixels), 0xc8ee4dc1); + assert_eq!(tiled_pixels(&bytes8), (64, 48, pixels.clone())); + assert_eq!(tiled_pixels(&bytes16), (64, 48, pixels.clone()), "16-bit samples scaled to 8 bits"); } #[test] fn rotated_scaled_pixels_keep_the_full_affine_transform() { - let Some((_, doc, images)) = read_fixture("patchy-transform.af") else { return }; + let Some((bytes, doc, images)) = read_fixture("patchy-transform.af") else { return }; assert!(doc.warnings.is_empty()); assert_eq!(images.len(), 1); assert_eq!((images[0].width, images[0].height), (80, 60)); @@ -97,18 +161,19 @@ fn rotated_scaled_pixels_keep_the_full_affine_transform() { let Pixels::Rgba8(pixels) = &images[0].pixels else { panic!() }; assert_eq!(pixels.len(), 80 * 60 * 4); assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255)); - assert_eq!(crc32fast::hash(pixels), 0x3720a442); + assert_eq!(tiled_pixels(&bytes), (80, 60, pixels.clone())); } #[test] fn cmyk_pixels_stay_cmyk_and_lab_losses_are_reported() { // CMYK layers keep their inks for the importer to convert through a colour profile. - let Some((_, cmyk, images)) = read_fixture("patchy-cmyk.af") else { return }; + let Some((bytes, cmyk, images)) = read_fixture("patchy-cmyk.af") else { return }; assert_eq!(images.len(), 1); assert_eq!((images[0].width, images[0].height), (64, 48)); let Pixels::Cmyka8(pixels) = &images[0].pixels else { panic!() }; assert_eq!(pixels.len(), 64 * 48 * 5); - assert_eq!(crc32fast::hash(pixels), 0x56b1f659); + assert_eq!(tiled_pixels(&bytes), (64, 48, pixels.clone())); + assert!(pixels.as_chunks::<5>().0.iter().any(|p| p[0] != p[3]), "inks differ between channels"); assert!(cmyk.warnings.is_empty(), "{:?}", cmyk.warnings); assert_eq!(cmyk.cmyk_profile, None, "this file embeds no profile"); let (_, lab, images) = read_fixture("patchy-lab.af").unwrap(); diff --git a/crates/affinity/tests/support/affinity3-signatures.txt b/crates/affinity/tests/support/affinity3-signatures.txt index 79ed6df5ec..7afa67411f 100644 --- a/crates/affinity/tests/support/affinity3-signatures.txt +++ b/crates/affinity/tests/support/affinity3-signatures.txt @@ -1,33 +1,33 @@ -affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=32b7cf3f;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"] -affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=c10daaea;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"] -affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=3bc13374;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"] -affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=bc0c838d;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"] -patchy-adjust-curves.af dpi=72;spreads=1;model_crc32=36ab962f;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] -patchy-adjust-hsl.af dpi=72;spreads=1;model_crc32=e2eac05e;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] -patchy-artboards.af dpi=72;spreads=1;model_crc32=0037a28e;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[] -patchy-blend-affinity.af dpi=72;spreads=1;model_crc32=8497c917;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"] -patchy-cmyk.af dpi=72;spreads=1;model_crc32=56754ce9;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-dpi300.af dpi=300;spreads=1;model_crc32=2561f9d3;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-embedded-jpeg.af dpi=72;spreads=1;model_crc32=ab4b6fbf;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-fx-blur.af dpi=72;spreads=1;model_crc32=29b5083b;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["blur effects (left out) (2×)"] -patchy-fx-gradient.af dpi=72;spreads=1;model_crc32=96cd10be;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=[] -patchy-fx.af dpi=72;spreads=1;model_crc32=7c8d4d20;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=[] -patchy-group.af dpi=72;spreads=1;model_crc32=dc37ab6c;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[] -patchy-incremental-chain.af dpi=72;spreads=1;model_crc32=38c9c5f4;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-lab.af dpi=72;spreads=1;model_crc32=df3a4e40;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"] -patchy-lazy-placed.af dpi=72;spreads=1;model_crc32=8776a8a0;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-live-filter.af dpi=72;spreads=1;model_crc32=12235fe9;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"] -patchy-rgba16.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-rgba8.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-shapes-2.af dpi=72;spreads=1;model_crc32=6f174318;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 168, "shapes": 12, "strokes": 0, "subpaths": 13};boards=[];fonts={};warnings=[] -patchy-shapes.af dpi=72;spreads=1;model_crc32=c1790e97;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[] -patchy-text-artistic.af dpi=72;spreads=1;model_crc32=1d33192c;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[] -patchy-text-caps.af dpi=72;spreads=1;model_crc32=24e52518;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"] -patchy-text-frame.af dpi=72;spreads=1;model_crc32=3bff8ef9;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[] -patchy-text-indent.af dpi=72;spreads=1;model_crc32=dc36dfc5;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"] -patchy-text-para-spacing.af dpi=72;spreads=1;model_crc32=6408f39b;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"] -patchy-text-rotated.af dpi=72;spreads=1;model_crc32=3d1de559;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"] -patchy-text-runs.af dpi=72;spreads=1;model_crc32=7820b881;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"] -patchy-transform.af dpi=72;spreads=1;model_crc32=8d56df84;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-vector-mask.af dpi=72;spreads=1;model_crc32=80ca946a;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"] -patchy-vector.af dpi=72;spreads=1;model_crc32=3b16c7ed;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[] +affinity3-mexican-guy.af dpi=300;spreads=1;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"] +affinity3-mexican-man.af dpi=300;spreads=1;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"] +affinity3-mexican-woman.af dpi=300;spreads=1;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"] +affinity3-playing-cards.af dpi=300;spreads=1;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"] +patchy-adjust-curves.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] +patchy-adjust-hsl.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] +patchy-artboards.af dpi=72;spreads=1;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[] +patchy-blend-affinity.af dpi=72;spreads=1;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"] +patchy-cmyk.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-dpi300.af dpi=300;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-embedded-jpeg.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-fx-blur.af dpi=72;spreads=1;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["blur effects (left out) (2×)"] +patchy-fx-gradient.af dpi=72;spreads=1;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=[] +patchy-fx.af dpi=72;spreads=1;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=[] +patchy-group.af dpi=72;spreads=1;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[] +patchy-incremental-chain.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-lab.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"] +patchy-lazy-placed.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-live-filter.af dpi=72;spreads=1;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"] +patchy-rgba16.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-rgba8.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-shapes-2.af dpi=72;spreads=1;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 168, "shapes": 12, "strokes": 0, "subpaths": 13};boards=[];fonts={};warnings=[] +patchy-shapes.af dpi=72;spreads=1;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[] +patchy-text-artistic.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[] +patchy-text-caps.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"] +patchy-text-frame.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[] +patchy-text-indent.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"] +patchy-text-para-spacing.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"] +patchy-text-rotated.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"] +patchy-text-runs.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"] +patchy-transform.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-vector-mask.af dpi=72;spreads=1;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"] +patchy-vector.af dpi=72;spreads=1;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[] diff --git a/crates/affinity/tests/support/features.rs b/crates/affinity/tests/support/features.rs index f7024feb62..61eb43318b 100644 --- a/crates/affinity/tests/support/features.rs +++ b/crates/affinity/tests/support/features.rs @@ -1,8 +1,7 @@ //! Structural regression signatures, measured from the pinned files through our own reader. -//! These freeze feature retention; they are not independent visual or compatibility oracles. -//! The model CRC covers every decoded field via its Debug representation (including paths, -//! paint, masks, image pixels and text runs). A deliberate reader/Debug change needs review; -//! input authenticity is independently checked with SHA256 by the corpus gate. +//! They count retained features; they are not independent visual or compatibility oracles. +//! Pixels are checked against the stored tiles in `raster.rs`. Input authenticity is checked +//! with SHA256 by the corpus gate. use std::collections::{BTreeMap, BTreeSet}; use vectorcraft_affinity::model::{Document, Kind, Node}; use vectorcraft_affinity::paint::Paint; @@ -58,11 +57,5 @@ pub fn signature(doc: &Document) -> String { for spread in &doc.spreads { visit(&spread.nodes, &mut counts, &mut fonts, &mut boards, 1); } - let model_crc32 = crc32fast::hash(format!("{:?}", doc.spreads).as_bytes()); - format!( - "dpi={};spreads={};model_crc32={model_crc32:08x};counts={counts:?};boards={boards:?};fonts={fonts:?};warnings={:?}", - doc.dpi, - doc.spreads.len(), - doc.warnings - ) + format!("dpi={};spreads={};counts={counts:?};boards={boards:?};fonts={fonts:?};warnings={:?}", doc.dpi, doc.spreads.len(), doc.warnings) } diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index dd80644279..0d65d4695c 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1543,13 +1543,61 @@ fn export_bytes_match_shared_writer_goldens() { let out = export(&doc, &DxfOptions { version, ..opts(&doc) }).unwrap(); let got = std::str::from_utf8(&out.bytes).expect("UTF-8 DXF"); let path = dir.join(name); - if std::env::var_os("WRITE_DXF_GOLDENS").is_some() { - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(&path, got).unwrap(); - continue; - } let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display())); - assert_eq!(got, expected, "DXF bytes changed versus {}", path.display()); + assert_holds_shapes_doc(&expected, version); + if got != expected { + // Written for review only; a golden file changes by hand after its drawing checks pass. + let actual = std::env::temp_dir().join(format!("{name}.actual")); + let saved = std::fs::write(&actual, got).map_or_else(|e| format!("not saved: {e}"), |()| format!("saved to {}", actual.display())); + panic!("DXF bytes changed versus {} (output {saved})", path.display()); + } + } +} + +/// Checks that a golden file holds [`shapes_doc`] as the DXF Reference describes it, in a 200 × 100 pt +/// region with y up: the red fill and the black 1 pt stroke of the rectangle (10, 40)–(110, 90), and +/// the blue 2 pt circle of radius 30 around (150, 50). ACI colors 1, 5 and 7 are red, blue and +/// black/white; code 420 holds 0xRRGGBB; code 370 is lineweight in hundredths of a millimeter +/// (1 pt = 0.3528 mm gives 35, 2 pt gives 70); a POLYLINE vertex's bulge is tan(arc angle / 4). +fn assert_holds_shapes_doc(golden: &str, version: DxfVersion) { + let ents = section(&pairs(golden.as_bytes()), "ENTITIES"); + let colored = |aci: &str| -> Vec<&Pairs> { ents.iter().filter(|e| get(e, 62) == Some(aci)).collect() }; + // Every drawn point of the entities in one color; (0, 0) is the elevation point of POLYLINE + // and HATCH headers, which no shape of the drawing reaches. + let points = |aci: &str| -> Vec<(f64, f64)> { + colored(aci).iter().flat_map(|e| all(e, 10).into_iter().zip(all(e, 20))).filter(|p| *p != (0.0, 0.0)).collect() + }; + let bbox = |pts: &[(f64, f64)]| { + pts.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1))) + }; + for aci in ["1", "7"] { + let pts = points(aci); + assert_eq!(pts.len() % 4, 0, "{version:?} ACI {aci}: rectangle corners {pts:?}"); + assert_eq!(bbox(&pts), (10.0, 40.0, 110.0, 90.0), "{version:?} ACI {aci}"); + } + let circle = colored("5"); + assert!(!circle.is_empty(), "{version:?}: the blue circle"); + if let Some(c) = circle.iter().find(|e| kind(e) == "CIRCLE") { + assert_eq!((all(c, 10), all(c, 20), all(c, 40)), (vec![150.0], vec![50.0], vec![30.0]), "{version:?}"); + } else { + let pts = points("5"); + assert!(pts.len() >= 2, "{version:?}: circle vertices {pts:?}"); + for (x, y) in &pts { + assert!(((x - 150.0).hypot(y - 50.0) - 30.0).abs() < 1e-4, "{version:?}: vertex ({x}, {y}) off the circle"); + } + let turn: f64 = circle.iter().flat_map(|e| all(e, 42)).map(|b| 4.0 * b.atan()).sum(); + assert!((turn.abs() - std::f64::consts::TAU).abs() < 1e-4, "{version:?}: bulges sweep {turn} rad"); + } + if version >= DxfVersion::R2000 { + let code = |aci: &str, c: i32| -> Vec { colored(aci).iter().filter_map(|e| get(e, c)).map(str::to_string).collect() }; + assert!(code("1", 420).iter().all(|v| v == "16711680") && !code("1", 420).is_empty(), "{version:?}: red true color"); + assert_eq!(code("7", 420), ["0"], "{version:?}: black true color"); + assert_eq!(code("5", 420), ["255"], "{version:?}: blue true color"); + assert_eq!(code("7", 370), ["35"], "{version:?}: 1 pt stroke"); + assert_eq!(code("5", 370), ["70"], "{version:?}: 2 pt stroke"); + } else { + let stroke = colored("7"); + assert_eq!((all(stroke[0], 40), all(stroke[0], 41)), (vec![1.0], vec![1.0]), "{version:?}: 1 pt polyline width"); } } From d22296ce8220c72f79385ccb45417d53ce7d4096 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:36:00 -0800 Subject: [PATCH 62/72] Tests: engine assertions check the exact drag offset, dither shares and colors The Alt-drag test now requires the 80 pt offset instead of any positive x. The pattern transparency dither tests check the exact 25% and 75% opaque shares. The plug-in tests' near() allows 2 levels per channel instead of 40. --- crates/engine/src/cmd/fileio/tests_palette.rs | 4 ++++ crates/engine/src/tests/large_edits.rs | 2 +- crates/engine/src/tests/plugins.rs | 6 +++--- crates/engine/src/tests/webexport.rs | 4 ++++ 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_palette.rs b/crates/engine/src/cmd/fileio/tests_palette.rs index d27166e5da..1ef846806e 100644 --- a/crates/engine/src/cmd/fileio/tests_palette.rs +++ b/crates/engine/src/cmd/fileio/tests_palette.rs @@ -120,6 +120,10 @@ fn palette_exports_take_the_transparency_dither() { let dithered = file(json!({"transparencyDither": method})); let [left, right] = opaque_halves(&dithered); assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}"); + if method == "pattern" { + // The ordered pattern keeps exactly one pixel of each 2x2 cell at 25% and three at 75%. + assert_eq!([left, right], [0.25, 0.75], "{format}"); + } assert_eq!(file(json!({"transparencyDither": method})), dithered, "{format} {method}: the same art gives the same file"); // Without transparency the dither does nothing. let opaque = file(json!({"transparencyDither": method, "transparency": false})); diff --git a/crates/engine/src/tests/large_edits.rs b/crates/engine/src/tests/large_edits.rs index 2806cdd925..19cbe75c56 100644 --- a/crates/engine/src/tests/large_edits.rs +++ b/crates/engine/src/tests/large_edits.rs @@ -435,7 +435,7 @@ fn alt_drag_of_30000_objects_takes_few_tree_walks() { assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Copy")); // The squares stay; their copies move together. let moved = bounds(&s, copies[0]).origin() - square_at(0).origin(); - assert!(moved.x > 0.0, "{moved:?}"); + assert!((moved.x - 80.0).abs() < 1e-6 && moved.y.abs() < 1e-6, "the copies move by the drag: {moved:?}"); for (k, (id, copy)) in ids.iter().zip(&copies).enumerate() { assert_eq!(bounds(&s, *id), square_at(k)); assert_eq!(bounds(&s, *copy), square_at(k) + moved); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 836daf8b05..5fe28b4639 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -1545,10 +1545,10 @@ fn kept_art_follows_the_swatches_once_a_replaced_plugin_paints() { assert_eq!(draw(&s), (WHITE, RED), "without the swatch, the object as it is"); } -/// Whether `px` is within 40 levels of `want` on every channel. A blur leaves the middle of a -/// shape close to its color. +/// Whether `px` is within 2 levels of `want` on every channel. The samples sit well inside their +/// shapes, so a blur changes them only by rounding. fn near(px: [u8; 4], want: [u8; 4]) -> bool { - px.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 40) + px.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 2) } /// A kept raster of a blur over a painted effect is made again when a swatch its piece names diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index 0d1d6b50a8..656a5689f8 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -197,6 +197,10 @@ fn transparency_dither_keeps_a_share_of_partly_transparent_pixels() { let dithered = file(&mut s, p.clone()); let [left, right] = opaque_halves(&pixels(&dithered)); assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}"); + if method == "pattern" { + // The ordered pattern keeps exactly one pixel of each 2x2 cell at 25% and three at 75%. + assert_eq!([left, right], [0.25, 0.75], "{format}"); + } if format == "gif" { assert_eq!(gif_transparent_index(&dithered), Some(0), "{method}"); } From 888df1c1c89d23ad7f9cc24f091a58a4dfb1fcb2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:39:28 -0800 Subject: [PATCH 63/72] Tests: tighten loose tolerances in geom, pathops, trace and three-d - The two-anchor ellipse test now expects the exact area of its two cubics, 4/5 of the box (4800), instead of a 10% band around the true ellipse that accepted handles moved 10 pt inward (4560). - The abutting trace seam must sit within 0.05 px of the anti-aliased edge at x = 10.4, so snapping it to a whole pixel fails. - The straight-on shadow area is compared exactly with 10000: the sampling grid has 1 pt2 cells and no sample on the square's edge. - The pinned Pathfinder inputs now also get a point check: for Unite, Minus Front, Minus Back, Intersect and Exclude, every grid point away from an input edge must be inside the output exactly when the inputs covering it say so, so the pins no longer rest on the sweep that computed them alone. --- crates/geom/src/shapes.rs | 7 ++- crates/pathops/tests/it/pathfinder_pinned.rs | 61 +++++++++++++++++++- crates/three-d/src/shadow/tests.rs | 5 +- crates/trace/src/seam.rs | 2 +- 4 files changed, 70 insertions(+), 5 deletions(-) diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index f3ab848e81..2d23c4c3bc 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -1382,7 +1382,12 @@ mod tests { "{n}: {b:?}" ); let area = p.subpaths[0].area().abs(); - assert!((area - PI * 50.0 * 30.0).abs() / area < if n == 2 { 0.1 } else { 0.01 }, "{n}: {area}"); + if n == 2 { + // Two cubics with handles 4/3 of the half height long: each encloses 2/5 of the box. + assert!((area - 0.8 * 100.0 * 60.0).abs() < 1e-8, "{n}: {area}"); + } else { + assert!((area - PI * 50.0 * 30.0).abs() / area < 0.01, "{n}: {area}"); + } } // A box with no height leaves the path flat rather than dividing by zero. let flat = ellipse_with_anchors(Rect::new(0.0, 5.0, 40.0, 5.0), 6); diff --git a/crates/pathops/tests/it/pathfinder_pinned.rs b/crates/pathops/tests/it/pathfinder_pinned.rs index 85f9ca423c..14fadbc6cb 100644 --- a/crates/pathops/tests/it/pathfinder_pinned.rs +++ b/crates/pathops/tests/it/pathfinder_pinned.rs @@ -1,7 +1,10 @@ //! The exact output of every Pathfinder operation, pinned so that work on the windings and the //! coverage tests can't change it: overlapping ellipses, rectangles and stars (even-odd and -//! non-zero, repeated keys for Merge) at a few counts. +//! non-zero, repeated keys for Merge) at a few counts. The filled regions of Unite, Minus Front, +//! Minus Back, Intersect and Exclude on the same inputs are also checked point by point against the +//! inputs' own coverage, so the pins do not rest on the sweep that computed them alone. +use kurbo::{BezPath, Shape as _}; use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath, shapes}; use vectorcraft_pathops::{PathfinderOp, Shape, pathfinder}; @@ -78,6 +81,62 @@ fn every_pathfinder_operation_is_pinned() { assert_eq!(got, PINNED); } +/// Whether an operation's output covers a point, from which inputs cover it. +type CoverRule = fn(&[bool]) -> bool; + +/// Shapes as kurbo paths with their fill rules. +type Filled = Vec<(BezPath, FillRule)>; + +fn inside(path: &BezPath, rule: FillRule, p: kurbo::Point) -> bool { + let w = path.winding(p); + match rule { + FillRule::NonZero => w != 0, + FillRule::EvenOdd => w % 2 != 0, + } +} + +#[test] +fn the_pinned_inputs_fill_what_their_coverage_says() { + use PathfinderOp::*; + // Which inputs cover a point decides whether each operation's output covers it. + let rules: [(PathfinderOp, CoverRule); 5] = [ + (Unite, |m| m.iter().any(|&c| c)), + (MinusFront, |m| m[0] && !m[1..].iter().any(|&c| c)), + (MinusBack, |m| m[m.len() - 1] && !m[..m.len() - 1].iter().any(|&c| c)), + (Intersect, |m| m.iter().all(|&c| c)), + (Exclude, |m| m.iter().filter(|&&c| c).count() % 2 == 1), + ]; + for (n, seed) in [(2, 3), (5, 7), (12, 11), (30, 13)] { + let input = shapes_of(n, seed); + let paths: Filled = input.iter().map(|s| (s.path.to_bezpath(), s.rule)).collect(); + let cover = |p: kurbo::Point| paths.iter().map(|(b, r)| inside(b, *r, p)).collect::>(); + let outputs: Vec<(PathfinderOp, CoverRule, Filled)> = + rules.iter().map(|&(op, rule)| (op, rule, pathfinder(op, &input).iter().map(|s| (s.path.to_bezpath(), s.rule)).collect())).collect(); + let (mut checked, mut filled) = (0, 0); + // A grid whose pitch shares no factor with the inputs' coordinates; points within 0.25 pt + // of an input edge are skipped, since the output's edge may sit there within the precision. + for i in 0..200 { + for j in 0..160 { + let p = kurbo::Point::new(-60.0 + f64::from(i) * 1.37, -60.0 + f64::from(j) * 1.37); + let m = cover(p); + let near_edge = [(0.25, 0.25), (-0.25, 0.25), (0.25, -0.25), (-0.25, -0.25)] + .iter() + .any(|&(dx, dy)| cover(kurbo::Point::new(p.x + dx, p.y + dy)) != m); + if near_edge { + continue; + } + checked += 1; + for (op, rule, out) in &outputs { + let got = out.iter().any(|(b, r)| inside(b, *r, p)); + assert_eq!(got, rule(&m), "{op:?} n={n} at {p:?}, covered by {m:?}"); + filled += usize::from(got); + } + } + } + assert!(checked > 10_000 && filled > 1_000, "n={n}: {checked} points, {filled} filled"); + } +} + /// Computed with the sweep of craft-libs 610c86792a, which places output curves closer to their /// inputs than the one before (craft-libs#721): every output keeps its shapes, subpaths and /// anchors, and its area and length agree with the earlier pins to 1e-6 relative. diff --git a/crates/three-d/src/shadow/tests.rs b/crates/three-d/src/shadow/tests.rs index 2d80c2ea61..f6f9806a43 100644 --- a/crates/three-d/src/shadow/tests.rs +++ b/crates/three-d/src/shadow/tests.rs @@ -49,9 +49,10 @@ fn a_light_straight_in_front_casts_the_silhouette_behind_the_object() { for (got, want) in [(b.x0, 100.0), (b.y0, 100.0), (b.x1, 200.0), (b.y1, 200.0)] { assert!((got - want).abs() < 1e-6, "{b:?}"); } - // Every face of the box projects into the square, and the nonzero union fills it whole. + // Every face of the box projects into the square, and the nonzero union fills it whole. Each + // sample stands for 1 pt² and none lies on the square's edge, so the count is exact. let area = covered(&path, Rect::new(90.0, 90.0, 210.0, 210.0), 120); - assert!((area - 10_000.0).abs() < 300.0, "{area}"); + assert_eq!(area, 10_000.0); } #[test] diff --git a/crates/trace/src/seam.rs b/crates/trace/src/seam.rs index b0c6447d8a..6882903af9 100644 --- a/crates/trace/src/seam.rs +++ b/crates/trace/src/seam.rs @@ -311,7 +311,7 @@ mod tests { assert!(keys(seam).iter().all(|k| lower.contains(k) && upper.contains(k))); assert!(seam.path.anchor_count() <= res.anchor_count()); for a in seam.path.subpaths.iter().flat_map(|sp| &sp.anchors) { - assert!((a.p.x - 10.4).abs() < 0.5, "{a:?}"); + assert!((a.p.x - 10.4).abs() < 0.05, "{a:?}"); } let ys: Vec = seam.path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p.y)).collect(); assert_eq!((ys.iter().copied().fold(f64::INFINITY, f64::min), ys.iter().copied().fold(f64::NEG_INFINITY, f64::max)), (0.0, 16.0)); From e6d6769d02deaceb0c76631d3b78b7f38e40ff5e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:45:34 -0800 Subject: [PATCH 64/72] Tests: check DXF golden rectangle edges and circle arcs segment by segment --- crates/cad/src/tests.rs | 42 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index 0d65d4695c..6140395323 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1574,6 +1574,16 @@ fn assert_holds_shapes_doc(golden: &str, version: DxfVersion) { let pts = points(aci); assert_eq!(pts.len() % 4, 0, "{version:?} ACI {aci}: rectangle corners {pts:?}"); assert_eq!(bbox(&pts), (10.0, 40.0, 110.0, 90.0), "{version:?} ACI {aci}"); + // Each run of four points is one outline of the rectangle: all four corners, each joined to + // the next (and the last to the first) by a horizontal or vertical edge. + let corners = [(10.0, 40.0), (110.0, 40.0), (110.0, 90.0), (10.0, 90.0)]; + for quad in pts.chunks(4) { + assert!(corners.iter().all(|c| quad.contains(c)), "{version:?} ACI {aci}: corners {quad:?}"); + for (i, a) in quad.iter().enumerate() { + let b = quad[(i + 1) % 4]; + assert!((a.0 == b.0) != (a.1 == b.1), "{version:?} ACI {aci}: edge {a:?} to {b:?} in {quad:?}"); + } + } } let circle = colored("5"); assert!(!circle.is_empty(), "{version:?}: the blue circle"); @@ -1587,6 +1597,38 @@ fn assert_holds_shapes_doc(golden: &str, version: DxfVersion) { } let turn: f64 = circle.iter().flat_map(|e| all(e, 42)).map(|b| 4.0 * b.atan()).sum(); assert!((turn.abs() - std::f64::consts::TAU).abs() < 1e-4, "{version:?}: bulges sweep {turn} rad"); + // Each segment, the closing one included, is an arc of the circle: the point halfway along it, + // which lies bulge × chord / 2 to the right of the chord's middle, is on the circle too. + let mut verts: Vec<((f64, f64), f64)> = Vec::new(); + for e in &circle { + let mut x = None; + for (c, v) in e.iter() { + let n = || v.trim().parse::().expect("a number"); + match c { + 10 => x = Some(n()), + 20 => { + let p = (x.take().unwrap_or(f64::NAN), n()); + if p != (0.0, 0.0) { + verts.push((p, 0.0)); + } + } + 42 => { + if let Some(last) = verts.last_mut() { + last.1 = n(); + } + } + _ => {} + } + } + } + for (i, &((px, py), b)) in verts.iter().enumerate() { + let (qx, qy) = verts[(i + 1) % verts.len()].0; + let (mx, my) = (px + (qx - px) / 2.0 + b * (qy - py) / 2.0, py + (qy - py) / 2.0 - b * (qx - px) / 2.0); + assert!( + ((mx - 150.0).hypot(my - 50.0) - 30.0).abs() < 1e-4, + "{version:?}: segment ({px}, {py}) to ({qx}, {qy}) with bulge {b} leaves the circle at ({mx}, {my})" + ); + } } if version >= DxfVersion::R2000 { let code = |aci: &str, c: i32| -> Vec { colored(aci).iter().filter_map(|e| get(e, c)).map(str::to_string).collect() }; From 72b0bdad60b1cdf857bb2c96e866057a63243fe5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:34:14 -0800 Subject: [PATCH 65/72] Tests: Smart Blur checks hand-calculated pixels at radius 2 and 12 The Normal-mode test compares the default output with blurMode=normal, so a fault both share passes it. Three checks now stand on their own: - A 6-pixel row at radius 2 checks exact averages that a radius-1 search gives differently (105 and 115 at the ends instead of 110). - A step from gray 100 to 200 at radius 12 checks that the pixels next to the step read the box-blurred copy at threshold 50 and keep their gray at threshold 30, that pixels far from the step keep theirs, and that medium quality takes in less of the other gray than low. - A one-column gray-200 stripe at radius 12 checks that a neighbour whose own value is past the threshold stays out even when its blurred value is within it. - A 5 x 5 image at radius 2 checks that a pixel two columns away counts and one two columns and two rows away (outside the disc) does not. - A 7 x 7 image with default settings checks that the default radius of 3 reaches a pixel three columns away. - The radius-1 threshold test gives its last two pixels the same color with alpha 255 and 128, so it fails if alpha is left out. --- crates/effects/src/pixel/tests.rs | 104 +++++++++++++++++++++++++++++- 1 file changed, 102 insertions(+), 2 deletions(-) diff --git a/crates/effects/src/pixel/tests.rs b/crates/effects/src/pixel/tests.rs index f2f66b2dd4..eff3af66ed 100644 --- a/crates/effects/src/pixel/tests.rs +++ b/crates/effects/src/pixel/tests.rs @@ -714,14 +714,16 @@ fn smart_blur_normal_mode_keeps_its_pixels() { /// Smart Blur at radius 1 averages each pixel with the neighbours whose channels, alpha included, /// all lie within the threshold: grays 100 and 110 average to 105 each, 200 is 90 levels from 110 -/// and stays, and the half-covered pixel next to it differs in alpha and stays too. +/// and stays, and the two grays 100 after it have the same color but alpha 255 and 128, so neither +/// takes the other. #[test] fn smart_blur_averages_only_the_neighbours_within_the_threshold() { - let (w, h) = (4, 1); + let (w, h) = (5, 1); let src = image(w, h, |x, _| match x { 0 => [100, 100, 100, 255], 1 => [110, 110, 110, 255], 2 => [200, 200, 200, 255], + 3 => [100, 100, 100, 255], _ => [100, 100, 100, 128], }); let mut d = src.clone(); @@ -730,6 +732,104 @@ fn smart_blur_averages_only_the_neighbours_within_the_threshold() { assert_eq!(at(&d, w, 1, 0), [105, 105, 105, 255]); assert_eq!(at(&d, w, 2, 0), [200, 200, 200, 255]); assert_eq!(at(&d, w, 3, 0), at(&src, w, 3, 0)); + assert_eq!(at(&d, w, 4, 0), at(&src, w, 4, 0)); +} + +/// Smart Blur at radius 12 reads its neighbours from a box-blurred copy. Next to a step from gray +/// 100 to gray 200 that copy holds values between them, so at threshold 50 the pixel on the dark +/// side of the step takes in some lighter gray and the pixel on the light side some darker gray, +/// while pixels more than 15 pixels from the step keep their gray. Medium quality takes in less of +/// the other gray than low, and at threshold 30 the pixels next to the step keep their gray. +#[test] +fn smart_blur_at_a_wide_radius_reads_the_blurred_copy_next_to_an_edge() { + let (w, h) = (60, 40); + let src = image(w, h, |x, _| grey(if x < 30 { 100 } else { 200 })); + let mut d = src.clone(); + fx("blur.smart", json!({"radius": 12, "threshold": 50, "quality": "low"})).apply(&mut d, w, h, &space(w, h)); + let dark = at(&d, w, 29, 20)[0]; + let light = at(&d, w, 30, 20)[0]; + assert!((101..=150).contains(&dark), "the dark side takes in some lighter gray: {dark}"); + assert!((150..=199).contains(&light), "the light side takes in some darker gray: {light}"); + assert_eq!(at(&d, w, 10, 20), grey(100)); + assert_eq!(at(&d, w, 50, 20), grey(200)); + // Medium quality spreads 7 samples instead of 5, read from a copy blurred over 2 pixels instead + // of 3, so less of the other gray reaches the pixels next to the step. + let mut medium = src.clone(); + fx("blur.smart", json!({"radius": 12, "threshold": 50, "quality": "medium"})).apply(&mut medium, w, h, &space(w, h)); + let (medium_dark, medium_light) = (at(&medium, w, 29, 20)[0], at(&medium, w, 30, 20)[0]); + assert!(100 < medium_dark && medium_dark < dark, "medium {medium_dark}, low {dark}"); + assert!(light < medium_light && medium_light < 200, "medium {medium_light}, low {light}"); + // At threshold 30 the blurred values next to the step are too far from both grays, and the + // pixels on either side keep their gray. + let mut sharp = src.clone(); + fx("blur.smart", json!({"radius": 12, "threshold": 30, "quality": "low"})).apply(&mut sharp, w, h, &space(w, h)); + assert_eq!(at(&sharp, w, 29, 20), grey(100)); + assert_eq!(at(&sharp, w, 30, 20), grey(200)); +} + +/// Smart Blur at radius 12 and low quality samples offsets 0, 6 and 12 pixels along each axis, +/// in both directions, within distance 12.5. A one-column gray-200 stripe at x = 30 on gray 100 +/// becomes (6 * 100 + 200) / 7, about 114.29, in the copy box-blurred with radius 3. For the +/// gray-100 pixel at (24, 20), only the three samples at x = 30 have blurred values above 100. +/// Their own value 200 is outside threshold 30, so they are excluded and the result stays 100. +/// Including them would average ten samples of 100 with three of about 114.29 and round to 103. +#[test] +fn smart_blur_at_a_wide_radius_rejects_a_stripes_own_value_outside_the_threshold() { + let (w, h) = (60, 40); + let src = image(w, h, |x, _| grey(if x == 30 { 200 } else { 100 })); + let mut d = src.clone(); + fx("blur.smart", json!({"radius": 12, "threshold": 30, "quality": "low"})).apply(&mut d, w, h, &space(w, h)); + assert_eq!(at(&d, w, 24, 20), grey(100)); +} + +/// Smart Blur at radius 2 reaches two pixels each way: grays 100, 110 and 120 lie within 20 levels +/// of each other and all average to 110 (at radius 1 the ends would give 105 and 115), 200 and 210 +/// average to 205, and 60 is too far from both groups and stays. +#[test] +fn smart_blur_at_radius_two_averages_the_neighbours_two_pixels_away() { + let (w, h) = (6, 1); + let src = image(w, h, |x, _| grey([100, 110, 120, 200, 210, 60][x])); + let mut d = src.clone(); + fx("blur.smart", json!({"radius": 2, "threshold": 20, "quality": "high"})).apply(&mut d, w, h, &space(w, h)); + let want = image(w, h, |x, _| grey([110, 110, 110, 205, 205, 60][x])); + assert_eq!(d, want); +} + +/// Smart Blur at radius 2 and high quality reads the original pixels within distance 2.5. +/// The center at (2, 2) is gray 100, one neighbor is gray 120, and the rest are gray 200, +/// outside threshold 20. A neighbor at (4, 2) is two pixels away, so the center averages +/// (100 + 120) / 2 = 110. A neighbor at (4, 4) is sqrt(8), about 2.83 pixels away, so it is +/// excluded and the center stays 100. Reading the whole square would give 110 in both cases. +#[test] +fn smart_blur_at_radius_two_keeps_the_neighbours_inside_the_disc() { + let (w, h) = (5, 5); + for ((nx, ny), want) in [((4, 2), 110), ((4, 4), 100)] { + let src = image(w, h, |x, y| match (x, y) { + (2, 2) => grey(100), + p if p == (nx, ny) => grey(120), + _ => grey(200), + }); + let mut d = src.clone(); + fx("blur.smart", json!({"radius": 2, "threshold": 20, "quality": "high"})).apply(&mut d, w, h, &space(w, h)); + assert_eq!(at(&d, w, 2, 2), grey(want), "neighbor at ({nx}, {ny})"); + } +} + +/// Smart Blur's default radius 3 and medium quality (7 samples) read every integer offset +/// in the 7 by 7 square without prefiltering, keeping offsets within distance 3.5. +/// The center at (3, 3) is gray 100, its neighbor at (6, 3) is gray 120, and the rest are +/// gray 200, outside the default threshold 25. The center averages (100 + 120) / 2 = 110. +/// A search limited to two pixels would leave the center at 100. +#[test] +fn smart_blur_default_radius_averages_the_neighbour_three_pixels_away() { + let (w, h) = (7, 7); + let mut d = image(w, h, |x, y| match (x, y) { + (3, 3) => grey(100), + (6, 3) => grey(120), + _ => grey(200), + }); + fx("blur.smart", json!({})).apply(&mut d, w, h, &space(w, h)); + assert_eq!(at(&d, w, 3, 3), grey(110)); } /// Smart Blur's test image: grays 56 and 64 in a checkerboard for x < 3 and 66 and 74 for x in 3..6 From 6a34a994bba95705a10db4a66961bfd42ffd6ef5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 03:35:40 -0800 Subject: [PATCH 66/72] xtask: census skips loops with a break and rejections across && A break can end a whole-table loop before the last entry, and an unwrap_err() or expect_err() on the other side of an && always runs, so neither is a presence-only census. --- xtask/src/test_lint.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 6b40bf8423..437efea639 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1355,7 +1355,8 @@ fn census(v: &View, helpers: &HashSet) -> Vec { let Some(close) = matching(m, open) else { continue }; let pattern = String::from_utf8_lossy(&m[at + 3..kw]); let var = pattern.split_whitespace().last().unwrap_or("").trim_start_matches('&'); - if whole_table(&norm(&m[kw + 2..open])) && weak_in(open, close, var) { + // A `break` in the body can end the loop before it reaches every entry. + if whole_table(&norm(&m[kw + 2..open])) && words(m, b"break", open, close).is_empty() && weak_in(open, close, var) { return vec![v.whole(Rule::Census, "loops over every entry of a table and checks only presence or a round trip".into())]; } } @@ -1382,7 +1383,11 @@ fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool census_condition(&cond[1..cond.len() - 1], depth + 1, helpers) } else if let Some(at) = or.or_else(|| top_level_at(cond, "&&").first().copied()) { let side = |s: &str| { - if s.contains(".all(") { census_condition(s, depth + 1, helpers) } else { (weak_predicate(s) && !calls_any(s, helpers), false) } + if s.contains(".all(") { + census_condition(s, depth + 1, helpers) + } else { + (weak_predicate(s) && !calls_any(s, helpers) && !rejects(s.as_bytes()), false) + } }; let (l, r) = (side(&cond[..at]), side(&cond[at + 2..])); let r = if or.is_some() && (calls_any(&cond[..at], helpers) || rejects(&cond.as_bytes()[..at])) { (false, false) } else { r }; @@ -3017,6 +3022,11 @@ mod tests { assert_eq!(census_in(skips, &ctx()), [(2, "census")], "a rejection after a presence check on an || can be skipped"); let first = "#[test]\nfn t() {\n assert!(parse(invalid).unwrap_err().contains(\"bad\") || CASES.iter().all(|c| c.is_some()));\n}\n"; assert_eq!(census_in(first, &ctx()), [], "a rejection on the left of an || always runs"); + let and_rejects = "#[test]\nfn t() {\n assert!(CASES.iter().all(|c| c.is_some()) && parse(invalid).unwrap_err().is_empty());\n}\n"; + assert_eq!(census_in(and_rejects, &ctx()), [], "a rejection on the other side of an && always runs"); + let broken = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some());\n break;\n }\n}\n"; + assert_eq!(census_in(broken, &ctx()), [], "a break can end the loop before the last entry"); + assert_eq!(census_in(&broken.replace(" break;\n", ""), &ctx()), [(2, "census")]); let only_ok = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n }\n}\n"; assert_eq!(census_in(only_ok, &ctx()), [(2, "census")]); let all_helper = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| exercise(c).is_some()));\n}\nfn exercise(c: &Color) -> Option<()> {\n assert_eq!(blend(c), WHITE);\n Some(())\n}\n"; From 4de23f0c9570817b10a8c62693e028b083b44efc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 04:06:08 -0800 Subject: [PATCH 67/72] Tests: census skips helper sources and negated rejection checks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A whole-table loop or .all(…) whose source calls an asserting helper runs that helper for every entry, so census no longer reports it. A negated is_ok() or is_some() checks a rejection and is no longer counted as a presence check; !is_empty() still is. --- xtask/src/test_lint.rs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 437efea639..5cc0a180aa 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1356,7 +1356,12 @@ fn census(v: &View, helpers: &HashSet) -> Vec { let pattern = String::from_utf8_lossy(&m[at + 3..kw]); let var = pattern.split_whitespace().last().unwrap_or("").trim_start_matches('&'); // A `break` in the body can end the loop before it reaches every entry. - if whole_table(&norm(&m[kw + 2..open])) && words(m, b"break", open, close).is_empty() && weak_in(open, close, var) { + // An asserting helper in the loop source runs for every entry, like one in the body. + if whole_table(&norm(&m[kw + 2..open])) + && helpers_in(kw + 2, open).is_empty() + && words(m, b"break", open, close).is_empty() + && weak_in(open, close, var) + { return vec![v.whole(Rule::Census, "loops over every entry of a table and checks only presence or a round trip".into())]; } } @@ -1444,7 +1449,7 @@ fn weak_table_all(op: &str, helpers: &[String]) -> bool { let end = arg_end(rest); // A rejection call checks something only on the branches that run it, like an asserting helper. let checks: Vec = helpers.iter().cloned().chain(["unwrap_err".into(), "expect_err".into()]).collect(); - rest[end..] == *")" && whole_table(receiver) && presence_only(&rest[..end], &checks, 0) + rest[end..] == *")" && whole_table(receiver) && !calls_any(&op[..i], helpers) && presence_only(&rest[..end], &checks, 0) } /// Whether `body` calls `.unwrap_err()` or `.expect_err(`, with any whitespace inside the call. @@ -1558,7 +1563,12 @@ fn weak_predicate(pred: &str) -> bool { if let Some(at) = boolean_split(pred) { return weak_predicate(&pred[..at]) && weak_predicate(&pred[at + 2..]); } + let negated = (pred.len() - pred.trim_start_matches('!').len()) % 2 == 1; let pred = pred.trim_start_matches('!'); + // A negated check is a presence check only for `!….is_empty()`; `!….is_ok()` checks a rejection. + if negated && !pred.ends_with(".is_empty()") { + return false; + } if let Some(list) = pred.strip_suffix(".len()>0") { return !list.contains(['=', '<', '>']); } @@ -3051,6 +3061,16 @@ mod tests { assert_eq!(census_in(&generic, &with_helpers), [], "a helper called with a turbofish"); let enforced = "#[test]\nfn t() {\n for case in CASES {\n assert!(!case.is_empty());\n let Ok(_) = parse(case) else { panic!(\"parse failed\") };\n }\n}\n"; assert_eq!(census_in(enforced, &ctx()), [(2, "census")], "a panic that only enforces success"); + let mapped = "#[test]\nfn t() {\n assert!(COLORS.iter().map(|c| { verify_entry(c); c }).all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(mapped, &ctx()), [], "a helper in the .all(…) receiver runs for every entry"); + assert_eq!(census_in(&mapped.replace("verify_entry(c); ", ""), &ctx()), [(2, "census")]); + let sourced = "#[test]\nfn t() {\n for c in COLORS.iter().map(|c| { verify_entry(c); c }) {\n assert!(c.is_some());\n }\n}\n"; + assert_eq!(census_in(sourced, &ctx()), [], "a helper in the loop source runs for every entry"); + assert_eq!(census_in(&sourced.replace("verify_entry(c); ", ""), &ctx()), [(2, "census")]); + let refused = "#[test]\nfn t() {\n for case in CASES {\n assert!(!parse(case.invalid).is_ok());\n }\n for case in CASES {\n assert!(!lookup(case.missing).is_some());\n }\n}\n"; + assert_eq!(census_in(refused, &ctx()), [], "a negated is_ok or is_some checks a rejection"); + let filled = "#[test]\nfn t() {\n for c in COLORS {\n assert!(!c.name.is_empty());\n }\n}\n"; + assert_eq!(census_in(filled, &ctx()), [(2, "census")]); } #[test] From b26f833acf9e0a48cf51fbd3622b01255f310d8d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 04:37:05 -0800 Subject: [PATCH 68/72] Vector Halftone: round and diamond dots stay in their cell Circle, Ellipse and Diamond dots were sized by their own area and drew past their cell once they reached its sides. In dark tones neighbors of different sizes overlapped into notches and slivers where the dots joined, and even full black left white specks at the cell corners. These dots are now clipped to their cell and sized so the clipped dot covers the tone. Neighbors meet along the shared side, and full tone fills the whole cell. Light tones, where the dot stays inside its cell, draw as before. --- crates/effects/src/addons/halftone.rs | 168 ++++++++++++++++++++++---- 1 file changed, 146 insertions(+), 22 deletions(-) diff --git a/crates/effects/src/addons/halftone.rs b/crates/effects/src/addons/halftone.rs index 371f664781..d371bfb363 100644 --- a/crates/effects/src/addons/halftone.rs +++ b/crates/effects/src/addons/halftone.rs @@ -90,16 +90,10 @@ impl DotShape { fn path(self, t: f64, s: f64) -> PathData { let square = |side: f64| shapes::rectangle(Rect::from_center_size(Point::ZERO, (side, side))); match self { - DotShape::Circle => { - let r = s * (t / std::f64::consts::PI).sqrt(); - shapes::ellipse(Rect::from_center_size(Point::ZERO, (2.0 * r, 2.0 * r))) - } - DotShape::Ellipse => { - let r = s * (t / std::f64::consts::PI).sqrt(); - shapes::ellipse(Rect::from_center_size(Point::ZERO, (2.6 * r, 2.0 * r / 1.3))) - } + DotShape::Circle => cell_dot(t, s / 2.0, CellKind::Circle), + DotShape::Ellipse => cell_dot(t, s / 2.0, CellKind::Ellipse), DotShape::Square => square(s * t.sqrt()), - DotShape::Diamond => square(s * t.sqrt()).transformed(Affine::rotate(std::f64::consts::FRAC_PI_4)), + DotShape::Diamond => cell_dot(t, s / 2.0, CellKind::Diamond), // Cells along a row join into a line as thick as the tone. DotShape::Line => shapes::rectangle(Rect::from_center_size(Point::ZERO, (s * 1.001, s * t))), DotShape::Euclidean => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Euclidean)), @@ -296,6 +290,9 @@ fn spot_quadrant(u: f64, h: f64, kind: SpotKind) -> Vec { /// the cell with the dot of the opposite tone cut out at each corner, so the dark joins up and the /// light becomes holes. fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath { + if t <= 0.5 { + return four_quadrants(&spot_quadrant(t, h, kind)); + } let mut bp = BezPath::new(); let mut add = |curves: Vec, first: bool| { for (k, c) in curves.iter().enumerate() { @@ -305,20 +302,129 @@ fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath { bp.curve_to(c.p1, c.p2, c.p3); } }; - if t <= 0.5 { - let q1 = spot_quadrant(t, h, kind); - add(q1.clone(), true); - add(reversed(&mapped(&q1, |p| Point::new(-p.x, p.y))), false); - add(mapped(&q1, |p| Point::new(-p.x, -p.y)), false); - add(reversed(&mapped(&q1, |p| Point::new(p.x, -p.y))), false); - } else { - // Round the corners counterclockwise, each one's hole the dot of the opposite tone. - let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind); - add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true); - add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false); - add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false); - add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false); + // Round the corners counterclockwise, each one's hole the dot of the opposite tone. + let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind); + add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true); + add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false); + add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false); + add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false); + bp.close_path(); + bp +} + +/// The dots that grow past their cell's sides: drawn clipped to the cell, so neighbors meet along +/// the shared side instead of overlapping, sized so the clipped dot covers the tone, and the whole +/// cell at full tone. +#[derive(Clone, Copy)] +enum CellKind { + Circle, + /// 1.69 times as wide as tall. + Ellipse, + Diamond, +} + +static CELL_CIRCLE: OnceLock> = OnceLock::new(); +static CELL_ELLIPSE: OnceLock> = OnceLock::new(); +static CELL_DIAMOND: OnceLock> = OnceLock::new(); + +impl CellKind { + /// The first quadrant of the dot of size `r` clipped to the quadrant [0, 1]², from the x axis to + /// the y axis. Circle: radius `r`; Ellipse: semi-axes 1.3 `r` and `r` / 1.3; Diamond: half + /// diagonal `r`. + fn quadrant(self, r: f64) -> Vec { + let corner = Point::new(1.0, 1.0); + match self { + CellKind::Diamond if r <= 1.0 => vec![segment(Point::new(r, 0.0), Point::new(0.0, r))], + CellKind::Diamond if r < 2.0 => vec![ + segment(Point::new(1.0, 0.0), Point::new(1.0, r - 1.0)), + segment(Point::new(1.0, r - 1.0), Point::new(r - 1.0, 1.0)), + segment(Point::new(r - 1.0, 1.0), Point::new(0.0, 1.0)), + ], + CellKind::Diamond => vec![segment(Point::new(1.0, 0.0), corner), segment(corner, Point::new(0.0, 1.0))], + CellKind::Circle | CellKind::Ellipse => { + let (a, b) = if matches!(self, CellKind::Circle) { (r, r) } else { (1.3 * r, r / 1.3) }; + // The ellipse stays inside x ≤ 1 from angle tx and inside y ≤ 1 up to angle ty. + let tx = (1.0 / a).min(1.0).acos(); + let ty = (1.0 / b).min(1.0).asin(); + if tx >= ty { + return vec![segment(Point::new(1.0, 0.0), corner), segment(corner, Point::new(0.0, 1.0))]; + } + let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); + let mut out = vec![]; + if a > 1.0 { + out.push(segment(Point::new(1.0, 0.0), at(tx))); + } + ellipse_arc(&mut out, a, b, tx, ty); + if b > 1.0 { + out.push(segment(at(ty), Point::new(0.0, 1.0))); + } + out + } + } } + + /// The size at which the dot covers the whole quadrant. + fn max_size(self) -> f64 { + match self { + CellKind::Circle => std::f64::consts::SQRT_2, + // 1 / (1.3 r)² + (1.3 / r)² = 1 at the corner. + CellKind::Ellipse => (1.0 / 1.69 + 1.69_f64).sqrt(), + CellKind::Diamond => 2.0, + } + } + + fn table(self) -> &'static OnceLock> { + match self { + CellKind::Circle => &CELL_CIRCLE, + CellKind::Ellipse => &CELL_ELLIPSE, + CellKind::Diamond => &CELL_DIAMOND, + } + } + + /// For tones `k / SIZE_STEPS`, the size of the dot whose clipped quadrant covers that tone. + fn sizes(self) -> Vec { + (0..=SIZE_STEPS) + .map(|k| { + let target = k as f64 / SIZE_STEPS as f64; + let (mut lo, mut hi) = (0.0, self.max_size()); + for _ in 0..50 { + let mid = (lo + hi) / 2.0; + if curves_area(&self.quadrant(mid)) < target { lo = mid } else { hi = mid } + } + (lo + hi) / 2.0 + }) + .collect() + } +} + +/// The `kind` dot for tone `t` (0..1) in a cell of half side `h` centered on the origin, clipped to +/// the cell ([`CellKind`]). +fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData { + let sizes = kind.table().get_or_init(|| kind.sizes()); + let x = t.clamp(0.0, 1.0) * SIZE_STEPS as f64; + let i = (x.floor() as usize).min(SIZE_STEPS - 1); + let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0)); + let r = lo + (hi - lo) * (x - i as f64); + let q1 = mapped(&kind.quadrant(r), |p| Point::new(p.x * h, p.y * h)); + PathData::from_bezpath(&four_quadrants(&q1)) +} + +/// The closed path through `q1` (from the x axis to the y axis) and its mirror images in the other +/// three quadrants, counterclockwise. +fn four_quadrants(q1: &[CubicBez]) -> BezPath { + let mut bp = BezPath::new(); + let mut add = |curves: Vec, first: bool| { + for (k, c) in curves.iter().enumerate() { + if k == 0 { + if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) } + } + bp.curve_to(c.p1, c.p2, c.p3); + } + }; + add(q1.to_vec(), true); + add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y))), false); + add(mapped(q1, |p| Point::new(-p.x, -p.y)), false); + add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y))), false); bp.close_path(); bp } @@ -709,6 +815,24 @@ mod tests { assert_eq!((DotShape::parse("Euclidean"), DotShape::parse("elliptical")), (Some(DotShape::Euclidean), Some(DotShape::Elliptical))); } + #[test] + fn round_and_diamond_dots_stay_in_their_cell_and_fill_it_at_full_tone() { + for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond] { + for t in [0.2, 0.6, 0.85, 0.97] { + // The dot never reaches into a neighbor's cell, so dots of different tones meet + // along the shared side instead of overlapping into notches. + let b = shape.path(t, 2.0).control_bounds().unwrap(); + assert!(b.x0 >= -1.0 - 1e-9 && b.x1 <= 1.0 + 1e-9 && b.y0 >= -1.0 - 1e-9 && b.y1 <= 1.0 + 1e-9, "{shape:?} at {t}: {b:?}"); + // What it covers of the cell is the tone. + let area = shape.path(t, 2.0).to_bezpath().area().abs() / 4.0; + assert!((area - t).abs() < 2e-3, "{shape:?} at {t}: {area}"); + } + // Full tone is the whole cell, its corners included. + assert!(covers(shape, 1.0, (0.49, 0.49)) && covers(shape, 1.0, (-0.49, 0.49)), "{shape:?}"); + assert!(!covers(shape, 0.9, (0.499, 0.499)), "{shape:?}"); + } + } + #[test] fn euclidean_dots_meet_corner_to_corner_at_half() { let s = DotShape::Euclidean; From a8731bf8edc0ec597c529eaa824d64528b83443e Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:31:48 +0530 Subject: [PATCH 69/72] Canvas: offer Create Outlines for text inside selected groups --- crates/engine/src/cmd/typecmd.rs | 12 ++++++++++++ crates/engine/src/lib.rs | 1 + crates/ui-egui/src/menus/context.rs | 2 +- crates/ui-egui/src/tests/contextmenu.rs | 20 ++++++++++++++++++++ docs/ui-parity.md | 2 +- 5 files changed, 35 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 1c45d37f4c..f69f878e50 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -589,6 +589,18 @@ fn overflow_note(ids: &[NodeId], left_out: &str) -> Option { } } +/// Whether Create Outlines has a text object to convert in the selected roots. +pub fn can_create_outlines(s: &Session) -> bool { + use std::ops::ControlFlow::{Break, Continue}; + + let Ok(roots) = selected_roots(s) else { return false }; + let Some(st) = s.active() else { return false }; + roots + .iter() + .filter_map(|id| st.doc.node(*id)) + .any(|node| node.try_walk(&mut |child| if matches!(child.kind, NodeKind::Text(_)) { Break(()) } else { Continue(()) }).is_break()) +} + /// Text objects among `ids` and their descendants. fn text_ids(d: &Document, ids: &[NodeId]) -> Vec { text_ids_where(d, ids, |_| true) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index fb2115190c..2607f9d254 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -39,6 +39,7 @@ pub use cmd::pathops::{HAIRLINE_SLIVER_WIDTH, HAIRLINE_SLIVER_WIDTH_RANGE, auto_ pub use cmd::rasterfx::{export_pdf, flatten_raster_effects}; pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step}; pub use cmd::textwrap::TEXT_WRAP_OFFSET_RANGE; +pub use cmd::typecmd::can_create_outlines; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; pub use cmd::{EyedropperOptions, PathfinderOptions}; pub use journal::Journal; diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index 06f1a6900b..d94e4feef4 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -118,7 +118,7 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { if any(|k| matches!(k, NodeKind::Compound { .. })) { v.push(c("Release Compound Path", "object.compoundPath.release")); } - if any(|k| matches!(k, NodeKind::Text(_))) { + if vectorcraft_engine::can_create_outlines(&app.session) { v.push(c("Create Outlines", "type.createOutlines")); } // The paragraphs of the selected type, or those the Type tool's selection touches. diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index 4ed9e3d47d..ad11b25441 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -727,6 +727,26 @@ fn create_outlines_from_the_canvas_menu_converts_selected_text_in_one_undo_step( } } +#[test] +fn create_outlines_is_offered_for_a_selected_group_with_nested_text() { + let mut app = app(); + let a = rect(&mut app, 20.0, 20.0); + let b = rect(&mut app, 150.0, 20.0); + app.run("select.set", json!({"ids": [a.0, b.0]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + let paths = app.session.active().unwrap().selection.objects[0]; + assert!(!has(&app, "Create Outlines"), "a group of paths has no text to outline"); + + let text = app.run("text.create", json!({"x": 180, "y": 175, "text": "Nested"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [paths.0, text]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + let inner = app.session.active().unwrap().selection.objects[0]; + let c = rect(&mut app, 280.0, 20.0); + app.run("select.set", json!({"ids": [inner.0, c.0]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + assert!(has(&app, "Create Outlines"), "the selected outer group contains text"); +} + /// #5267: a right-click on a stroked object offers Outline Stroke, which runs /// `object.path.outlineStroke` (the Object › Path item) and leaves filled art; an object with no /// stroke to outline has no such item. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 170549ae4c..6d273a7d65 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -530,7 +530,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Pathfinder panel › Pathfinder Options…: Precision, Remove Redundant Points, Divide and Outline Will Remove Unpainted Artwork | done | #3426; `object.pathfinder.options`, kept in the preferences; defaults (0.01 pt, both off) keep the earlier results; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html) | | Cmd/Ctrl+4 repeats the last successful Shape Mode or Pathfinder operation on the selection | done | Panel operations, direct `object.pathfinder.*` commands and `command.batch` steps (Actions playback) set history; `action.batch`, Trap, compound-shape edits and live effects do not. Repeat uses current Pathfinder Options; [key spec](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), [menu spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html) | | Pathfinder panel: compound shapes (Make, Release and Expand Compound Shape in the panel menu, Alt-click a Shape Mode, a Shape Mode for selected members, the Expand button) | partial | #4522; `object.compoundShape.make`/`setMode`/`release`/`expand`; members stay editable, the area draws, exports and saves; the button of the members' shared mode is lit, and members in different modes put a question mark on each Shape Mode button; blends, envelopes and warped objects are members as they draw; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html); missing: hit-testing by the area | -| Canvas context menu | done | Right-clicking type opens the canvas menu, with Bullets and Numbering and Spelling. The menu offers Create Outlines when at least one text object is selected, with the same shortcut and undoable command as Type › Create Outlines (#9022). The Menu key and Shift+F10 open the menu for the current selection. Right-clicking a path offers Object › Path › Simplify… and Smooth…, each opening what its menu item opens (#8344). A selection with a visible stroke to outline (a path, compound path or group holding one; not type) adds Outline Stroke (`object.path.outlineStroke`, the Object › Path item, no shortcut), after the path operations (#5267). Artboard rows, library groups and items, the rulers and floating toolbar grips have menus too. Gaps: other panels have none | +| Canvas context menu | done | Right-clicking type opens the canvas menu, with Bullets and Numbering and Spelling. The menu offers Create Outlines when the selection includes text directly or inside a selected group, with the same shortcut and undoable command as Type › Create Outlines (#9022). The Menu key and Shift+F10 open the menu for the current selection. Right-clicking a path offers Object › Path › Simplify… and Smooth…, each opening what its menu item opens (#8344). A selection with a visible stroke to outline (a path, compound path or group holding one; not type) adds Outline Stroke (`object.path.outlineStroke`, the Object › Path item, no shortcut), after the path operations (#5267). Artboard rows, library groups and items, the rulers and floating toolbar grips have menus too. Gaps: other panels have none | | Layers panel row context menu | done | Right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export; right-clicking a ruler guide row shows Hide/Show, Lock/Unlock, Release Guides, Delete and Locate Object; right-clicking a blend spine row shows Select, Blend Options…, Reverse Spine, Reverse Front to Back, Expand, Release and Locate Object (#8592). | | Swatches item context menu (G12) | done | List and thumbnail items offer Swatch Options…, Duplicate Swatch and Delete Swatch for the clicked item. Right-click selects without applying paint; reserved/missing items disable actions. All 39 Swatches tests pass, including all five views and Undo; the regression fails with the menu hooks removed. Rendered headless menus inspected. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. | | History panel row context menu (G12) | done | New Document from State, Step to This State, and Clear History; current-row stepping and empty-history clearing are disabled. Snapshot identity is checked after pending tool edits, and jumps settle typing before counting undo/redo. A state discarded while an edit settles reports that it is unavailable. Shift+F10 opens the focused row menu; Escape returns focus to the row. Switching documents dismisses the menu. Headless tests: `panels::history::tests`. | From 8a73135d7f72bfc2d07c654e7b7a691a68431579 Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:39:01 +0530 Subject: [PATCH 70/72] Preflight: add finding row context menus --- crates/ui-egui/src/panels/preflight.rs | 72 +++++++++++++----- crates/ui-egui/src/panels/preflight/tests.rs | 80 +++++++++++++++++++- docs/production-preflight.md | 9 ++- 3 files changed, 139 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/panels/preflight.rs b/crates/ui-egui/src/panels/preflight.rs index 9ee83019d9..923d07b793 100644 --- a/crates/ui-egui/src/panels/preflight.rs +++ b/crates/ui-egui/src/panels/preflight.rs @@ -13,6 +13,7 @@ use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Show as _, S use craft::ui::display::{Divider, Shade, Text}; use craft::ui::form::{Field, FieldGroup}; use craft::ui::list::{Finding, FindingsList, FindingsWords, ListRow, Severity}; +use craft::ui::menu::{Menu, MenuItem}; use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::pickers::Select; use craft::ui::runtime::frame::clock; @@ -30,6 +31,8 @@ const RECHECK: f64 = 2.0; pub(crate) struct PreflightPanel { pub(crate) options: Options, pub(crate) cache: Cache, + /// The document and finding for the open row menu. Report positions can change on recheck. + menu: Option<(u64, Value)>, } /// What the user chose to check. @@ -213,6 +216,15 @@ fn heading_row<'r>(check: &Value, pending: &'r Pending) -> ListRow<'r> { row } +fn link_action(finding: &Value) -> Option<(&str, &'static str, u64)> { + let id = finding["sourceId"].as_u64()?; + match finding["code"].as_str()? { + "missingLink" => Some((tl!("Relink…"), "ui.relinkDialog", id)), + "modifiedLink" => Some((tl!("Update Link"), "links.update", id)), + _ => None, + } +} + /// The row of one finding, with the button that repairs a link under it. fn finding_row<'r>(key: u64, finding: &Value, words: &FindingsWords, pending: &'r Pending) -> ListRow<'r> { let code = finding["code"].as_str().unwrap_or_default(); @@ -221,14 +233,9 @@ fn finding_row<'r>(key: u64, finding: &Value, words: &FindingsWords, pending: &' let values = ppi.iter().filter_map(Value::as_f64).map(|n| format!("{n:.0}")).collect::>(); detail = format!("{detail}; {}", effective_ppi_line(&values)); } - let row = Finding::new(key, Severity::Warning, finding["name"].as_str().unwrap_or_default()).detail(detail).row(words); - let action = match code { - "missingLink" => Some((tl!("Relink…"), "ui.relinkDialog")), - "modifiedLink" => Some((tl!("Update Link"), "links.update")), - _ => None, - }; - match (action, finding["sourceId"].as_u64()) { - (Some((label, command)), Some(id)) => row.below(Button::new(label.to_owned()), move |out| { + let row = Finding::new(key, Severity::Warning, finding["name"].as_str().unwrap_or_default()).detail(detail).row(words).row_menu(); + match link_action(finding) { + Some((label, command, id)) => row.below(Button::new(label.to_owned()), move |out| { if out.clicks == 1 { pending.borrow_mut().push((command, json!({ "ids": [id] }))); } @@ -280,43 +287,74 @@ fn options(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { } pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { - if app.session.active().is_none() { + let Some(document) = app.session.active().map(|st| st.uid) else { + app.ui.preflight_panel.menu = None; Notice::new(Tone::Neutral, tl!("Open a document to check it before delivery.").to_owned()) .title(tl!("Production Preflight").to_owned()) .layout(NoticeLayout::Centred) .show(ui); return; - } + }; let force = options(app, ui); Divider::horizontal().show(ui); if app.session.active().is_some_and(|st| st.interaction.is_some()) || app.session.tool_busy() { + app.ui.preflight_panel.menu = None; Notice::new(Tone::Neutral, tl!("Preflight updates when the edit finishes.").to_owned()).layout(NoticeLayout::Centred).show(ui); return; } let cache = cached(app, ui, force); if let Some(error) = cache.error { + app.ui.preflight_panel.menu = None; Notice::new(Tone::Bad, crate::i18n::msg(&error)).title(tl!("Preflight could not complete").to_owned()).layout(NoticeLayout::Centred).show(ui); return; } - results(app, ui, &cache.report); + results(app, ui, document, &cache.report); } -fn results(app: &mut VectorcraftApp, ui: &mut Ui, report: &Value) { +fn results(app: &mut VectorcraftApp, ui: &mut Ui, document: u64, report: &Value) { let rows = PreflightRows::new(report); let pending = Pending::default(); - let out = FindingsList::new(tl!("Findings")).show_items(ui, &rows, &mut |key, icx| match rows.entries.get(*key as usize) { + let list = FindingsList::new(tl!("Findings")).id(ui.scope_id().with(("preflight-findings", document))); + let out = list.show_items(ui, &rows, &mut |key, icx| match rows.entries.get(*key as usize) { Some(Entry_::Heading(c)) => heading_row(&rows.checks[*c], &pending), Some(Entry_::Finding(f)) => finding_row(*key, &rows.findings[*f], &icx.words::(), &pending), None => ListRow::new(String::new()), }); let mut located = None; + let finding_at = |key: u64| match rows.entries.get(rows.index_of(&key)?)? { + Entry_::Finding(f) => rows.findings.get(*f), + Entry_::Heading(_) => None, + }; + let menu = &mut app.ui.preflight_panel.menu; for event in out.events { - if let CollectionEvent::Activate(key) = event - && let Some(Entry_::Finding(f)) = usize::try_from(key).ok().and_then(|at| rows.entries.get(at)) - { - located = rows.findings.get(*f); + match event { + CollectionEvent::ContextMenu(request) => *menu = finding_at(request.key).map(|f| (document, f.clone())), + CollectionEvent::Activate(key) => located = finding_at(key), + _ => {} } } + // Resolve the captured finding in the current report even if another row now occupies its old slot. + let target = menu.as_ref().filter(|(uid, _)| *uid == document).and_then(|(_, saved)| rows.findings.iter().find(|f| *f == saved)); + if let Some(finding) = target { + let shown = Menu::context(tl!("Findings"), &out.response).show(ui, |ui, _| { + if MenuItem::new(tl!("Select and Zoom")).show(ui).ran { + located = Some(finding); + } + if finding["kind"] == "fonts" && MenuItem::new(tl!("Find Font…")).show(ui).ran { + pending.borrow_mut().push(("type.findFont", json!({}))); + } + if let Some((label, command, id)) = link_action(finding) + && MenuItem::new(label.to_owned()).show(ui).ran + { + pending.borrow_mut().push((command, json!({ "ids": [id] }))); + } + }); + if shown.output.closed.is_some() || located.is_some() || !pending.borrow().is_empty() { + *menu = None; + } + } else { + *menu = None; + } if let Some(finding) = located { locate(app, finding); } diff --git a/crates/ui-egui/src/panels/preflight/tests.rs b/crates/ui-egui/src/panels/preflight/tests.rs index 18f9ad57c4..0220b447c2 100644 --- a/crates/ui-egui/src/panels/preflight/tests.rs +++ b/crates/ui-egui/src/panels/preflight/tests.rs @@ -131,6 +131,77 @@ fn clicking_a_preflight_finding_selects_and_zooms_to_its_artwork() { assert!(app.view().unwrap().zoom > 1.0); } +#[test] +fn a_finding_menu_can_be_opened_dismissed_and_run_from_the_keyboard() { + use egui::{Key, Modifiers}; + + let (mut app, id) = app(); + app.run("select.set", json!({ "ids": [] })).unwrap(); + big_canvas(&mut app); + let overflow = row(&mut app, "overflow"); + let mut panel = Panel::new(app, show); + panel.focus(&overflow); + assert!(panel.focused(&overflow)); + + panel.key(Key::F10, Modifiers::SHIFT); + panel.frame(); + panel.frame(); + assert!(panel.focused("Select and Zoom")); + assert!(panel.app().session.active().unwrap().selection.objects.is_empty()); + + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + panel.frame(); + assert!(!panel.shows("Select and Zoom")); + assert!(panel.focused(&overflow)); + + panel.key(Key::F10, Modifiers::SHIFT); + panel.frame(); + panel.frame(); + panel.key(Key::Enter, Modifiers::NONE); + app_frame(&mut panel.app()); + let app = panel.app(); + assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(id.as_u64().unwrap())]); + assert!(app.view().unwrap().fitted); +} + +#[test] +fn a_finding_menu_stays_on_its_original_finding_after_recheck() { + let (mut app, first) = app(); + let second = app.run("text.create", json!({ "x": 120, "y": 10, "text": "Ab\nCd\nEf\nGh", "font": "Preflight UI Missing 917", "size": 12, "area": { "width": 100, "height": 20 } })).unwrap()["id"].clone(); + app.run("object.setProps", json!({ "ids": [second], "name": "Back page" })).unwrap(); + app.run("select.set", json!({ "ids": [] })).unwrap(); + let overflow = |name: &str| format!("{name}, {}, Warning", reason("overflow")); + let mut panel = Panel::new(app, show); + panel.secondary_click(&overflow("Back page")); + panel.frame(); + assert!(panel.shows("Select and Zoom")); + + panel.app().run("text.areaOptions", json!({ "ids": [first], "height": 150 })).unwrap(); + panel.frame(); + assert!(!panel.shows(&overflow("Delivery headline"))); + panel.click_menu_item("Select and Zoom"); + assert_eq!(panel.app().session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(second.as_u64().unwrap())]); +} + +#[test] +fn switching_documents_dismisses_the_finding_menu() { + let (mut app, _) = app(); + let font = row(&mut app, "missingFont"); + let mut panel = Panel::new(app, show); + panel.secondary_click(&font); + panel.frame(); + assert!(panel.shows_role("Find Font…", craft::ui::contract::Role::MENU_ITEM)); + + panel.app().run("file.new", json!({ "width": 500, "height": 400 })).unwrap(); + panel.frame(); + assert!(!panel.shows("Select and Zoom")); + panel.app().run("document.activate", json!({ "index": 0 })).unwrap(); + panel.frame(); + assert!(panel.shows(&font)); + assert!(!panel.shows("Select and Zoom")); +} + #[test] fn clicking_a_preflight_finding_on_a_locked_artboard_reports_the_problem() { let (mut app, id) = app(); @@ -218,8 +289,15 @@ fn preflight_panel_rechecks_missing_files_on_its_timer_and_on_request() { panel.frame(); assert!(panel.shows(&missing)); assert_eq!(rev, panel.app().session.active().unwrap().revision); + panel.secondary_click(&missing); + panel.frame(); + assert!(panel.shows_role("Relink…", craft::ui::contract::Role::MENU_ITEM)); std::fs::write(&path, &bytes).unwrap(); - panel.click("Recheck"); + panel.advance(2.0); + panel.frame(); + assert!(!panel.shows("Select and Zoom"), "the timer dismissed the menu for a resolved finding"); assert!(!panel.shows(&missing)); std::fs::remove_file(&path).unwrap(); + panel.click("Recheck"); + assert!(panel.shows(&missing), "Recheck notices a newly missing file before the timer"); } diff --git a/docs/production-preflight.md b/docs/production-preflight.md index ecc551f0c9..261c51fca6 100644 --- a/docs/production-preflight.md +++ b/docs/production-preflight.md @@ -13,10 +13,11 @@ The panel checks: - **Image Resolution:** effective resolution along both pixel axes at the image's placed size. Print includes the job's page transform, so enlarging the print can lower effective resolution. -Click a finding to select and zoom to the affected artwork. A font finding can select several -objects. A finding inside a symbol, pattern, brush or opacity mask locates its first visible -canvas owner. If some artwork cannot be selected, the status bar reports it; any selectable -objects are still located without unlocking artwork or artboards. **Find Font…**, **Relink…** and +Click a finding to select and zoom to the affected artwork. Right-click a finding or press +Shift+F10 on its focused row for **Select and Zoom** and any available repair action. +A font finding can select several objects. A finding inside a symbol, pattern, brush or opacity +mask locates its first visible canvas owner. If some artwork cannot be selected, the status bar +reports it and the panel still locates any selectable objects. **Find Font…**, **Relink…** and **Update Link** open the existing repair workflows; they do not apply an automatic font substitution or change artwork just by checking it. From 6f4fd3e187a161075e61d14e01f659eb0b65985a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 06:59:58 -0800 Subject: [PATCH 71/72] Tests: ACL replacement tests run without the acl tools a_replaced_sidecar_takes_no_inherited_acl and a_replacement_takes_no_inherited_acl_the_old_file_lacked set the folder's default ACL with setfacl and returned early when it was missing, so on a Linux host without the acl package they passed without checking anything. They now write the default ACL as the system.posix_acl_default extended attribute through rustix, check that a new file takes it, and read the replacement's access ACL with getxattr. They skip only when the file system keeps no ACLs (EOPNOTSUPP); any other setup error fails the test. --- crates/engine/src/tests/script_xmp.rs | 37 +++++++++++++++++++++------ crates/format/src/atomic.rs | 33 +++++++++++++++++++++--- 2 files changed, 59 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs index 3a4f8952f4..4fbbc1741d 100644 --- a/crates/engine/src/tests/script_xmp.rs +++ b/crates/engine/src/tests/script_xmp.rs @@ -729,7 +729,9 @@ fn a_temporary_file_starts_private() { } /// A replaced sidecar that had no access ACL takes none from its folder's default ACL, whose named -/// users the sidecar's group bits would let in. (Skipped where `setfacl` or ACLs are missing.) +/// users the sidecar's group bits would let in. The default ACL is set through its extended +/// attribute, so the test runs where the `acl` tools are not installed. (Skipped on a file system +/// without ACLs.) #[cfg(target_os = "linux")] #[test] fn a_replaced_sidecar_takes_no_inherited_acl() { @@ -741,11 +743,28 @@ fn a_replaced_sidecar_takes_no_inherited_acl() { &format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"), ); let path = PathBuf::from(log[0].as_str().unwrap()); - let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(path.parent().unwrap()).status(); - if !set.is_ok_and(|s| s.success()) { - let _ = std::fs::remove_dir_all(base); - return; + let parent = path.parent().unwrap(); + // `u::rw-,u:nobody:rw-,g::r--,m::rw-,o::r--` as the kernel's attribute: version 2, then tag, + // permissions and id per entry. + let mut acl = 2u32.to_le_bytes().to_vec(); + for (tag, perm, id) in [(0x01u16, 6u16, u32::MAX), (0x02, 6, 65534), (0x04, 4, u32::MAX), (0x10, 6, u32::MAX), (0x20, 4, u32::MAX)] { + acl.extend(tag.to_le_bytes()); + acl.extend(perm.to_le_bytes()); + acl.extend(id.to_le_bytes()); } + match rustix::fs::setxattr(parent, "system.posix_acl_default", &acl, rustix::fs::XattrFlags::empty()) { + Ok(()) => {} + Err(e) if e == rustix::io::Errno::NOTSUP => { + let _ = std::fs::remove_dir_all(base); + return; + } + Err(e) => panic!("setting the default ACL: {e}"), + } + let mut buf = vec![0u8; 4096]; + let probe = parent.join("probe"); + std::fs::write(&probe, b"").unwrap(); + assert!(rustix::fs::getxattr(&probe, "system.posix_acl_access", &mut buf[..]).is_ok(), "a new file takes the default ACL"); + std::fs::remove_file(&probe).unwrap(); logged( &mut s, &base, @@ -753,9 +772,11 @@ fn a_replaced_sidecar_takes_no_inherited_acl() { var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();", ); assert!(std::fs::read_to_string(&path).unwrap().contains("changed")); - let acl = std::process::Command::new("getfacl").args(["--omit-header", "--absolute-names"]).arg(&path).output().unwrap(); - let acl = String::from_utf8_lossy(&acl.stdout); - assert!(!acl.contains("nobody"), "the replacement takes no ACL entry the sidecar lacked: {acl}"); + assert_eq!( + rustix::fs::getxattr(&path, "system.posix_acl_access", &mut buf[..]), + Err(rustix::io::Errno::NODATA), + "the replacement takes no ACL entry the sidecar lacked" + ); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index c9e219cabf..f314fcdd15 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -422,15 +422,17 @@ mod tests { } /// A replaced file that had no access ACL gets none from the folder's default ACL, whose named - /// users the old file's group bits would let in. (Skipped where `setfacl` or ACLs are missing.) + /// users the old file's group bits would let in. The default ACL is set through its extended + /// attribute, so the test runs where the `acl` tools are not installed. (Skipped on a file system + /// without ACLs.) #[cfg(target_os = "linux")] #[test] fn a_replacement_takes_no_inherited_acl_the_old_file_lacked() { let d = dir("acl"); let f = d.join("doc.vectorcraft"); std::fs::write(&f, b"old").unwrap(); - let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(&d).status(); - if !set.is_ok_and(|s| s.success()) { + if !set_default_acl_for_nobody(&d) { + let _ = std::fs::remove_dir_all(&d); return; } write_atomic(&f, b"new").unwrap(); @@ -439,6 +441,31 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// Give folder `d` the default ACL `u::rw-,u:nobody:rw-,g::r--,m::rw-,o::r--`, written as the + /// kernel's `system.posix_acl_default` attribute (version 2, then tag, permissions and id per entry). + #[cfg(target_os = "linux")] + /// `false` when the folder's file system keeps no ACLs. + fn set_default_acl_for_nobody(d: &Path) -> bool { + const NO_ID: u32 = u32::MAX; + let mut acl = 2u32.to_le_bytes().to_vec(); + for (tag, perm, id) in [(0x01u16, 6u16, NO_ID), (0x02, 6, 65534), (0x04, 4, NO_ID), (0x10, 6, NO_ID), (0x20, 4, NO_ID)] { + acl.extend(tag.to_le_bytes()); + acl.extend(perm.to_le_bytes()); + acl.extend(id.to_le_bytes()); + } + match rustix::fs::setxattr(d, "system.posix_acl_default", &acl, rustix::fs::XattrFlags::empty()) { + Ok(()) => {} + Err(e) if e == rustix::io::Errno::NOTSUP => return false, + Err(e) => panic!("setting the default ACL: {e}"), + } + let mut buf = vec![0u8; 4096]; + let probe = d.join("probe"); + std::fs::write(&probe, b"").unwrap(); + assert!(rustix::fs::getxattr(&probe, "system.posix_acl_access", &mut buf[..]).is_ok(), "a new file takes the default ACL"); + std::fs::remove_file(&probe).unwrap(); + true + } + /// The other files in `d` besides `keep`. fn leftovers(d: &Path, keep: &str) -> Vec { std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect() From 2604dab38a69fe1a6bb4e8b749cdf70ba57e80a1 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Tue, 1 Dec 2026 22:01:26 +0530 Subject: [PATCH 72/72] Copy a fallback layer lock only between layers that share a name (#9176) A PDF part without layers comes in on one layer named for its page. When the editing data is set aside (a stale copy of another page size, say), pairing that layer with the editing data's one layer locked art nothing ties to it. Layers now take locks only by a name unique on both sides. --- crates/eps/src/import/native/layers.rs | 14 +++-------- crates/eps/src/import/tests_native.rs | 35 +++++++++++++++++++++++--- 2 files changed, 34 insertions(+), 15 deletions(-) diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index e62af0e938..dcaa95a141 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -303,17 +303,9 @@ fn unique_name_pairs>(vis_nodes: &[T], priv_no /// Apply lock states from private data layers to visible PDF layers. pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc], private_layers: &[LockTree]) { - if private_layers.is_empty() || visible_layers.is_empty() { - return; - } - - // A document with a single visible layer and a single private layer pairs them directly. - if visible_layers.len() == 1 && private_layers.len() == 1 { - apply_node_locks(Arc::make_mut(&mut visible_layers[0]), &private_layers[0]); - return; - } - - // Otherwise, match only layers with identifiable correspondence (matching unique names). + // Only layers that are evidently the same one (a name unique on both sides) take its locks: one + // layer each is no evidence, since a PDF part without layers comes in on a layer named for its + // page, and the editing data it was set aside for may not be the art on it. for (v_idx, p_idx) in unique_name_pairs(visible_layers, private_layers) { apply_node_locks(Arc::make_mut(&mut visible_layers[v_idx]), &private_layers[p_idx]); } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index a3041244f3..c5b6b61d58 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8841,21 +8841,48 @@ fn ai_reordered_three_children_roads_triangle_circle_preserve_locks() { assert!(!vis_rd.locked, "Roads matched to unlocked private Roads by unique name"); } +/// The PDF part's one layer, named for its page because the PDF part has no layers, isn't the +/// editing data's one layer: nothing says the art on it is that layer's, so the layer's lock and +/// those of what it holds stay out of it. #[test] -fn ai_fallback_with_generated_page_name_preserves_private_layer_lock() { +fn ai_fallback_with_generated_page_name_does_not_take_private_layer_lock() { use std::sync::Arc; let mut doc = Document::new(100.0, 100.0); let mut priv_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0)); priv_layer.locked = true; + let mut priv_roads = Node::group(doc.alloc_id(), vec![]); + priv_roads.name = Some("Roads".to_string()); + priv_roads.locked = true; + if let NodeKind::Layer { children, .. } = &mut priv_layer.kind { + children.push(Arc::new(priv_roads)); + } let mut vis_layer = Node::layer(doc.alloc_id(), "Page 1", LayerColor::Preset(0)); - vis_layer.locked = false; + let mut vis_roads = Node::group(doc.alloc_id(), vec![]); + vis_roads.name = Some("Roads".to_string()); + if let NodeKind::Layer { children, .. } = &mut vis_layer.kind { + children.push(Arc::new(vis_roads)); + } let mut visible_layers = vec![Arc::new(vis_layer)]; let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)]; super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers); - assert_eq!(visible_layers[0].name.as_deref(), Some("Page 1")); - assert!(visible_layers[0].locked, "single-layer document pairs visible and private layers"); + assert!(!visible_layers[0].locked, "the page's layer doesn't take the editing data's layer lock"); + assert!(!visible_layers[0].children().unwrap()[0].locked, "nor does what it holds"); +} + +/// An editing copy that doesn't fit the PDF part (a stale copy of another page size) is set aside, +/// and the PDF part without layers comes in on one layer named for its page: the editing copy's +/// locked layer doesn't lock that art, which nothing ties to it. +#[test] +fn a_stale_editing_copy_does_not_lock_the_pdf_parts_page_layer() { + let art = native(&locked_layer("Map", &square(10, 10))); + let mut page = Document::new(300.0, 300.0); + std::sync::Arc::make_mut(&mut page.layers[0]).name = Some("Page 1".into()); + let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(!read, "the editing copy of another page size is set aside: {w:?}"); + assert_eq!(names(&d), ["Page 1"], "{w:?}"); + assert!(!d.layers[0].locked, "the page's layer isn't locked: {w:?}"); } #[test]