From 1b429b586e35da80f83c6e861b800de25a245921 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:31:30 -0800 Subject: [PATCH 01/32] 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/32] 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/32] 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/32] 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/32] 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/32] 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/32] 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/32] 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/32] 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/32] 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/32] 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 0359cc0b93b3e11ab08e583f7b238786e6eacbfa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:21:27 -0800 Subject: [PATCH 12/32] 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 a0455ff1176e0729119d9400601ed5bb65c271b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 22:40:41 -0800 Subject: [PATCH 13/32] 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 14/32] 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 0c13a1edb2705176fb3e134d420989b20752c3e8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 14:54:47 -0800 Subject: [PATCH 15/32] 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 d7686cd9f40b8ba8b4a9a36f56e5c592b86e230f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 20:15:53 -0800 Subject: [PATCH 16/32] Fix #10262: Document Info scrolls in a short dock group Document Info was left out of the panel forms that scroll inside their dock group, so in a short group its lower rows could not be reached. It now scrolls like the other forms. A test draws every panel in 120 pt and 60 pt groups and scrolls each one until its lowest control is in view. --- crates/ui-egui/src/dock.rs | 1 + crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/panel_harness.rs | 14 ++++++ crates/ui-egui/src/tests/panel_scroll.rs | 61 +++++++++++++++++++++++ 4 files changed, 77 insertions(+) create mode 100644 crates/ui-egui/src/tests/panel_scroll.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index dcff2191a4..d5f31df6c3 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -22,6 +22,7 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { | "blend" | "character" | "color" + | "docInfo" | "magicWand" | "openType" | "paragraph" diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 70eba60a17..953946dc7f 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -23,6 +23,7 @@ mod numfields; mod overprint; mod paintchips; pub(crate) mod panel_harness; +mod panel_scroll; mod pastechords; mod pathtype; mod pdfoutput; diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 60e6bd2182..0b9fa40f9f 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -383,6 +383,20 @@ impl Panel { seen.is_some_and(|r| r.width() >= 0.0 && r.height() >= 0.0) } + /// The named control the latest frame lays out lowest, where its name finds that control: the control a reader + /// reaches last. + pub(crate) fn lowest(&self) -> Option { + let mut names = self.names(); + names.sort(); + names.dedup(); + names + .into_iter() + .filter_map(|name| self.fixture.by_label(&name).map(|t| (name, t.rect.bottom()))) + .filter(|(_, bottom)| bottom.is_finite()) + .max_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(name, _)| name) + } + /// Whether the control named `name` takes input. pub(crate) fn enabled(&self, name: &str) -> bool { !self.fixture.tree().is_disabled_key(self.look(name).node) diff --git a/crates/ui-egui/src/tests/panel_scroll.rs b/crates/ui-egui/src/tests/panel_scroll.rs new file mode 100644 index 0000000000..0fbc73e271 --- /dev/null +++ b/crates/ui-egui/src/tests/panel_scroll.rs @@ -0,0 +1,61 @@ +//! Every panel in a dock group shorter than its contents scrolls to its last control (#10262). + +use std::cell::RefCell; + +use egui::{Ui, pos2, vec2}; +use serde_json::json; +use vectorcraft_engine::Session; + +use crate::VectorcraftApp; +use crate::tests::panel_harness::Panel; + +thread_local! { + /// The panel the harness draws. + static SHOWN: RefCell = const { RefCell::new(String::new()) }; +} + +fn draw(app: &mut VectorcraftApp, ui: &mut Ui) { + let id = SHOWN.with(|s| s.borrow().clone()); + crate::dock::panel_body(app, ui, &id); +} + +/// The panels whose last control a short dock group hides and the wheel does not bring into view. +fn unreachable_panels(room_height: f32) -> Vec { + let mut stuck = Vec::new(); + for (id, _) in crate::state::all_panels() { + SHOWN.with(|s| *s.borrow_mut() = id.to_owned()); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + if let Err(e) = app.run("file.new", json!({"width": 200, "height": 200})) { + panic!("file.new: {e}"); + } + // A selected path, so the panels that edit a selection show their controls. + if let Err(e) = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})) { + panic!("shape.rectangle: {e}"); + } + let mut panel = Panel::new(app, draw); + let Some(last) = panel.lowest() else { continue }; + panel.room(vec2(300.0, room_height)); + panel.frame(); + panel.frame(); + if !panel.shows(&last) || panel.in_view(&last) { + continue; + } + for _ in 0..60 { + panel.scroll_at(pos2(150.0, room_height / 2.0), -120.0); + if panel.in_view(&last) { + break; + } + } + if !panel.in_view(&last) { + stuck.push(format!("{id}: {last:?}")); + } + } + stuck +} + +#[test] +fn every_panel_in_a_short_dock_group_scrolls_to_its_last_control() { + let mut stuck = unreachable_panels(120.0); + stuck.extend(unreachable_panels(60.0)); + assert!(stuck.is_empty(), "panels whose last control the wheel cannot reach: {stuck:?}"); +} From 947b74c9e9b62510a722eafa963e8d0e31a24323 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 20:30:09 -0800 Subject: [PATCH 17/32] 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 1dbbf874361974c88fe2770d2c1303b37a104e28 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 21:56:24 -0800 Subject: [PATCH 18/32] Tests: guards check the environment, not the output under test Several tests returned early when the code under test gave back nothing, so the regression they guard against passed. Each of those guards now checks only what the host provides (an installed face, the bundled fonts), and the output itself is asserted: - PDF live text: the lam-alef face is no longer picked by whether its type imports (#6072); Insert Kashidas asserts the kashida and the imported type. - Effects and Expand Appearance on type assert the outlines and the drawn type when the default face is installed. - The OpenType panel's Stylistic Sets test asserts sets with the bundled fonts. - Thumbnail worker tests assert that the worker starts; the memory peak test asserts a reading. - The json2 test checks the interpreter's Date, replace and RegExp on every run, before looking for json2.js. - Devanagari arrow keys and the Arabic narrow-area wrap assert the layout they set up. --- apps/vectorcraft-cli/src/perf.rs | 3 +-- crates/effects/src/tests/rasterfollow.rs | 20 ++++++++++++++++---- crates/engine/src/tests/objexpand.rs | 6 ++++-- crates/js/tests/json2.rs | 14 +++++--------- crates/pdf/src/tests/live_text.rs | 6 +++--- crates/pdf/src/tests/realtext.rs | 18 +++++++----------- crates/text/src/layout/wrapping_tests.rs | 8 ++++---- crates/tools/src/text/tests.rs | 13 +------------ crates/ui-egui/src/panels/opentype.rs | 3 ++- crates/ui-egui/src/thumb_worker.rs | 4 ++-- 10 files changed, 45 insertions(+), 50 deletions(-) diff --git a/apps/vectorcraft-cli/src/perf.rs b/apps/vectorcraft-cli/src/perf.rs index e533d00b73..ca0108f955 100644 --- a/apps/vectorcraft-cli/src/perf.rs +++ b/apps/vectorcraft-cli/src/perf.rs @@ -654,8 +654,7 @@ mod tests { let held = rss_mb(); drop(buffer); let (Some((held, _)), Some((now, peak))) = (held, rss_mb()) else { - eprintln!("no memory reading (Linux without `ps`): nothing to check"); - return; + panic!("rss_mb gave no memory reading"); }; assert!(peak.is_some_and(|peak| peak > held - 16.0), "holding 64 MB: {held:.1} MB, after freeing it: {now:.1} MB, peak {peak:?}"); } diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index db34010c22..d0e4939e8e 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -1035,10 +1035,11 @@ fn a_baked_group_with_type_keeps_a_shadow_on_each_copy() { use vectorcraft_doc::text::{CharStyle, TextObject}; let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; let words = Node::new(NodeId(161), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); - if !crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0) { + if !fonts() { eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); return; } + assert!(crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0), "the type outlines to paths"); let g = group(160, vec![words, square(162, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]); let b = baked(g); assert!(near(&shadows_in(&b), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&b)); @@ -1640,6 +1641,17 @@ fn type_node(id: u64, effects: Vec) -> Node { n } +/// Whether the face of the default character style is installed, so that type lays out glyphs. +/// When it is, `type_node`'s type must outline to paths. +fn fonts() -> bool { + let style = vectorcraft_doc::text::CharStyle::default(); + if vectorcraft_text::FontDb::global().face(&style.font_family, &style.font_style).is_none() { + return false; + } + assert!(crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0), "{}: the type outlines to paths", style.font_family); + true +} + /// An instance at (50, 50) with `effects` of a symbol, and the symbol's art: a black 20 pt square /// centered on its origin. fn instance(id: u64, effects: Vec) -> (Node, Node) { @@ -1660,7 +1672,7 @@ fn instance(id: u64, effects: Vec) -> (Node, Node) { /// image and the instance are checked. #[test] fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_before_it() { - let fonts = crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0); + let fonts = fonts(); if !fonts { eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); } @@ -1702,7 +1714,7 @@ fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_bef /// listed before that effect, as the canvas draws it, rather than staying type under one shadow. #[test] fn baked_type_whose_transform_moves_its_copies_keeps_a_shadow_on_each() { - if !crate::outline_text(&type_node(99, vec![])).is_some_and(|o| paths_in(&o) > 0) { + if !fonts() { eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); return; } @@ -1738,7 +1750,7 @@ fn type_carries_its_fills_shadow_on_each_copy() { n }; let copying = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))]; - if !crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0) { + if !fonts() { eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); return; } diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index ffa8e83f40..7ae627e546 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -445,11 +445,13 @@ fn each_copys_shadow_on_type_expands_as_the_canvas_draws_it() { let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow})); run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}})); - let before = render(&s); - if !(0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])) { + let style = vectorcraft_doc::text::CharStyle::default(); + if vectorcraft_text::FontDb::global().face(&style.font_family, &style.font_style).is_none() { eprintln!("skipped: built without a font that draws the type"); return; } + let before = render(&s); + assert!((0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])), "the type draws in red"); // The rightmost red pixel of the copy, below the type, and 38 pt right of it the copy's shadow. let red = (100..200u32).flat_map(|y| (0..200u32).map(move |x| (x, y))).filter(|&(x, y)| before.pixel(x, y) == [255, 0, 0, 255]).max_by_key(|p| p.0); diff --git a/crates/js/tests/json2.rs b/crates/js/tests/json2.rs index af408a4fef..521040373e 100644 --- a/crates/js/tests/json2.rs +++ b/crates/js/tests/json2.rs @@ -68,20 +68,16 @@ problem; #[test] fn json2_polyfill_round_trips_with_the_built_in_json() { + let mut realm = Realm::new(); + match realm.run(NEEDS) { + Ok(JsValue::Bool(true)) => {} + other => panic!("json2: the interpreter lacks Date, String.prototype.replace or RegExp, which json2.js uses: {other:?}"), + } let Some(path) = json2_file() else { println!("json2: SKIPPED (no json2.js; run cargo xtask test262)"); return; }; let source = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); - let mut realm = Realm::new(); - match realm.run(NEEDS) { - Ok(JsValue::Bool(true)) => {} - Ok(JsValue::Bool(false)) => { - println!("json2: SKIPPED (the interpreter lacks Date, String.prototype.replace or RegExp, which json2.js uses)"); - return; - } - other => panic!("json2: the built-in check failed: {other:?}"), - } match realm.run(&format!("{BEFORE}\n{source}\n{ROUND_TRIP}")) { Ok(JsValue::String(s)) if s == "ok" => println!("json2: the polyfill and the built-in JSON agree on every sample"), other => panic!("json2: {other:?}"), diff --git a/crates/pdf/src/tests/live_text.rs b/crates/pdf/src/tests/live_text.rs index 90341ca28b..60a20079d6 100644 --- a/crates/pdf/src/tests/live_text.rs +++ b/crates/pdf/src/tests/live_text.rs @@ -503,13 +503,13 @@ fn arabic_ligatures_keep_their_letters_in_order() { let t = TextObject::point(kurbo::Point::ORIGIN, "لا", style); vectorcraft_text::layout(db, &t).glyphs.len() == 1 }; - // An installed Arabic font with a lam-alef ligature whose glyphs come back as live type. + // An installed Arabic font with a lam-alef ligature. The test checks that its type comes + // back, so the choice of font does not depend on the import. let Some(face) = preferred .iter() .chain(&db.families()) .filter_map(|f| db.face(f, "Regular")) - .filter(|f| f.covers('\u{0644}') && f.covers('\u{0627}') && ligates(f)) - .find(|f| !imported_texts(f, "بب").is_empty()) + .find(|f| f.covers('\u{0644}') && f.covers('\u{0627}') && ligates(f)) else { return; // No such font on this host. }; diff --git a/crates/pdf/src/tests/realtext.rs b/crates/pdf/src/tests/realtext.rs index 7fcd06dd56..5f4ef0205f 100644 --- a/crates/pdf/src/tests/realtext.rs +++ b/crates/pdf/src/tests/realtext.rs @@ -202,8 +202,7 @@ fn line_break_hyphens_of_right_to_left_lines_are_written_as_text_where_the_canva /// The kashidas of justified Arabic type (Insert Kashidas), which stand for no character either, /// are drawn as paths: reopened, the type holds its letters and no hyphen or tatweel. Skipped -/// without an OpenType font that covers Arabic and the tatweel, when the layout adds no kashida, -/// or when PDF text import returns no strings on this platform. +/// without an OpenType font that covers Arabic and the tatweel. #[test] fn kashidas_are_not_written_as_hyphens() { let db = FontDb::global(); @@ -221,20 +220,17 @@ fn kashidas_are_not_written_as_hyphens() { t.para.justify = vectorcraft_doc::Justify::JustifyAll; t.para.kashida = vectorcraft_doc::text::Kashida::Medium; let tatweel = face.glyph_for('\u{0640}'); - if !vectorcraft_text::layout(db, &t).glyphs.iter().any(|g| g.len == 0 && g.gid == tatweel) { - return; - } + assert!( + vectorcraft_text::layout(db, &t).glyphs.iter().any(|g| g.len == 0 && g.gid == tatweel), + "{}: justified layout inserts a kashida", + face.family + ); let back = texts(&import_as(&pdf(&doc(vec![t]), false).bytes, TextAs::Text)); - if back.is_empty() { - return; - } + assert!(!back.is_empty(), "{}: the PDF's type comes back", face.family); assert!(!back.concat().contains(['-', '\u{2010}', '\u{0640}']), "{back:?}"); // Every letter comes back, at least as often as the text holds it (the justified words may // come back as type objects of their own). let all = back.concat(); - if all.is_empty() { - return; - } let count = |s: &str, c: char| s.chars().filter(|&x| x == c).count(); for c in text.chars().filter(|c| c.is_alphabetic()) { assert!(count(&all, c) >= count(text, c), "{c}: {back:?}"); diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index 225e58a053..5164dd1998 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -228,11 +228,10 @@ fn narrow_arabic_area_wrap_keeps_base_and_mark_together_when_supported() { let levels = bidi.as_ref().map_or(&[][..], |info| &info.levels); let mut shaped = Vec::new(); shape_range(db, text, 0..text.len(), &[(0..text.len(), &style)], &[], &OtFeatures::default(), levels, &mut shaped); - let Some(first) = shaped.first() else { return }; + let first = shaped.first().expect("the text shapes to glyphs"); let first_end = shaped.iter().take_while(|g| g.byte == first.byte).count(); - if first.byte != 0 || first_end < 2 || first_end >= shaped.len() { - return; - } + assert_eq!(first.byte, 0, "{}: the first cluster starts the text: {shaped:?}", face.family); + assert!(first_end >= 2 && first_end < shaped.len(), "{}: the base and its mark are one cluster of two glyphs: {shaped:?}", face.family); // Pick a narrow width that fits glyphs before one positive-advance glyph but not that next // glyph. This ensures the old per-glyph loop would have returned inside the first cluster. let mut prefix = shaped.first().map_or(0.0, |g| g.adv); @@ -245,6 +244,7 @@ fn narrow_arabic_area_wrap_keeps_base_and_mark_together_when_supported() { None } }); + // A face whose mark has no advance gives no width that splits the cluster. let Some(width) = width else { return }; let mut object = TextObject::point(Point::ZERO, text, style); diff --git a/crates/tools/src/text/tests.rs b/crates/tools/src/text/tests.rs index c6211550b3..ac4355e3a2 100644 --- a/crates/tools/src/text/tests.rs +++ b/crates/tools/src/text/tests.rs @@ -183,12 +183,7 @@ fn type_arrows_keep_devanagari_clusters_across_wrapped_lines() { let split_width: f64 = hindi_glyphs.iter().filter(|g| g.byte == split).map(|g| g.advance).sum(); assert!(prefix_width.is_finite() && prefix_width > 0.0, "setup: prefix has positive finite advance"); assert!(split_width.is_finite(), "setup: the internal raw-group advance is finite"); - if split_width <= 0.0 { - eprintln!( - "SKIPPED: type_arrows_keep_devanagari_clusters_across_wrapped_lines; layout capability: the selected face has no positive-advance raw group at internal byte {split}" - ); - return; - } + assert!(split_width > 0.0, "setup: {} lays out a positive-advance raw group at internal byte {split}", face.family); let width = prefix_width + split_width * 0.5; assert!(width.is_finite() && width > prefix_width && width < prefix_width + split_width, "setup: one measured width separates the raw groups"); @@ -205,12 +200,6 @@ fn type_arrows_keep_devanagari_clusters_across_wrapped_lines() { assert_eq!(edit::prev_cluster(text, hindi.len()), second, "setup: logical cluster start is 6"); assert_eq!(edit::prev_cluster(text, split), second, "setup: raw line endpoint 12 is inside the grapheme"); assert_eq!(edit::next_cluster(text, split), hindi.len(), "setup: raw line endpoint 12 is not its end"); - if lay.lines.len() < 2 || (lay.lines[0].start, lay.lines[0].end, lay.lines[1].start) != (0, split, split) { - eprintln!( - "SKIPPED: type_arrows_keep_devanagari_clusters_across_wrapped_lines; layout capability: the measured frame does not expose adjacent wrapped endpoints at internal byte {split}" - ); - return; - } assert!(lay.lines.len() >= 2, "setup: actual wrapping occurred"); assert_eq!( (lay.lines[0].start, lay.lines[0].end, lay.lines[1].start), diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 8715d02401..b2c8f2cbe2 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -855,7 +855,8 @@ mod tests { let mut app = selected_text(); let Some((st, _)) = text_style(&app) else { panic!("no text style") }; let sets = set_entries(&app, &st); - // Builds without the bundled fonts have no face that offers sets. + // With the bundled fonts, the text's face offers sets. Without them, an installed face may. + assert!(!cfg!(feature = "bundled-fonts") || !sets.is_empty(), "the bundled face of the text offers stylistic sets"); let Some((first, flag, _)) = sets.first() else { return }; let (label, tag) = (set_label(first), flag.tag().unwrap()); set(&mut app, OtFeatures { small_caps: true, ..Default::default() }); diff --git a/crates/ui-egui/src/thumb_worker.rs b/crates/ui-egui/src/thumb_worker.rs index e9898a078f..5e7c48758c 100644 --- a/crates/ui-egui/src/thumb_worker.rs +++ b/crates/ui-egui/src/thumb_worker.rs @@ -214,7 +214,7 @@ mod tests { #[test] fn jobs_come_back_newest_last_per_slot() { - let Some(w) = ThumbWorker::::start(&crate::testing::ui_context(), "test") else { return }; + let w = ThumbWorker::::start(&crate::testing::ui_context(), "test").expect("the worker thread starts"); let job = |n: u32| -> JobFn { Box::new(move |_| Some(Rendered { width: n, height: 1, pixels: vec![0; 4] })) }; for k in 1..=3 { assert!(w.submit(0, k, job(k))); @@ -238,7 +238,7 @@ mod tests { #[test] fn discarded_jobs_do_not_run_and_the_running_one_finishes() { - let Some(w) = ThumbWorker::::start(&crate::testing::ui_context(), "test") else { return }; + let w = ThumbWorker::::start(&crate::testing::ui_context(), "test").expect("the worker thread starts"); let job = |n: u32| -> JobFn { Box::new(move |_| Some(Rendered { width: n, height: 1, pixels: vec![0; 4] })) }; // A job that holds the thread until it is let go, so the others queue behind it. let (started, running) = channel::<()>(); From 573246a5b2069dbaa4fd356fbda210dfbf9333b8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 01:01:57 -0800 Subject: [PATCH 19/32] xtask: test-lint adds mirror, constant-echo, fixture-only, never-run and exact-pixel rules --- xtask/src/main.rs | 5 +- xtask/src/test_lint.rs | 672 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 652 insertions(+), 25 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 1c9af7db00..9ad742749e 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -35,8 +35,9 @@ commands: cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails) test-lint [--base ] [--all] weak tests in the lines changed since the base: fail on self-compares, reasonless - #[ignore] and sleeps; list only is_ok/is_some checks, unguarded .all(), no assertion, - early returns, unset env gates... (xtask/src/test_lint.rs); --all lists every hit + #[ignore], sleeps, reads of Rust source and tests no CI target runs; list only + is_ok/is_some checks, unguarded .all(), no assertion, early returns, unset env + gates, constant echoes, exact pixels... (xtask/src/test_lint.rs); --all lists every hit by crate and never fails i18n-report list the strings each language's catalog lacks, shown in English (fails only on a broken scan; ci runs it too) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 2a839af6be..10eaf15294 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -37,14 +37,27 @@ //! string literals, `echo` or `printf` output that is not written to `$GITHUB_ENV`, and variable //! reads do not; //! * `sleep`: `thread::sleep` in test code, or a bare `sleep(…)` in a file that imports it; -//! * `reads-source`: test code that reads Rust source (`include_str!` of a `.rs` file, or a walk -//! that keeps files ending in `.rs`), outside the source audits in [`SOURCE_AUDITS`]; +//! * `reads-source`: test code that reads Rust source (`include_str!` of a `.rs` file, +//! `read_to_string` of a path with a `.rs` literal, or a walk 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. +//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table; +//! * `mirror`: `assert_eq!(f(a), f(b) …)`, where the expected side derives its value from a +//! second call of the same function (same path) with arithmetic, so a fault in `f` moves both +//! sides; builders and conversions (`new`, `from`, `to_string` …) are left out; +//! * `constant-echo`: every assertion of the test compares only constants, literals and enum +//! variants; +//! * `fixture-only`: every assertion reads only constants, literals and immutable locals of the +//! test bound (in scope) to such values, so nothing the code under test returned is checked; +//! * `never-run`: a test that the `cfg` attributes on it, on the items around it or on the `mod` +//! declarations above its file leave out of every target CI runs tests on (Linux and FreeBSD on +//! x86_64, and Windows for the app and the UI crate's print tests); +//! * `exact-pixel`: in a file that uses egui, an assertion that a screen rect (an identifier `rect`, +//! `rect_…` or `…_rect`, whole or through a corner, edge or size) equals numbers written out. //! //! 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, …))]`, @@ -58,8 +71,9 @@ //! rules about a whole test it can be on any line from the line above the test attribute to the //! `fn` line. An allow without a reason exempts nothing. //! -//! `cargo xtask test-lint` fails on hits of `self-compare`, `ignore-without-reason` and `sleep` in -//! the lines and tests changed since a base, and lists the other rules' hits there without failing. The base is `--base ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's +//! `cargo xtask test-lint` fails on hits of `self-compare`, `ignore-without-reason`, `sleep`, +//! `reads-source` and `never-run` in the lines and tests changed since a base, and lists the other +//! rules' hits there without failing. The base is `--base ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's //! merge commit is checked out, and a shallow checkout fetches that parent); elsewhere the merge //! base of `HEAD` and `upstream/main` or `origin/main`. Uncommitted and untracked files count as //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the @@ -127,10 +141,15 @@ pub enum Rule { Sleep, ReadsSource, Census, + Mirror, + ConstantEcho, + FixtureOnly, + NeverRun, + ExactPixel, } impl Rule { - pub const ALL: [Rule; 11] = [ + pub const ALL: [Rule; 16] = [ Rule::AllUnguarded, Rule::OnlyWeak, Rule::SelfCompare, @@ -142,6 +161,11 @@ impl Rule { Rule::Sleep, Rule::ReadsSource, Rule::Census, + Rule::Mirror, + Rule::ConstantEcho, + Rule::FixtureOnly, + Rule::NeverRun, + Rule::ExactPixel, ]; pub fn id(self) -> &'static str { @@ -157,6 +181,11 @@ impl Rule { Rule::Sleep => "sleep", Rule::ReadsSource => "reads-source", Rule::Census => "census", + Rule::Mirror => "mirror", + Rule::ConstantEcho => "constant-echo", + Rule::FixtureOnly => "fixture-only", + Rule::NeverRun => "never-run", + Rule::ExactPixel => "exact-pixel", } } @@ -173,12 +202,19 @@ impl Rule { 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", + Rule::Mirror => "compare with an expected value written out, not with a second call of the same function", + Rule::ConstantEcho => "assert what the code under test returns, not a constant or literal the test or crate states", + Rule::FixtureOnly => "assert on what the code under test returns or changes, not on the input the test built", + Rule::NeverRun => "make the test build on a target CI runs (Linux, FreeBSD), or run it in a CI leg for its target", + Rule::ExactPixel => { + "assert relationships (inside its container, not overlapping, order, gap at least a spacing token), not a rect equal to numbers" + } } } /// Whether a hit on a changed line fails the command. The other rules only report. pub fn fails(self) -> bool { - matches!(self, Rule::SelfCompare | Rule::IgnoreWithoutReason | Rule::Sleep) + matches!(self, Rule::SelfCompare | Rule::IgnoreWithoutReason | Rule::Sleep | Rule::ReadsSource | Rule::NeverRun) } fn from_id(id: &str) -> Option { @@ -213,10 +249,19 @@ impl Hit { } } -/// What the rules need beyond the file: asserting helper names by crate and the variables CI sets. +/// What the rules need beyond the file: asserting helper names by crate, the variables CI sets, and +/// the `cfg` predicates each file's module inherits from the `mod` declarations above it. +#[derive(Default)] pub struct Ctx { pub helpers: HashMap>, pub ci_env: HashSet, + pub module_cfgs: HashMap>, +} + +/// A source file read from the work tree, or `None` when it is missing or larger than [`MAX_FILE`]. +fn read_small(root: &Path, path: &str) -> Option { + let full = root.join(path); + (std::fs::metadata(&full).ok()?.len() <= MAX_FILE).then(|| std::fs::read_to_string(full).ok()).flatten() } pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { @@ -226,7 +271,8 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let files: Vec = repo.into_iter().filter(|p| is_scanned(p)).collect(); if opts.all { let sources = read_all(root, &files)?; - let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env }; + let module_cfgs = module_cfgs(&files, &|p| read_small(root, p)); + let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs }; let hits: Vec = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); print!("{}", report(&hits, sources.len())); return Ok(()); @@ -236,8 +282,9 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let changed: BTreeMap>> = changed.into_iter().filter(|(p, _)| is_scanned(p)).collect(); let crates: BTreeSet = changed.keys().map(|p| crate_of(p)).chain([TESTKIT.to_owned()]).collect(); let helper_files: Vec = files.iter().filter(|p| crates.contains(&crate_of(p))).cloned().collect(); - let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env }; let present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); + let module_cfgs = module_cfgs(&present, &|p| read_small(root, p)); + let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { for hit in lint_file(&path, &src, &ctx) { @@ -1241,7 +1288,9 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { 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.extend(mirrors(&v)); + hits.extend(exact_pixels(&v)); + hits.extend([only_weak(&v), exit_status_only(&v), no_assertion(&v), echoes(&v), never_run(&v, ctx)].into_iter().flatten()); hits } @@ -2816,7 +2865,12 @@ fn reads_source_hits(file: &File) -> Vec { } let m = &file.m; let mut out = vec![]; - for (word, note) in [(&b"include_str"[..], "includes a .rs file as text"), (&b"ends_with"[..], "keeps files ending in .rs")] { + let words_and_notes = [ + (&b"include_str"[..], "includes a .rs file as text"), + (&b"ends_with"[..], "keeps files ending in .rs"), + (&b"read_to_string"[..], "reads a .rs file as text"), + ]; + for (word, note) in words_and_notes { for at in words(m, word, 0, m.len()).into_iter().filter(|&at| in_regions(&file.regions, at)) { let open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; @@ -2824,7 +2878,12 @@ fn reads_source_hits(file: &File) -> Vec { // An ordinary or raw string literal: `".rs"`, `r".rs"`, `r#"…/lib.rs"#`. let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); let literal = raw.unwrap_or(&arg); - let rs = if word == b"ends_with" { literal == "\".rs\"" } else { arg.trim_end_matches('#').ends_with(".rs\"") }; + let rs = match word { + b"ends_with" => literal == "\".rs\"", + // A path literal anywhere in the argument: `root.join("src/lib.rs")`, `concat!(…, "/x.rs")`. + b"read_to_string" => false, + _ => arg.trim_end_matches('#').ends_with(".rs\""), + }; if rs { out.push(file.hit(at, Rule::ReadsSource, file.test_at(at), note.into())); } @@ -2833,12 +2892,450 @@ fn reads_source_hits(file: &File) -> Vec { out } +// ---- Mirrors, echoes, never-run tests and exact pixels ---- + +/// Names a `mirror` comparison may call on both sides: builders, conversions and accessors. +const MIRROR_NEUTRAL: &[&str] = &[ + "new", "from", "into", "default", "clone", "to_string", "to_owned", "to_vec", "iter", "into_iter", "collect", "unwrap", "expect", "len", + "get", "as_str", "as_ref", "as_slice", "format", "vec", "Some", "Ok", "Err", "Box", "String", "Vec", "map", "cloned", "copied", +]; + +/// The function a whitespace-free operand starts by calling, with its path: `f` in `f(x).g()`, +/// `Kind::parse` in `Kind::parse(s)`. A method call on a value (`doc.node(id)`) is not one: two reads of the same +/// accessor compare two different things. +fn head_call(op: &str) -> Option<&str> { + let b = op.as_bytes(); + let mut i = 0; + loop { + let end = i + b.get(i..)?.iter().take_while(|&&c| is_ident(c)).count(); + if end == i || b[i].is_ascii_digit() { + return None; + } + match b.get(end) { + Some(b':') if b.get(end + 1) == Some(&b':') => i = end + 2, + Some(b'(') => return Some(&op[..end]), + _ => return None, + } + } +} + +/// `assert_eq!(f(a), f(b))`: both sides start by calling the same function, so a fault in `f` can +/// move both sides together. Identical sides are `self-compare`'s. +fn mirrors(v: &View) -> Vec { + v.asserts + .iter() + .filter(|a| a.name.ends_with("_eq")) + .filter_map(|a| { + let (l, r) = (norm(&v.file.m[a.args.first()?.0..a.args.first()?.1]), norm(&v.file.m[a.args.get(1)?.0..a.args.get(1)?.1])); + let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&')); + let name = head_call(l)?; + // The expected side derives its value from a second call with arithmetic; two calls + // compared as they are check that two inputs agree, which is a real check. + let derived = ["+", "-", "*", "/"].iter().any(|op| !top_level_at(r, op).is_empty()); + let last = name.rsplit("::").next().unwrap_or(name); + (l != r && derived && head_call(r) == Some(name) && !MIRROR_NEUTRAL.contains(&last)) + .then(|| v.hit(a.at, Rule::Mirror, format!("{}! calls `{name}` on both sides", a.name))) + }) + .collect() +} + +/// Methods that only read a value the test built itself. +const FIXTURE_READS: &[&str] = &["len", "is_empty", "clone", "to_string", "to_owned", "as_str", "as_ref", "as_slice", "to_vec", "into"]; + +/// Lowercase names that are types or keywords, not locals. +const PLAIN_NAMES: &[&str] = &[ + "true", "false", "as", "f32", "f64", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", + "bool", "char", "str", +]; + +fn screaming_or_camel(name: &str) -> bool { + name.as_bytes().first().is_some_and(u8::is_ascii_uppercase) +} + +/// Whether a (whitespace-free, masked) operand reads only literals, constants, enum variants and the +/// test's own locals bound to such values: `Some(true)` when it reads such a local, `Some(false)` +/// when it reads none, `None` when it calls or reads anything else. +fn inert(op: &str, local: &dyn Fn(&str) -> Option) -> Option { + let b = op.as_bytes(); + let mut reads_local = false; + let mut i = 0; + while i < b.len() { + if !is_ident(b[i]) || b[i].is_ascii_digit() || (i > 0 && is_ident(b[i - 1])) { + // Number suffixes (`1.0f32`, `2_u8`) are part of the literal. + if b[i].is_ascii_digit() { + i += b[i..].iter().take_while(|&&c| is_ident(c)).count(); + continue; + } + i += 1; + continue; + } + let end = i + b[i..].iter().take_while(|&&c| is_ident(c)).count(); + let name = &op[i..end]; + let after = &op[end..]; + let method = op[..i].ends_with('.') && !op[..i].ends_with(".."); + let path_tail = op[..i].ends_with("::"); + if method { + if after.starts_with('(') && !FIXTURE_READS.contains(&name) { + return None; + } + } else if after.starts_with("::") || PLAIN_NAMES.contains(&name) { + } else if after.starts_with('!') && !after.starts_with("!=") { + // `format!` can read locals inside its string (`"{got:?}"`), which masking hides. + if name != "vec" { + return None; + } + } else if after.starts_with('(') { + let builder = ["Some", "Ok", "Err"].contains(&name) + || (path_tail && ["Box::new", "String::from", "Vec::new"].iter().any(|p| op[..end].ends_with(p))) + || (!path_tail && screaming_or_camel(name)); + if !builder { + return None; + } + } else if after.starts_with(':') || screaming_or_camel(name) { + // A field name in a struct literal, a constant or a variant. + } else if path_tail { + return None; + } else { + match local(name) { + Some(true) => reads_local = true, + _ => return None, + } + } + i = end; + } + Some(reads_local) +} + +/// The initializer of the last immutable `let = …;` in `body[..before]`: `None` when there is +/// none, `Some(None)` when the reaching binding is `mut`, a pattern or has no initializer. The +/// initializer comes with the offset of its `let`, where the names it reads are resolved. +fn reaching_init(body: &[u8], name: &str, before: usize) -> Option> { + let mut found = None; + for at in words(body, b"let", 0, before) { + let start = skip_ws(body, at + 3); + let is_mut = body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace); + let n0 = if is_mut { skip_ws(body, start + 3) } else { start }; + let n1 = n0 + body[n0..].iter().take_while(|&&c| is_ident(c)).count(); + let stop = statement_end(body, n1); + if stop > before || block_close(body, at) < before { + continue; + } + let rest = norm(&body[n1..stop]); + let plain = n1 > n0 && (rest.is_empty() || rest.starts_with(':') || rest.starts_with('=')); + if plain && &body[n0..n1] == name.as_bytes() { + let init = rest.split_once('=').filter(|(ty, _)| ty.is_empty() || ty.starts_with(':')).map(|(_, init)| (init.to_owned(), at)); + found = Some(if is_mut { None } else { init }); + } else if !plain { + // A pattern that binds the name (`let (a, b) = …`, `let Foo { a, .. } = …`). + let pattern = norm(&body[n0..stop]); + let pattern = pattern.split_once('=').map_or(pattern.as_str(), |(p, _)| p); + if !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() { + found = Some(None); + } + } + } + found +} + +/// Where the innermost block holding `at` closes: its `}`, or the end of `body`. +fn block_close(body: &[u8], at: usize) -> usize { + let mut depth = 0usize; + for i in (0..at).rev() { + match body[i] { + b'}' => depth += 1, + b'{' if depth == 0 => return matching(body, i).unwrap_or(body.len()), + b'{' => depth -= 1, + _ => {} + } + } + body.len() +} + +/// `inert` for an operand of the test at `pos`, resolving locals through their initializers. +fn inert_at(body: &[u8], op: &str, pos: usize, depth: usize) -> Option { + let local = |name: &str| -> Option { + if depth > 8 { + return None; + } + let (init, at) = reaching_init(body, name, pos)??; + inert_at(body, &init, at, depth + 1).map(|_| true) + }; + inert(op, &local) +} + +/// `constant-echo` and `fixture-only`: every assertion of the test reads only constants and +/// literals, or the test's own locals bound to them, so no result of the code under test is checked. +fn echoes(v: &View) -> Option { + if v.asserts.is_empty() || v.delegates || v.should_panic { + return None; + } + let body = v.body_without_messages(); + if contains(&body, b"panic!") || contains(&body, b".unwrap_err()") || contains(&body, b".expect_err(") { + return None; + } + let mut reads_local = false; + for a in &v.asserts { + let n = guard_arg_count(&a.name); + if n == 0 { + return None; + } + for &(from, to) in a.args.iter().take(n) { + let op = norm(&body[from - v.t.open..to - v.t.open]); + reads_local |= inert_at(&body, &op, from - v.t.open, 0)?; + } + } + Some(if reads_local { + v.whole(Rule::FixtureOnly, "every assertion reads only locals the test bound to literals or constants".into()) + } else { + v.whole(Rule::ConstantEcho, "every assertion compares only constants and literals".into()) + }) +} + +/// A target CI builds and runs the tests on. +struct Target { + os: &'static str, + family: &'static str, + arch: &'static str, +} + +/// The shared gate (Linux) and the FreeBSD workflow run every test. +const CI_TARGETS: &[Target] = + &[Target { os: "linux", family: "unix", arch: "x86_64" }, Target { os: "freebsd", family: "unix", arch: "x86_64" }]; + +/// The printing workflow also runs the app's tests and the UI crate's print tests on Windows. +const WINDOWS_TARGET: Target = Target { os: "windows", family: "windows", arch: "x86_64" }; + +fn windows_runs(path: &str) -> bool { + path.starts_with("apps/vectorcraft/") || path == "crates/ui-egui/src/tests/printps.rs" +} + +/// Whether a (whitespace-free) `cfg` predicate holds on `t`: `None` when it depends on something +/// else (a feature, `debug_assertions`, an unknown key). +fn cfg_value(p: &str, t: &Target) -> Option { + for (head, all) in [("all(", true), ("any(", false)] { + if let Some(args) = p.strip_prefix(head).and_then(|a| a.strip_suffix(')')) { + let mut parts = vec![]; + let mut start = 0; + for at in top_level_at(args, ",").into_iter().chain([args.len()]) { + if at > start { + parts.push(cfg_value(&args[start..at], t)); + } + start = at + 1; + } + return if parts.contains(&Some(!all)) { + Some(!all) + } else if parts.iter().all(Option::is_some) { + Some(all) + } else { + None + }; + } + } + if let Some(arg) = p.strip_prefix("not(").and_then(|a| a.strip_suffix(')')) { + return cfg_value(arg, t).map(|v| !v); + } + // An ordinary or raw string value: `"linux"`, `r"linux"`, `r#"linux"#`. + let (key, value) = p.split_once('=').map_or((p, ""), |(k, v)| (k, v.strip_prefix('r').unwrap_or(v).trim_matches('#').trim_matches('"'))); + match key { + "test" => Some(true), + "unix" => Some(t.family == "unix"), + "windows" => Some(t.family == "windows"), + "target_os" => Some(t.os == value), + "target_family" => Some(t.family == value), + "target_arch" => Some(t.arch == value), + "target_pointer_width" => Some(value == "64"), + _ => None, + } +} + +/// The predicates of the `#[cfg(…)]` and `#![cfg(…)]` attributes whose item holds `pos`. +fn cfgs_over(file: &File, pos: usize) -> Vec { + let m = &file.m; + let mut out = vec![]; + for at in words(m, b"cfg", 0, m.len()) { + let before = m[..at].trim_ascii_end(); + let Some(hash) = before.strip_suffix(b"[").map(<[u8]>::trim_ascii_end) else { continue }; + let inner = hash.ends_with(b"#!"); + if !inner && !hash.ends_with(b"#") { + continue; + } + let open = skip_ws(m, at + "cfg".len()); + let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; + let end = skip_ws(m, close + 1); + if m.get(end) != Some(&b']') { + continue; + } + let span = if inner { + // An inner attribute covers the file (or the module) it opens. + let enclosing = m[..at].iter().rposition(|&c| c == b'{'); + enclosing.and_then(|o| matching(m, o).map(|c| (o, c))).unwrap_or((0, m.len())) + } else { + let after = end + 1; + let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; + match (m[open], matching(m, open)) { + (b'{', Some(close)) => (at, close), + _ => continue, + } + }; + if span.0 <= pos && pos <= span.1 { + // The source text: masking blanks the string literals `target_os = "macos"` needs. + out.push(file.src_norm((open + 1, close))); + } + } + out +} + +/// The module name a file declares and the files that may declare it with `mod ;`, or `None` +/// for a crate root (`lib.rs`, `main.rs`, `build.rs`, a file directly in `tests`, `benches` or +/// `examples`). +fn module_parent(path: &str) -> Option<(&str, Vec)> { + let (dir, file) = path.rsplit_once('/')?; + let root_dir = ["/tests", "/benches", "/examples"].iter().any(|d| dir.ends_with(d)); + if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") { + return None; + } + let (name, parent) = if file == "mod.rs" { dir.rsplit_once('/').map(|(p, n)| (n, p))? } else { (file.strip_suffix(".rs")?, dir) }; + let mut candidates: Vec = ["mod.rs", "lib.rs", "main.rs"].iter().map(|f| format!("{parent}/{f}")).collect(); + candidates.push(format!("{parent}.rs")); + Some((name, candidates)) +} + +/// The predicates of the `#[cfg(…)]` attributes on a `mod ;` declaration in `src`, or `None` +/// when `src` declares no such module. +fn declared_cfgs(src: &str, name: &str) -> Option> { + let m = mask(src); + let decl = words(&m, b"mod", 0, m.len()).into_iter().find(|&at| { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + &m[start..end] == name.as_bytes() && m.get(skip_ws(&m, end)) == Some(&b';') + })?; + let item = m[..decl].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let mut out = vec![]; + for at in words(&m, b"cfg", item, decl) { + let open = skip_ws(&m, at + 3); + let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + if let Some(close) = (attr && m.get(open) == Some(&b'(')).then(|| matching(&m, open)).flatten() { + out.push(norm(&src.as_bytes()[open + 1..close])); + } + } + Some(out) +} + +/// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the +/// modules above it, read through `read`. +fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { + let mut out = HashMap::new(); + for path in paths { + let (mut preds, mut at) = (vec![], path.clone()); + for _ in 0..16 { + let Some((name, candidates)) = module_parent(&at) else { break }; + let Some((parent, found)) = candidates.into_iter().find_map(|c| read(&c).and_then(|s| declared_cfgs(&s, name)).map(|f| (c, f))) else { + break; + }; + preds.extend(found); + at = parent; + } + if !preds.is_empty() { + out.insert(path.clone(), preds); + } + } + out +} + +/// A test that a `cfg` compiles out on every target CI runs tests on. +fn never_run(v: &View, ctx: &Ctx) -> Option { + let mut preds = cfgs_over(v.file, v.t.fn_at); + preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned()); + if preds.is_empty() { + return None; + } + let windows = windows_runs(v.file.path).then_some(&WINDOWS_TARGET); + let off = |t: &Target| preds.iter().any(|p| cfg_value(p, t) == Some(false)); + if CI_TARGETS.iter().chain(windows).all(off) { + let shown: Vec = preds.iter().filter(|p| p.as_str() != "test").map(|p| format!("cfg({p})")).collect(); + return Some(v.whole(Rule::NeverRun, format!("{} leaves it out of every target CI tests on", shown.join(", ")))); + } + None +} + +/// What may follow a screen rect in an exact-pixel comparison: a corner, an edge or a size. +const RECT_PARTS: &[&str] = &[ + ".min", ".max", ".left_top()", ".right_bottom()", ".center()", ".size()", ".width()", ".height()", ".left()", ".right()", ".top()", + ".bottom()", +]; + +/// Whether a whitespace-free operand reads a screen rect: an identifier `rect`, or one that starts +/// with `rect_` or ends with `_rect` (a call to one included), taken whole or through +/// [`RECT_PARTS`]. Document geometry (artboards, `x0`/`y0` corners, a document's nodes) and a rect +/// passed on as an argument do not count. +fn names_rect(op: &str) -> bool { + if ["artboard", "doc", ".x0", ".y0", ".x1", ".y1", "obox"].iter().any(|w| op.contains(w)) { + return false; + } + let b = op.as_bytes(); + let mut i = 0; + while i < b.len() { + if !is_ident(b[i]) || (i > 0 && is_ident(b[i - 1])) { + i += 1; + continue; + } + let end = i + b[i..].iter().take_while(|&&c| is_ident(c)).count(); + let w = &op[i..end]; + if w == "rect" || w.starts_with("rect_") || w.ends_with("_rect") { + let mut after = end; + if b.get(after) == Some(&b'(') { + after = matching(b, after).map_or(b.len(), |c| c + 1); + } + let rest = &op[after..]; + if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.starts_with(p)) { + return true; + } + } + i = end; + } + false +} + +/// Whether a whitespace-free operand is only numbers, alone or in `pos2`, `vec2` or `Rect` builders. +fn only_numbers(op: &str) -> bool { + let mut rest = op.trim_start_matches('&').replace("egui::", "").replace("emath::", ""); + for builder in ["Rect::from_min_max", "Rect::from_min_size", "Rect::from_center_size", "Pos2::new", "Vec2::new", "pos2", "vec2", "Some"] { + rest = rest.replace(builder, ""); + } + let rest = rest.replace("f32", ""); + rest.bytes().any(|c| c.is_ascii_digit()) && rest.bytes().all(|c| c.is_ascii_digit() || b".,()-+_".contains(&c)) +} + +/// An assertion in a UI test that a rect, or a coordinate or size of one, equals numbers written out. +fn exact_pixels(v: &View) -> Vec { + if !contains(&v.file.m, b"egui") { + return vec![]; + } + v.asserts + .iter() + .filter_map(|a| { + let arg = |i: usize| a.args.get(i).map(|&(f, t)| norm(&v.file.m[f..t])); + let (l, r) = if a.name.ends_with("_eq") { + (arg(0)?, arg(1)?) + } else if PLAIN_ASSERTS.contains(&a.name.as_str()) { + let cond = arg(0)?; + let at = *top_level_at(&cond, "==").first()?; + (cond[..at].to_owned(), cond[at + 2..].to_owned()) + } else { + return None; + }; + let pixel = (names_rect(&l) && only_numbers(&r)) || (names_rect(&r) && only_numbers(&l)); + pixel.then(|| v.hit(a.at, Rule::ExactPixel, format!("{}! compares a rect with numbers written out", a.name))) + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; fn ctx() -> Ctx { - Ctx { helpers: HashMap::new(), ci_env: ["SET_IN_CI".to_owned()].into_iter().collect() } + Ctx { ci_env: ["SET_IN_CI".to_owned()].into_iter().collect(), ..Ctx::default() } } /// The rule ids of `src`'s hits, as `(line, rule)`. @@ -3807,12 +4304,12 @@ mod tests { let src = "fn same(a: u8, b: u8) {\n assert_eq!(a, b);\n}\nfn twice(a: u8) {\n same(a, a);\n}\n#[test]\nfn t() {\n twice(f());\n}\n#[test]\n#[should_panic]\nfn p() {\n f();\n}\n#[test]\nfn q() {\n check_round_trip(f());\n}\n"; let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); assert!(helpers["crates/x"].contains("twice"), "{helpers:?}"); - let ctx = Ctx { helpers, ci_env: HashSet::new() }; + let ctx = Ctx { helpers, ..Ctx::default() }; assert_eq!(hits_in("crates/x/tests/it.rs", src, &ctx), []); assert_eq!(hits_in("crates/y/tests/it.rs", src, &ctx), [(8, "no-assertion")], "another crate's helper does not count"); let kit = asserting_helpers(&[("crates/testkit/src/lib.rs".to_owned(), src.to_owned()), ("crates/y/src/lib.rs".to_owned(), String::new())]); assert!(kit["crates/y"].contains("twice"), "testkit helpers count in every crate: {kit:?}"); - assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx { helpers: HashMap::new(), ci_env: HashSet::new() }), [(8, "no-assertion")]); + assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx::default()), [(8, "no-assertion")]); } #[test] @@ -3834,7 +4331,7 @@ mod tests { assert!(helpers["crates/x"].contains("same")); assert!(helpers["crates/x"].contains("twice")); assert!(!helpers["crates/x"].contains("idle")); - let ctx = Ctx { helpers, ci_env: HashSet::new() }; + let ctx = Ctx { helpers, ..Ctx::default() }; for call in ["same::(a, b)", "twice::>>(x)"] { let src = format!("#[test]\nfn t() {{\n {call};\n}}\n"); assert_eq!(hits_in("crates/x/tests/it.rs", &src, &ctx), [], "{call}"); @@ -4062,7 +4559,9 @@ mod tests { #[test] fn only_failing_rules_fail_the_check() { let failing: Vec<&str> = Rule::ALL.into_iter().filter(|r| r.fails()).map(Rule::id).collect(); - assert_eq!(failing, ["self-compare", "ignore-without-reason", "sleep"]); + assert_eq!(failing, ["self-compare", "ignore-without-reason", "sleep", "reads-source", "never-run"]); + let mac = "#[cfg(target_os = \"macos\")]\n#[test]\nfn mac() {\n assert_eq!(f(), 1);\n}\n"; + assert!(finish(&lint_file("crates/x/src/tests.rs", mac, &ctx()), 0, 1, "base").is_err(), "never-run fails the check"); let weak = "#[test]\nfn weak() {\n assert!(f().is_ok());\n}\n"; let unguarded = "#[test]\nfn all() {\n assert!(f().iter().all(|x| valid(x)));\n}\n"; let skipped = "#[test]\n#[ignore]\nfn skipped() {\n assert_eq!(f(), 1);\n}\n"; @@ -4128,11 +4627,11 @@ mod tests { fn workflow_mentions_do_not_suppress_unset_gates() { let src = "#[test]\nfn t() {\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; for workflow in ["if: env.MY_SAMPLES != ''", "run: echo $MY_SAMPLES", "# MY_SAMPLES=value"] { - let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words(workflow).collect() }; + let ctx = Ctx { ci_env: upper_words(workflow).collect(), ..Ctx::default() }; assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [(3, "env-gate-unset")], "{workflow}"); } for workflow in ["env:\n MY_SAMPLES: fixtures", "run: |\n export MY_SAMPLES=fixtures", "with:\n env: |\n MY_SAMPLES=fixtures"] { - let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words(workflow).collect() }; + let ctx = Ctx { ci_env: upper_words(workflow).collect(), ..Ctx::default() }; assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [], "{workflow}"); } } @@ -4174,10 +4673,10 @@ mod tests { let src = "mod a {\n pub fn exercise() { assert_eq!(f(), 1); }\n}\nmod b {\n pub fn exercise() { f(); }\n}\n#[test]\nfn t() {\n b::exercise();\n}\n"; let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); assert!(!helpers["crates/x"].contains("exercise"), "{helpers:?}"); - assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx { helpers, ci_env: HashSet::new() }), [(8, "no-assertion")]); + assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx { helpers, ..Ctx::default() }), [(8, "no-assertion")]); let both = src.replace("{ f(); }", "{ assert!(f()); }"); let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), both.clone())]); - assert_eq!(hits_in("crates/x/tests/it.rs", &both, &Ctx { helpers, ci_env: HashSet::new() }), []); + assert_eq!(hits_in("crates/x/tests/it.rs", &both, &Ctx { helpers, ..Ctx::default() }), []); } #[test] @@ -4246,7 +4745,7 @@ mod tests { fn single_letter_variables_set_in_ci_count() { let src = "#[test]\nfn t() {\n let dir = std::env::var(\"X\");\n assert_eq!(f(dir), 3);\n}\n"; assert_eq!(hits(src), [(3, "env-gate-unset")]); - let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words("env:\n X: 1\n").collect() }; + let ctx = Ctx { ci_env: upper_words("env:\n X: 1\n").collect(), ..Ctx::default() }; assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), []); } @@ -4310,4 +4809,131 @@ mod tests { assert_eq!(found.iter().map(|h| (h.rule, h.line, h.first, h.last)).collect::>(), [(Rule::IgnoreWithoutReason, 2, 2, 3)]); assert!(touches(&found[0], Some(&[3].into_iter().collect())), "a change to the reason alone"); } + + fn only(rule: &'static str, src: &str) -> Vec<(usize, &'static str)> { + hits(src).into_iter().filter(|h| h.1 == rule).collect() + } + + #[test] + fn mirrors_call_the_same_function_on_both_sides() { + let bad = "#[test]\nfn t() {\n assert_eq!(scale(p, 2.0), scale(p, 1.0) * 2.0);\n}\n"; + assert_eq!(only("mirror", bad), [(3, "mirror")]); + let written = "#[test]\nfn t() {\n assert_eq!(scale(p, 2.0), Point::new(2.0, 4.0));\n}\n"; + assert_eq!(only("mirror", written), []); + let builders = "#[test]\nfn t() {\n assert_eq!(Some(area(a)), Some(4.0));\n assert_eq!(a.to_string(), b.to_string());\n}\n"; + assert_eq!(only("mirror", builders), [], "a builder or conversion on both sides"); + let same = "#[test]\nfn t() {\n assert_eq!(scale(p), scale(p));\n}\n"; + assert_eq!(only("mirror", same), [], "identical sides are self-compare's"); + let oracle = "#[test]\nfn t() {\n assert_eq!(actual::area(s), reference::area(s) * 2.0);\n}\n"; + assert_eq!(only("mirror", oracle), [], "two functions of the same name in different paths"); + let ne = "#[test]\nfn t() {\n assert_ne!(hash(a), hash(b));\n}\n"; + assert_eq!(only("mirror", ne), [], "two inputs that must differ"); + let allowed = "#[test]\nfn t() {\n // test-lint: allow mirror both spellings parse to one value\n assert_eq!(parse(\"a\"), parse(\"A\"));\n}\n"; + assert_eq!(only("mirror", allowed), []); + } + + #[test] + fn echoes_check_only_constants_or_the_fixture() { + let constant = "#[test]\nfn t() {\n assert_eq!(MAX_ZOOM, 64.0);\n assert!(Kind::A != Kind::B);\n}\n"; + assert_eq!(only("constant-echo", constant), [(2, "constant-echo")]); + let fixture = + "#[test]\nfn t() {\n let input = vec![1, 2, 3];\n let n = 3;\n let _ = process(&input);\n assert_eq!(input.len(), n);\n}\n"; + assert_eq!(only("fixture-only", fixture), [(2, "fixture-only")]); + let result = "#[test]\nfn t() {\n let input = vec![1, 2, 3];\n let out = process(&input);\n assert_eq!(out.len(), 3);\n}\n"; + assert_eq!(only("fixture-only", result), [], "the result of the code under test"); + let changed = "#[test]\nfn t() {\n let mut input = vec![1, 2, 3];\n process(&mut input);\n assert_eq!(input.len(), 3);\n}\n"; + assert_eq!(only("fixture-only", changed), [], "a mutable local the code changes"); + let borrowed = "#[test]\nfn t() {\n let input = &mut [3, 1];\n sort(input);\n assert_eq!(*input, [1, 3]);\n}\n"; + assert_eq!(only("fixture-only", borrowed), [], "an immutable binding of a mutable reference"); + let pattern = "#[test]\nfn t() {\n let (a, b) = split(4);\n assert_eq!(a, 2);\n assert_eq!(b, 2);\n}\n"; + assert_eq!(only("fixture-only", pattern), [], "a pattern binding of a result"); + let mixed = "#[test]\nfn t() {\n assert_eq!(MAX_ZOOM, 64.0);\n assert_eq!(zoom_in(1.0), 2.0);\n}\n"; + assert_eq!(only("constant-echo", mixed), [], "one real assertion keeps the test"); + let shadowed = "#[test]\nfn t() {\n let x = 1;\n let x = double(x);\n assert_eq!(x, 2);\n}\n"; + assert_eq!(only("fixture-only", shadowed), [], "the reaching binding is a call"); + let helper = "#[test]\nfn t() {\n assert_eq!(MAX, 4);\n check_all();\n}\n"; + assert_eq!(only("constant-echo", helper), [], "an asserting helper"); + let printed = "#[test]\nfn t() {\n let got = sample(1.0);\n assert_eq!(format!(\"{got:?}\"), \"1\");\n}\n"; + assert_eq!(hits(printed), [], "format! reads a local inside its string"); + let scoped = "#[test]\nfn t() {\n let result = compute();\n {\n let result = 0;\n consume(result);\n }\n assert_eq!(result, 1);\n}\n"; + assert_eq!(hits(scoped), [], "a binding in a block that has ended"); + let later = "#[test]\nfn t() {\n let x = compute();\n let y = x;\n let x = 0;\n assert_eq!(y, 2);\n assert_eq!(x, 0);\n}\n"; + assert_eq!(hits(later), [], "an initializer reads the binding that reaches it, not a later one"); + } + + #[test] + fn never_run_tests_are_compiled_out_on_every_ci_target() { + let mac = "#[cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", mac), [(3, "never-run")]); + let module = "#[cfg(all(test, windows))]\nmod tests {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + assert_eq!(hits_in("crates/x/src/lib.rs", module, &ctx()).into_iter().filter(|h| h.1 == "never-run").count(), 1); + let file = "#![cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", file), [(3, "never-run")]); + let unix = "#[cfg(unix)]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", unix), [], "Linux runs it"); + let not_mac = "#[cfg(not(target_os = \"macos\"))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", not_mac), []); + let raw = "#[cfg(target_os = r\"linux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", raw), [], "a raw string value"); + let feature = "#[cfg(feature = \"gpu\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", feature), [], "a feature CI may enable"); + let any = "#[cfg(any(target_os = \"macos\", target_os = \"linux\"))]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", any), []); + let win = "#[cfg(windows)]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in("apps/vectorcraft/src/printing/tests.rs", win, &ctx()), [], "the printing workflow runs it on Windows"); + assert_eq!(hits_in("crates/x/src/tests.rs", win, &ctx()), [(3, "never-run")]); + let other = "#[cfg(target_os = \"macos\")]\nfn helper() {}\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", other), [], "a cfg on another item"); + } + + #[test] + fn never_run_follows_the_cfg_of_the_mod_declaration() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod mac;\nmod plain;\n"), + ("crates/x/src/mac.rs", "mod inner;\n"), + ("crates/x/src/mac/inner.rs", ""), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let paths: Vec = ["crates/x/src/mac.rs", "crates/x/src/mac/inner.rs", "crates/x/src/plain.rs", "crates/x/tests/it.rs"] + .into_iter() + .map(String::from) + .collect(); + let cfgs = module_cfgs(&paths, &read); + assert_eq!(cfgs.get("crates/x/src/mac.rs").map(Vec::as_slice), Some(&["target_os=\"macos\"".to_owned()][..])); + assert!(cfgs.contains_key("crates/x/src/mac/inner.rs"), "inherited through mac.rs"); + assert!(!cfgs.contains_key("crates/x/src/plain.rs") && !cfgs.contains_key("crates/x/tests/it.rs")); + let ctx = Ctx { module_cfgs: cfgs, ..ctx() }; + let test = "#[cfg(test)]\nmod tests {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + assert_eq!(hits_in("crates/x/src/mac/inner.rs", test, &ctx), [(4, "never-run")]); + assert_eq!(hits_in("crates/x/src/plain.rs", test, &ctx), []); + } + + #[test] + fn exact_pixels_compare_a_rect_with_numbers() { + let ui = |body: &str| format!("use egui::Rect;\n#[test]\nfn t() {{\n {body}\n}}\n"); + let px = |body: &str| only("exact-pixel", &ui(body)); + assert_eq!(px("assert_eq!(button_rect.min.x, 12.0);"), [(4, "exact-pixel")]); + assert_eq!(px("assert_eq!(resp.rect, Rect::from_min_size(pos2(0.0, 20.0), vec2(80.0, 24.0)));"), [(4, "exact-pixel")]); + assert_eq!(px("assert!(rect.width() == 120.0);"), [(4, "exact-pixel")]); + assert_eq!(px("assert!(panel_rect.contains_rect(button_rect));"), [], "a relationship"); + assert_eq!(px("assert!(rect.width() >= SPACING);"), []); + assert_eq!(px("assert_eq!(rects.len(), 3);"), [], "a count"); + assert_eq!(px("assert_eq!(correct, 3);"), [], "a word that only contains rect"); + assert_eq!(px("assert_eq!(tabs_rect(&app).min.y, 0.0);"), [(4, "exact-pixel")], "a call that returns a rect"); + assert_eq!(px("assert_eq!(doc.artboards[1].rect.width(), 100.0);"), [], "document geometry in a UI test"); + assert_eq!(px("assert_eq!((rect.x0, rect.y0), (200.0, 200.0));"), [], "document corners"); + assert_eq!(px("assert_eq!(rgb8(&fill_color(&app, rect)), [255, 255, 255]);"), [], "a rect passed on"); + let engine = "#[test]\nfn t() {\n assert_eq!(art_rect.width(), 10.0);\n}\n"; + assert_eq!(only("exact-pixel", engine), [], "document geometry outside UI code"); + } + + #[test] + fn reads_source_covers_read_to_string_of_rust_files() { + let read = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src/lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", read), [(3, "reads-source")]); + let data = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", data), []); + } } From c944c493e56c35537fe21ae6dd060b2970eef465 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 01:17:43 -0800 Subject: [PATCH 20/32] xtask: test-lint flags read_to_string of Rust files --- xtask/src/test_lint.rs | 55 +++++++++++++++++++++++++++++++++++------- 1 file changed, 46 insertions(+), 9 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index d40be26e68..7d1d8b49b4 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2931,7 +2931,7 @@ fn reads_source_hits(file: &File) -> Vec { let rs = match word { b"ends_with" => literal == "\".rs\"", // A path literal anywhere in the argument: `root.join("src/lib.rs")`, `concat!(…, "/x.rs")`. - b"read_to_string" => false, + b"read_to_string" => arg.contains(".rs\""), _ => arg.trim_end_matches('#').ends_with(".rs\""), }; if rs { @@ -2946,8 +2946,35 @@ fn reads_source_hits(file: &File) -> Vec { /// Names a `mirror` comparison may call on both sides: builders, conversions and accessors. const MIRROR_NEUTRAL: &[&str] = &[ - "new", "from", "into", "default", "clone", "to_string", "to_owned", "to_vec", "iter", "into_iter", "collect", "unwrap", "expect", "len", - "get", "as_str", "as_ref", "as_slice", "format", "vec", "Some", "Ok", "Err", "Box", "String", "Vec", "map", "cloned", "copied", + "new", + "from", + "into", + "default", + "clone", + "to_string", + "to_owned", + "to_vec", + "iter", + "into_iter", + "collect", + "unwrap", + "expect", + "len", + "get", + "as_str", + "as_ref", + "as_slice", + "format", + "vec", + "Some", + "Ok", + "Err", + "Box", + "String", + "Vec", + "map", + "cloned", + "copied", ]; /// The function a whitespace-free operand starts by calling, with its path: `f` in `f(x).g()`, @@ -2994,8 +3021,8 @@ const FIXTURE_READS: &[&str] = &["len", "is_empty", "clone", "to_string", "to_ow /// Lowercase names that are types or keywords, not locals. const PLAIN_NAMES: &[&str] = &[ - "true", "false", "as", "f32", "f64", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", - "bool", "char", "str", + "true", "false", "as", "f32", "f64", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "bool", "char", + "str", ]; fn screaming_or_camel(name: &str) -> bool { @@ -3149,8 +3176,7 @@ struct Target { } /// The shared gate (Linux) and the FreeBSD workflow run every test. -const CI_TARGETS: &[Target] = - &[Target { os: "linux", family: "unix", arch: "x86_64" }, Target { os: "freebsd", family: "unix", arch: "x86_64" }]; +const CI_TARGETS: &[Target] = &[Target { os: "linux", family: "unix", arch: "x86_64" }, Target { os: "freebsd", family: "unix", arch: "x86_64" }]; /// The printing workflow also runs the app's tests and the UI crate's print tests on Windows. const WINDOWS_TARGET: Target = Target { os: "windows", family: "windows", arch: "x86_64" }; @@ -3310,7 +3336,17 @@ fn never_run(v: &View, ctx: &Ctx) -> Option { /// What may follow a screen rect in an exact-pixel comparison: a corner, an edge or a size. const RECT_PARTS: &[&str] = &[ - ".min", ".max", ".left_top()", ".right_bottom()", ".center()", ".size()", ".width()", ".height()", ".left()", ".right()", ".top()", + ".min", + ".max", + ".left_top()", + ".right_bottom()", + ".center()", + ".size()", + ".width()", + ".height()", + ".left()", + ".right()", + ".top()", ".bottom()", ]; @@ -4909,7 +4945,8 @@ mod tests { assert_eq!(only("mirror", oracle), [], "two functions of the same name in different paths"); let ne = "#[test]\nfn t() {\n assert_ne!(hash(a), hash(b));\n}\n"; assert_eq!(only("mirror", ne), [], "two inputs that must differ"); - let allowed = "#[test]\nfn t() {\n // test-lint: allow mirror both spellings parse to one value\n assert_eq!(parse(\"a\"), parse(\"A\"));\n}\n"; + let allowed = + "#[test]\nfn t() {\n // test-lint: allow mirror both spellings parse to one value\n assert_eq!(parse(\"a\"), parse(\"A\"));\n}\n"; assert_eq!(only("mirror", allowed), []); } From 236149156b88f8fcc86d684192aae906a915b92a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 01:23:24 -0800 Subject: [PATCH 21/32] xtask: never-run follows cfg around mod declarations and counts cfg changes --- xtask/src/test_lint.rs | 42 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 7d1d8b49b4..a5fc3e4bbc 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -3224,9 +3224,9 @@ fn cfg_value(p: &str, t: &Target) -> Option { } } -/// The predicates of the `#[cfg(…)]` and `#![cfg(…)]` attributes whose item holds `pos`. -fn cfgs_over(file: &File, pos: usize) -> Vec { - let m = &file.m; +/// The predicates of the `#[cfg(…)]` and `#![cfg(…)]` attributes whose item holds `pos`, each with +/// the offset of its attribute. `m` is the masked text of `src`. +fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { let mut out = vec![]; for at in words(m, b"cfg", 0, m.len()) { let before = m[..at].trim_ascii_end(); @@ -3255,7 +3255,7 @@ fn cfgs_over(file: &File, pos: usize) -> Vec { }; if span.0 <= pos && pos <= span.1 { // The source text: masking blanks the string literals `target_os = "macos"` needs. - out.push(file.src_norm((open + 1, close))); + out.push((norm(&src[open + 1..close]), at)); } } out @@ -3276,8 +3276,8 @@ fn module_parent(path: &str) -> Option<(&str, Vec)> { Some((name, candidates)) } -/// The predicates of the `#[cfg(…)]` attributes on a `mod ;` declaration in `src`, or `None` -/// when `src` declares no such module. +/// The predicates of the `#[cfg(…)]` attributes on a `mod ;` declaration in `src` and on the +/// items and file around it, or `None` when `src` declares no such module. fn declared_cfgs(src: &str, name: &str) -> Option> { let m = mask(src); let decl = words(&m, b"mod", 0, m.len()).into_iter().find(|&at| { @@ -3294,6 +3294,7 @@ fn declared_cfgs(src: &str, name: &str) -> Option> { out.push(norm(&src.as_bytes()[open + 1..close])); } } + out.extend(cfgs_over(&m, src.as_bytes(), decl).into_iter().map(|(p, _)| p)); Some(out) } @@ -3320,7 +3321,10 @@ fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashM /// A test that a `cfg` compiles out on every target CI runs tests on. fn never_run(v: &View, ctx: &Ctx) -> Option { - let mut preds = cfgs_over(v.file, v.t.fn_at); + let local = cfgs_over(&v.file.m, v.file.src, v.t.fn_at); + // A change to an attribute that turns the test off counts as a change to the test. + let first_attr = local.iter().map(|&(_, at)| at).min(); + let mut preds: Vec = local.into_iter().map(|(p, _)| p).collect(); preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned()); if preds.is_empty() { return None; @@ -3329,7 +3333,11 @@ fn never_run(v: &View, ctx: &Ctx) -> Option { let off = |t: &Target| preds.iter().any(|p| cfg_value(p, t) == Some(false)); if CI_TARGETS.iter().chain(windows).all(off) { let shown: Vec = preds.iter().filter(|p| p.as_str() != "test").map(|p| format!("cfg({p})")).collect(); - return Some(v.whole(Rule::NeverRun, format!("{} leaves it out of every target CI tests on", shown.join(", ")))); + let mut hit = v.whole(Rule::NeverRun, format!("{} leaves it out of every target CI tests on", shown.join(", "))); + if let Some(at) = first_attr { + hit.first = hit.first.min(v.file.lines.of(at)); + } + return Some(hit); } None } @@ -5028,6 +5036,24 @@ mod tests { assert_eq!(hits_in("crates/x/src/plain.rs", test, &ctx), []); } + #[test] + fn never_run_follows_the_cfg_around_the_mod_declaration() { + let inner = "#![cfg(target_os = \"macos\")]\nmod child;\n"; + assert_eq!(declared_cfgs(inner, "child"), Some(vec!["target_os=\"macos\"".to_owned()])); + let block = "#[cfg(windows)]\nmod platform {\n mod child;\n}\n"; + assert_eq!(declared_cfgs(block, "child"), Some(vec!["windows".to_owned()])); + assert_eq!(declared_cfgs("mod child;\n", "child"), Some(vec![])); + } + + #[test] + fn never_run_hits_cover_the_attribute_that_turns_the_test_off() { + let src = "#[cfg(target_os = \"macos\")]\nmod mac {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).map(|h| (h.first, h.line)); + assert_eq!(hit, Some((1, 4))); + assert!(touches(found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(), Some(&[1].into_iter().collect())), "a change to the cfg alone"); + } + #[test] fn exact_pixels_compare_a_rect_with_numbers() { let ui = |body: &str| format!("use egui::Rect;\n#[test]\nfn t() {{\n {body}\n}}\n"); From 7407da03c8787b488d8d3b0ec5750a22e6fa1bd6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 01:35:17 -0800 Subject: [PATCH 22/32] Tests: the Stylistic Sets submenu test reads the sets from the face The test reads the expected ss01 to ss20 sets from the text's face, compares them with the panel's entries and with the submenu's toggle rows in order, and checks that the submenu is left out when the face offers no sets. Before, a face whose sets the panel dropped returned early and skipped every submenu assertion. --- crates/ui-egui/src/panels/opentype.rs | 30 +++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index b2c8f2cbe2..d61efcb289 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -857,6 +857,36 @@ mod tests { let sets = set_entries(&app, &st); // With the bundled fonts, the text's face offers sets. Without them, an installed face may. assert!(!cfg!(feature = "bundled-fonts") || !sets.is_empty(), "the bundled face of the text offers stylistic sets"); + // The submenu lists the `ss01` to `ss20` sets that the text's face offers, read here from + // the face itself, so the test returns early only when the face offers none. + let db = FontDb::global(); + let available = db.has_family(&db.canonical(&st.font_family, &st.font_style).0); + let face_sets = if available { db.style_face(&st).map(|face| face.stylistic_sets()).unwrap_or_default() } else { Vec::new() }; + let expected: Vec = face_sets.iter().filter(|set| (1..=20).contains(&set.number)).map(|set| format!("ss{:02}", set.number)).collect(); + let listed: Vec = sets.iter().map(|(_, flag, _)| flag.tag().unwrap_or_default().to_string()).collect(); + assert_eq!(listed, expected, "the submenu lists the stylistic sets of the text's face"); + let rows = menu_rows(&app); + if expected.is_empty() { + assert!(!rows.iter().any(|row| matches!(row, PanelRow::Submenu(..))), "the submenu is left out when the face offers no sets"); + } else { + let submenu = rows.iter().find_map(|row| match row { + PanelRow::Submenu(_, sub) if (1..=20).any(|number| has_row(sub, &toggle_ref(&format!("ss{number:02}")))) => Some(sub), + _ => None, + }); + let actual: Vec<&str> = submenu + .expect("the menu has a Stylistic Sets submenu") + .iter() + .filter_map(|row| match row { + PanelRow::Command(c) if c.id == TOGGLE => Some(c.params["tag"].as_str().expect("a toggle has a tag")), + _ => None, + }) + .collect(); + assert_eq!(actual, expected, "the submenu toggle tags match the face's sets in order"); + } + for tag in &expected { + let r = toggle_ref(tag); + assert!(rows.iter().any(|row| matches!(row, PanelRow::Submenu(_, sub) if has_row(sub, &r))), "the submenu has a row for {tag}"); + } let Some((first, flag, _)) = sets.first() else { return }; let (label, tag) = (set_label(first), flag.tag().unwrap()); set(&mut app, OtFeatures { small_caps: true, ..Default::default() }); From ded4e473a29f73fe134197df041b26d95a5f0dfc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:04:59 -0800 Subject: [PATCH 23/32] xtask: test-lint follows comments, inline and shared modules, and changed mod cfgs - never-run reads cfg predicates with comments removed, finds a module declared inside an inline module of its parent's parent, stops when several files declare a module with different attributes, and counts a change to a cfg on a mod declaration in another file against the tests it turns off. The lines between a module's cfg and the test no longer count as changes to the test. - reads-source ignores paths in comments. - census bounds weak_predicate at 64 levels and does not take a lookup with an operator before it as a round trip. - fixture-only treats a for-loop binding that shadows a fixture as unknown. - exact-pixel skips ratios and scaled values. - docs/development.md lists reads-source and never-run as failing rules. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 284 +++++++++++++++++++++++++++++++++++------ 2 files changed, 243 insertions(+), 43 deletions(-) diff --git a/docs/development.md b/docs/development.md index a1ceccaf59..7a6b8e04cf 100644 --- a/docs/development.md +++ b/docs/development.md @@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that no CI target builds because of a `cfg` on it or on a `mod` above it (`never-run`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index a5fc3e4bbc..bd00b6e833 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -240,6 +240,9 @@ pub struct Hit { /// only near `line`. pub first: usize, pub last: usize, + /// Other lines whose change counts as a change to the hit, by file: the `cfg` attributes that + /// turn a `never-run` test off, on its module or on a `mod` declaration in another file. + pub also: Vec<(String, usize, usize)>, } impl Hit { @@ -256,6 +259,18 @@ pub struct Ctx { pub helpers: HashMap>, pub ci_env: HashSet, pub module_cfgs: HashMap>, + /// Where the attributes of [`Ctx::module_cfgs`] are. + pub module_sites: HashMap>, +} + +/// [`Ctx::module_cfgs`] and [`Ctx::module_sites`] for `paths`. +fn module_ctx(paths: &[String], read: &dyn Fn(&str) -> Option) -> (HashMap>, HashMap>) { + let (mut cfgs, mut sites) = (HashMap::new(), HashMap::new()); + for (path, (preds, at)) in module_walk(paths, read) { + cfgs.insert(path.clone(), preds); + sites.insert(path, at); + } + (cfgs, sites) } /// A source file read from the work tree, or `None` when it is missing or larger than [`MAX_FILE`]. @@ -271,8 +286,8 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let files: Vec = repo.into_iter().filter(|p| is_scanned(p)).collect(); if opts.all { let sources = read_all(root, &files)?; - let module_cfgs = module_cfgs(&files, &|p| read_small(root, p)); - let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs }; + let (module_cfgs, module_sites) = module_ctx(&files, &|p| read_small(root, p)); + let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs, module_sites }; let hits: Vec = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); print!("{}", report(&hits, sources.len())); return Ok(()); @@ -283,18 +298,30 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let crates: BTreeSet = changed.keys().map(|p| crate_of(p)).chain([TESTKIT.to_owned()]).collect(); let helper_files: Vec = files.iter().filter(|p| crates.contains(&crate_of(p))).cloned().collect(); let present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); - let module_cfgs = module_cfgs(&present, &|p| read_small(root, p)); - let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; + // Every file whose module a changed `mod` declaration governs is linted too, so a `cfg` added to + // `mod child;` counts against the tests in `child.rs`. + let cache: std::cell::RefCell>> = Default::default(); + let read = |p: &str| cache.borrow_mut().entry(p.to_owned()).or_insert_with(|| read_small(root, p)).clone(); + let (module_cfgs, module_sites) = module_ctx(&files, &read); + let governed: Vec = module_sites + .iter() + .filter(|(p, sites)| !changed.contains_key(*p) && sites.iter().any(|(decl, _, _)| changed.contains_key(decl))) + .map(|(p, _)| p.clone()) + .collect(); + let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs, module_sites }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { for hit in lint_file(&path, &src, &ctx) { - if touches(&hit, changed.get(&path).and_then(Option::as_ref)) { + if touches_in(&hit, &changed) { counted.push(hit); } else { older += 1; } } } + for (path, src) in read_all(root, &governed)? { + counted.extend(lint_file(&path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && touches_in(h, &changed))); + } finish(&counted, older, present.len(), &base) } @@ -544,7 +571,14 @@ fn hunk_range(hunk: &str) -> Option<(usize, usize)> { /// Whether `hit` covers a changed line (`None`: the whole file is new). fn touches(hit: &Hit, changed: Option<&BTreeSet>) -> bool { - changed.is_none_or(|lines| lines.range(hit.first..=hit.last).next().is_some()) + let within = |lines: &BTreeSet, a: usize, b: usize| lines.range(a..=b).next().is_some(); + changed.is_none_or(|lines| within(lines, hit.first, hit.last) || hit.also.iter().any(|(p, a, b)| *p == hit.path && within(lines, *a, *b))) +} + +/// [`touches`] across files: the hit's own lines, or its [`Hit::also`] lines in any changed file. +fn touches_in(hit: &Hit, changed: &BTreeMap>>) -> bool { + let in_file = |p: &str, a: usize, b: usize| changed.get(p).is_some_and(|c| c.as_ref().is_none_or(|l| l.range(a..=b).next().is_some())); + changed.get(&hit.path).is_some_and(|c| touches(hit, c.as_ref())) || hit.also.iter().any(|(p, a, b)| in_file(p, *a, *b)) } // ---- What CI sets ---- @@ -1183,7 +1217,7 @@ struct File<'a> { impl File<'_> { fn hit(&self, at: usize, rule: Rule, test: &str, note: String) -> Hit { let line = self.lines.of(at); - Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line } + Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line, also: vec![] } } fn test_at(&self, pos: usize) -> &str { @@ -1586,12 +1620,21 @@ const ROUND_TRIP: &[&str] = &["parse", "from_str", "from_id", "from_name", "from /// Whether every operand of a (whitespace-free) condition or closure is a presence check alone. fn weak_predicate(pred: &str) -> bool { + weak_predicate_within(pred, 0) +} + +/// [`weak_predicate`] for at most 64 levels of nesting; deeper conditions are not judged, as in +/// [`census_condition`]. +fn weak_predicate_within(pred: &str, depth: usize) -> bool { + if depth > 64 { + return false; + } 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]); + return weak_predicate_within(&pred[1..pred.len() - 1], depth + 1); } if let Some(at) = boolean_split(pred) { - return weak_predicate(&pred[..at]) && weak_predicate(&pred[at + 2..]); + return weak_predicate_within(&pred[..at], depth + 1) && weak_predicate_within(&pred[at + 2..], depth + 1); } let pred = pred.trim_start_matches('!'); if let Some(list) = pred.strip_suffix(".len()>0") { @@ -1636,6 +1679,8 @@ fn round_trip_call(op: &str) -> bool { op.match_indices(&format!("{r}(")).any(|(at, _)| { let open = at + r.len(); !op.as_bytes()[..at].last().copied().is_some_and(is_ident) + // Only a path or receiver before the call: `offset + lookup(n)` is a derived value. + && !op[..at].contains(['+', '-', '*', '/', '%', '^', '|', '=', '!', ',', '&']) && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..])) }) }) @@ -2924,7 +2969,8 @@ fn reads_source_hits(file: &File) -> Vec { for at in words(m, word, 0, m.len()).into_iter().filter(|&at| in_regions(&file.regions, at)) { let open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; - let arg = norm(&file.src[open + 1..close]); + // Comments dropped, so `/* "src/lib.rs" */` beside a JSON path is not a hit. + let arg = file.src_norm((open + 1, close)); // An ordinary or raw string literal: `".rs"`, `r".rs"`, `r#"…/lib.rs"#`. let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); let literal = raw.unwrap_or(&arg); @@ -3111,6 +3157,26 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option in` binding of the name, whose block holds `before`, shadows the + // `let`: its value is unknown. + let found_at = match &found { + Some(Some((_, at))) => Some(*at), + _ => None, + }; + let shadows = |kw: &[u8], sep: &[u8]| { + words(body, kw, 0, before).into_iter().any(|at| { + let head = at + kw.len(); + let Some(open) = body[head..before].iter().position(|&c| c == b'{').map(|p| p + head) else { return false }; + let Some(split) = find(&body[..open], sep, head) else { return false }; + let pattern = &body[head..split]; + !words(pattern, name.as_bytes(), 0, pattern.len()).is_empty() + && matching(body, open).is_some_and(|close| open < before && before < close) + && found_at.is_none_or(|l| at > l) + }) + }; + if shadows(b"for", b" in ") { + return Some(None); + } found } @@ -3224,9 +3290,19 @@ fn cfg_value(p: &str, t: &Target) -> Option { } } +/// The text of a `cfg(…)` predicate without whitespace and comments; string literals keep their text. +fn cfg_text(src: &[u8]) -> String { + norm(&mask_parts(&String::from_utf8_lossy(src), true, false)) +} + +/// The 1-based line of a byte offset. +fn line_at(b: &[u8], at: usize) -> usize { + b[..at.min(b.len())].iter().filter(|&&c| c == b'\n').count() + 1 +} + /// The predicates of the `#[cfg(…)]` and `#![cfg(…)]` attributes whose item holds `pos`, each with -/// the offset of its attribute. `m` is the masked text of `src`. -fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { +/// the offsets of its attribute's `cfg` and closing `]`. `m` is the masked text of `src`. +fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { let mut out = vec![]; for at in words(m, b"cfg", 0, m.len()) { let before = m[..at].trim_ascii_end(); @@ -3255,76 +3331,133 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { }; if span.0 <= pos && pos <= span.1 { // The source text: masking blanks the string literals `target_os = "macos"` needs. - out.push((norm(&src[open + 1..close]), at)); + out.push((cfg_text(&src[open + 1..close]), at, end)); } } out } +/// A file that may declare a module, and the inline module it must be declared in, if any. +type Candidate = (String, Option); +/// The predicates on a `mod` declaration and the first and last line of each attribute. +type Declared = (Vec, Vec<(usize, usize)>); +/// A file that declares a module, whether it does so in an inline module, and what it declares. +type Owner = (String, bool, Declared); + /// The module name a file declares and the files that may declare it with `mod ;`, or `None` /// for a crate root (`lib.rs`, `main.rs`, `build.rs`, a file directly in `tests`, `benches` or -/// `examples`). -fn module_parent(path: &str) -> Option<(&str, Vec)> { +/// `examples`). A candidate that comes with a module name declares it inside that inline module +/// (`mod platform { mod child; }` in `src/lib.rs` for `src/platform/child.rs`); those come last. +fn module_parent(path: &str) -> Option<(&str, Vec)> { let (dir, file) = path.rsplit_once('/')?; let root_dir = ["/tests", "/benches", "/examples"].iter().any(|d| dir.ends_with(d)); if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") { return None; } let (name, parent) = if file == "mod.rs" { dir.rsplit_once('/').map(|(p, n)| (n, p))? } else { (file.strip_suffix(".rs")?, dir) }; - let mut candidates: Vec = ["mod.rs", "lib.rs", "main.rs"].iter().map(|f| format!("{parent}/{f}")).collect(); - candidates.push(format!("{parent}.rs")); + let files_of = |dir: &str| -> Vec { + let mut c: Vec = ["mod.rs", "lib.rs", "main.rs"].iter().map(|f| format!("{dir}/{f}")).collect(); + c.push(format!("{dir}.rs")); + c + }; + let mut candidates: Vec = files_of(parent).into_iter().map(|c| (c, None)).collect(); + if let Some((grand, inline)) = parent.rsplit_once('/') { + candidates.extend(files_of(grand).into_iter().map(|c| (c, Some(inline.to_owned())))); + } Some((name, candidates)) } /// The predicates of the `#[cfg(…)]` attributes on a `mod ;` declaration in `src` and on the /// items and file around it, or `None` when `src` declares no such module. +#[cfg(test)] fn declared_cfgs(src: &str, name: &str) -> Option> { + declared_cfg_spans(src, name, None).map(|(preds, _)| preds) +} + +/// [`declared_cfgs`] with the first and last line of each attribute. With `within`, only a +/// declaration inside the inline module of that name counts. +fn declared_cfg_spans(src: &str, name: &str, within: Option<&str>) -> Option { let m = mask(src); - let decl = words(&m, b"mod", 0, m.len()).into_iter().find(|&at| { + let named = |at: usize, word: &str, next: u8| { let start = skip_ws(&m, at + 3); let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); - &m[start..end] == name.as_bytes() && m.get(skip_ws(&m, end)) == Some(&b';') - })?; + (&m[start..end] == word.as_bytes() && m.get(skip_ws(&m, end)) == Some(&next)).then(|| skip_ws(&m, end)) + }; + let blocks: Option> = within.map(|w| { + words(&m, b"mod", 0, m.len()).into_iter().filter_map(|at| named(at, w, b'{').and_then(|o| matching(&m, o).map(|c| (o, c)))).collect() + }); + let decl = words(&m, b"mod", 0, m.len()) + .into_iter() + .find(|&at| named(at, name, b';').is_some() && blocks.as_ref().is_none_or(|bs| bs.iter().any(|&(o, c)| o < at && at < c)))?; let item = m[..decl].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - let mut out = vec![]; + let (mut preds, mut lines) = (vec![], vec![]); for at in words(&m, b"cfg", item, decl) { let open = skip_ws(&m, at + 3); let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); if let Some(close) = (attr && m.get(open) == Some(&b'(')).then(|| matching(&m, open)).flatten() { - out.push(norm(&src.as_bytes()[open + 1..close])); + preds.push(cfg_text(&src.as_bytes()[open + 1..close])); + lines.push((line_at(&m, at), line_at(&m, close))); } } - out.extend(cfgs_over(&m, src.as_bytes(), decl).into_iter().map(|(p, _)| p)); - Some(out) + for (p, at, end) in cfgs_over(&m, src.as_bytes(), decl) { + preds.push(p); + lines.push((line_at(&m, at), line_at(&m, end))); + } + Some((preds, lines)) } +/// Where a module's `cfg` attributes are: the declaring file and the attribute's first and last line. +pub type CfgSite = (String, usize, usize); + /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the -/// modules above it, read through `read`. -fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { +/// modules above it, read through `read`, with where those attributes are. When several files +/// declare a module (`lib.rs` and `main.rs`) with different attributes, the walk stops there and +/// the module's ownership is unknown. +fn module_walk(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap, Vec)> { let mut out = HashMap::new(); for path in paths { - let (mut preds, mut at) = (vec![], path.clone()); + let (mut preds, mut sites, mut at) = (vec![], vec![], path.clone()); for _ in 0..16 { let Some((name, candidates)) = module_parent(&at) else { break }; - let Some((parent, found)) = candidates.into_iter().find_map(|c| read(&c).and_then(|s| declared_cfgs(&s, name)).map(|f| (c, f))) else { - break; + let found: Vec = candidates + .into_iter() + .filter_map(|(c, within)| read(&c).and_then(|s| declared_cfg_spans(&s, name, within.as_deref())).map(|f| (c, within.is_some(), f))) + .collect(); + let direct = found.iter().any(|(_, inline, _)| !inline); + let owners: Vec<&Owner> = found.iter().filter(|(_, inline, _)| !inline || !direct).collect(); + let Some(first) = owners.first() else { break }; + let sorted = |p: &[String]| { + let mut p = p.to_vec(); + p.sort(); + p }; - preds.extend(found); - at = parent; + let base = sorted(&first.2.0); + if !owners.iter().all(|o| sorted(&o.2.0) == base) { + break; + } + preds.extend(first.2.0.iter().cloned()); + for o in &owners { + sites.extend(o.2.1.iter().map(|&(a, b)| (o.0.clone(), a, b))); + } + at = first.0.clone(); } if !preds.is_empty() { - out.insert(path.clone(), preds); + out.insert(path.clone(), (preds, sites)); } } out } +/// The predicates of [`module_walk`] alone. +#[cfg(test)] +fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { + module_walk(paths, read).into_iter().map(|(p, (preds, _))| (p, preds)).collect() +} + /// A test that a `cfg` compiles out on every target CI runs tests on. fn never_run(v: &View, ctx: &Ctx) -> Option { let local = cfgs_over(&v.file.m, v.file.src, v.t.fn_at); - // A change to an attribute that turns the test off counts as a change to the test. - let first_attr = local.iter().map(|&(_, at)| at).min(); - let mut preds: Vec = local.into_iter().map(|(p, _)| p).collect(); + let mut preds: Vec = local.iter().map(|(p, _, _)| p.clone()).collect(); preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned()); if preds.is_empty() { return None; @@ -3334,9 +3467,11 @@ fn never_run(v: &View, ctx: &Ctx) -> Option { if CI_TARGETS.iter().chain(windows).all(off) { let shown: Vec = preds.iter().filter(|p| p.as_str() != "test").map(|p| format!("cfg({p})")).collect(); let mut hit = v.whole(Rule::NeverRun, format!("{} leaves it out of every target CI tests on", shown.join(", "))); - if let Some(at) = first_attr { - hit.first = hit.first.min(v.file.lines.of(at)); - } + // A change to an attribute that turns the test off counts as a change to the test; the + // lines between that attribute and the test do not. + let lines = &v.file.lines; + hit.also.extend(local.iter().map(|&(_, at, end)| (v.file.path.to_owned(), lines.of(at), lines.of(end)))); + hit.also.extend(ctx.module_sites.get(v.file.path).into_iter().flatten().cloned()); return Some(hit); } None @@ -3366,6 +3501,10 @@ fn names_rect(op: &str) -> bool { if ["artboard", "doc", ".x0", ".y0", ".x1", ".y1", "obox"].iter().any(|w| op.contains(w)) { return false; } + // A ratio or a scaled value (`a.width() / b.width()`) is not a pixel size. + if op.trim_start_matches(['&', '*']).contains(['/', '*']) { + return false; + } let b = op.as_bytes(); let mut i = 0; while i < b.len() { @@ -3381,7 +3520,13 @@ fn names_rect(op: &str) -> bool { after = matching(b, after).map_or(b.len(), |c| c + 1); } let rest = &op[after..]; - if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.starts_with(p)) { + // The access must end the operand or a tuple or array item: `rect.width() / panel.width()` + // is a ratio, not a pixel size. + let ends = |r: &str| { + let r = r.strip_prefix(".x").or_else(|| r.strip_prefix(".y")).unwrap_or(r); + r.is_empty() || r.starts_with([',', ')', ']']) + }; + if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.strip_prefix(p).is_some_and(ends)) { return true; } } @@ -3525,6 +3670,18 @@ mod tests { assert_eq!(census(subsets), [], "subset adapters pick a few entries"); } + #[test] + fn census_skips_derived_lookups_and_deep_nesting() { + let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let offset = "#[test]\nfn t() {\n for n in COUNTS {\n assert_eq!(offset + lookup(n).unwrap(), n);\n }\n}\n"; + assert_eq!(census(offset), [], "an operator before the lookup derives a value"); + let qualified = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::parse(k.name()).unwrap(), k);\n }\n}\n"; + assert_eq!(census(qualified), [(2, "census")]); + let deep = + format!("#[test]\nfn t() {{\n for c in COLORS {{\n assert!({}c.is_some(){});\n }}\n}}\n", "(".repeat(66), ")".repeat(66)); + assert_eq!(census(&deep), [], "nesting deeper than the limit is not judged"); + } + #[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::>(); @@ -4954,7 +5111,7 @@ mod tests { let ne = "#[test]\nfn t() {\n assert_ne!(hash(a), hash(b));\n}\n"; assert_eq!(only("mirror", ne), [], "two inputs that must differ"); let allowed = - "#[test]\nfn t() {\n // test-lint: allow mirror both spellings parse to one value\n assert_eq!(parse(\"a\"), parse(\"A\"));\n}\n"; + "#[test]\nfn t() {\n // test-lint: allow mirror doubling is linear here\n assert_eq!(scale(p, 2.0), scale(p, 1.0) * 2.0);\n}\n"; assert_eq!(only("mirror", allowed), []); } @@ -4967,6 +5124,8 @@ mod tests { assert_eq!(only("fixture-only", fixture), [(2, "fixture-only")]); let result = "#[test]\nfn t() {\n let input = vec![1, 2, 3];\n let out = process(&input);\n assert_eq!(out.len(), 3);\n}\n"; assert_eq!(only("fixture-only", result), [], "the result of the code under test"); + let shadowed = "#[test]\nfn t() {\n let n = 1;\n for n in results() {\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", shadowed), [], "a loop binding that shadows the fixture"); let changed = "#[test]\nfn t() {\n let mut input = vec![1, 2, 3];\n process(&mut input);\n assert_eq!(input.len(), 3);\n}\n"; assert_eq!(only("fixture-only", changed), [], "a mutable local the code changes"); let borrowed = "#[test]\nfn t() {\n let input = &mut [3, 1];\n sort(input);\n assert_eq!(*input, [1, 3]);\n}\n"; @@ -5050,8 +5209,46 @@ mod tests { let src = "#[cfg(target_os = \"macos\")]\nmod mac {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; let found = lint_file("crates/x/src/tests.rs", src, &ctx()); let hit = found.iter().find(|h| h.rule == Rule::NeverRun).map(|h| (h.first, h.line)); - assert_eq!(hit, Some((1, 4))); - assert!(touches(found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(), Some(&[1].into_iter().collect())), "a change to the cfg alone"); + assert_eq!(hit, Some((3, 4))); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(touches(hit, Some(&[1].into_iter().collect())), "a change to the cfg alone"); + let helper = + "#[cfg(target_os = \"macos\")]\nmod mac {\n fn helper() {}\n\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", helper, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(!touches(hit, Some(&[3].into_iter().collect())), "a helper between the cfg and the test"); + let commented = "#[cfg(target_os = /* supported */ \"linux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", commented), [], "a comment inside the predicate"); + } + + #[test] + fn never_run_counts_a_changed_mod_declaration_in_another_file() { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod child;\n"), ("crates/x/src/child.rs", "")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); + let ctx = Ctx { module_cfgs, module_sites, ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let found = lint_file("crates/x/src/child.rs", test, &ctx); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + let changed = |lines: &[usize]| BTreeMap::from([("crates/x/src/lib.rs".to_owned(), Some(lines.iter().copied().collect()))]); + assert!(touches_in(hit, &changed(&[1])), "the cfg on the declaration changed"); + assert!(!touches_in(hit, &changed(&[2])), "only the declaration line changed"); + } + + #[test] + fn never_run_resolves_inline_parents_and_several_owners() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(windows)]\nmod platform {\n mod child;\n}\n#[cfg(target_os = \"macos\")]\nmod shared;\n"), + ("crates/x/src/main.rs", "mod shared;\n"), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let paths: Vec = ["crates/x/src/platform/child.rs", "crates/x/src/shared.rs"].into_iter().map(String::from).collect(); + let cfgs = module_cfgs(&paths, &read); + assert_eq!(cfgs.get("crates/x/src/platform/child.rs").map(Vec::as_slice), Some(&["windows".to_owned()][..])); + assert!(!cfgs.contains_key("crates/x/src/shared.rs"), "main.rs compiles it on every target"); } #[test] @@ -5063,6 +5260,7 @@ mod tests { assert_eq!(px("assert!(rect.width() == 120.0);"), [(4, "exact-pixel")]); assert_eq!(px("assert!(panel_rect.contains_rect(button_rect));"), [], "a relationship"); assert_eq!(px("assert!(rect.width() >= SPACING);"), []); + assert_eq!(px("assert_eq!(button_rect.width() / panel_rect.width(), 0.5);"), [], "a ratio"); assert_eq!(px("assert_eq!(rects.len(), 3);"), [], "a count"); assert_eq!(px("assert_eq!(correct, 3);"), [], "a word that only contains rect"); assert_eq!(px("assert_eq!(tabs_rect(&app).min.y, 0.0);"), [(4, "exact-pixel")], "a call that returns a rect"); @@ -5079,5 +5277,7 @@ mod tests { assert_eq!(only("reads-source", read), [(3, "reads-source")]); let data = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", data), []); + let commented = "#[test]\nfn t() {\n let s = fs::read_to_string(/* formerly \"src/lib.rs\" */ \"fixture.json\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", commented), [], "a path in a comment"); } } From 6441c1b95be15cb4d4e899d8c059d12575af89c9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:08:22 -0800 Subject: [PATCH 24/32] Tests: check exact values in panel and dialog tests Eleven assertions in the ui-egui Desaturate, Brush delete, Blend, Color Wheel, Color Balance, Remove Background and Document Info tests accepted halved, doubled or off-by-a-step values. Each now checks the value the test asks for. --- crates/ui-egui/src/addons/image/tests.rs | 3 +-- crates/ui-egui/src/dialogs/brush_delete/tests.rs | 3 ++- crates/ui-egui/src/dialogs/color_balance.rs | 4 ++-- crates/ui-egui/src/panels/doc_info.rs | 2 +- crates/ui-egui/src/panels/tests_blend.rs | 6 +++--- crates/ui-egui/src/panels/tests_color_wheel_hex.rs | 2 +- crates/ui-egui/src/panels/tests_color_wheel_opacity.rs | 4 ++-- crates/ui-egui/src/tests/plugins.rs | 6 ++++-- 8 files changed, 16 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/addons/image/tests.rs b/crates/ui-egui/src/addons/image/tests.rs index 154972dec7..3239ca6f00 100644 --- a/crates/ui-egui/src/addons/image/tests.rs +++ b/crates/ui-egui/src/addons/image/tests.rs @@ -248,6 +248,5 @@ fn properties_and_the_control_bar_remove_the_background_at_once() { assert!(closed(&app), "it runs at once"); assert_eq!(steps(&app), n + 1, "one undo step"); // The defaults (tolerance and softness 10): the white goes, the near-white ring fades. - let [corner, ring, block] = alphas(&app); - assert!(corner == 0 && ring > 0 && ring < 255 && block == 255, "{:?}", alphas(&app)); + assert_eq!(alphas(&app), [0, 95, 255]); } diff --git a/crates/ui-egui/src/dialogs/brush_delete/tests.rs b/crates/ui-egui/src/dialogs/brush_delete/tests.rs index b712b589d9..402a2b1922 100644 --- a/crates/ui-egui/src/dialogs/brush_delete/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_delete/tests.rs @@ -84,13 +84,14 @@ fn remove_strokes_runs_the_delete_and_cancel_changes_nothing() { let name = "10 pt. Oval"; app.run("brush.apply", json!({"name": name})).unwrap(); let before = app.session.active().unwrap().history.undo.len(); + let width = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap().width; ask(&mut app, json!({"name": name}), true); answer::(&mut app, choice, pump); assert_eq!(open_question(&app), None); assert_eq!(app.session.active().unwrap().history.undo.len(), before + usize::from(choice.is_some())); let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap(); assert_eq!(stroke.brush.as_deref(), choice.is_none().then_some(name)); - assert!(stroke.width > 0.0); + assert_eq!(stroke.width, width, "the stroke keeps its width"); } } diff --git a/crates/ui-egui/src/dialogs/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index 8c64b06a80..110c124717 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -437,8 +437,8 @@ mod tests { confirm(&mut app, &ctx); assert!(!app.session.in_interaction()); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); - let lighter = vectorcraft_color::Color::from_hex(&fill_hex(&app, id)).unwrap().to_rgb()[0]; - assert!(lighter > 0.6, "{lighter}"); + // #808080 holds less than 50% black, so taking 50% away leaves none. + assert_eq!(fill_hex(&app, id), "#ffffff"); } #[test] diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 5cb45f666a..13749667b9 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -950,7 +950,7 @@ mod tests { app.canvas.doc_info.clone().unwrap().1 }; let all = shown(&mut app, ""); - assert!(all["pathArea"].as_f64().is_some_and(|a| a > 0.0), "{}", all["pathArea"]); + assert!(all["pathArea"].as_f64().is_some_and(|a| (a - 200.0).abs() < 1e-6), "{}", all["pathArea"]); assert!(Arc::ptr_eq(&all, &shown(&mut app, "objects")), "Objects reuses All Categories' result"); for category in ["document", "fonts"] { let other = shown(&mut app, category); diff --git a/crates/ui-egui/src/panels/tests_blend.rs b/crates/ui-egui/src/panels/tests_blend.rs index 6aeaaeda67..1653488b5a 100644 --- a/crates/ui-egui/src/panels/tests_blend.rs +++ b/crates/ui-egui/src/panels/tests_blend.rs @@ -217,10 +217,10 @@ fn ramp_and_shift_edit_every_selected_blend_and_keep_their_other_options() { assert_eq!(undo_depth(&p.app()), depth + 1, "one undo step for both blends"); // The value typed goes to both; each keeps its own spacing, type and the other value. if name == "Ramp:" { - assert!(after_a.ease.ramp > 0.0 && after_a.ease.ramp == after_b.ease.ramp, "{after_a:?} {after_b:?}"); + assert!((after_a.ease.ramp - 0.75).abs() < 1e-9 && (after_b.ease.ramp - 0.75).abs() < 1e-9, "{after_a:?} {after_b:?}"); assert_eq!((after_a.color_shift, after_b.color_shift), (before_a.color_shift, before_b.color_shift)); } else { - assert!(after_a.color_shift > 0.0 && after_a.color_shift == after_b.color_shift, "{after_a:?} {after_b:?}"); + assert_eq!((after_a.color_shift, after_b.color_shift), (75.0, 75.0), "{after_a:?} {after_b:?}"); assert_eq!((after_a.ease.ramp, after_b.ease.ramp), (before_a.ease.ramp, before_b.ease.ramp)); } assert_eq!((after_a.spacing, after_b.spacing), (BlendSpacing::Steps(3), BlendSpacing::Distance(12.0))); @@ -238,7 +238,7 @@ fn ramp_is_dimmed_while_a_selected_blend_has_no_spine() { assert!(!p.enabled("Ramp:") && p.enabled("Shift:")); p.type_into("Shift:", "75"); let app = p.app(); - assert!(spec(&app, a).color_shift > 0.0 && spec(&app, b).color_shift == spec(&app, a).color_shift); + assert_eq!((spec(&app, a).color_shift, spec(&app, b).color_shift), (75.0, 75.0)); } #[test] diff --git a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs index e2c5a62b80..5c1920d8c4 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs @@ -452,7 +452,7 @@ fn an_opacity_click_in_one_frame_keeps_its_opacity_over_a_typed_alpha() { quick_click(&mut p, rail.rect.center()); let (hex, opacity) = first_stop(&p); assert_eq!(hex, "#336699", "the text applies"); - assert!(opacity > 0.2 && opacity < 0.8, "the press sets the opacity: {opacity}"); + assert!((opacity - 0.5).abs() < 0.005, "the press sets the opacity: {opacity}"); } /// A press on the opacity slider that takes the focus from an edited field applies the text and diff --git a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs index 507b8280e2..f3b5ca6a47 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs @@ -94,7 +94,7 @@ fn the_row_shows_under_the_box_view() { let at = along(&slider(&p), 0.5); p.fx.click_at(at).idle(2); let o = fill_opacity(&p.app()); - assert!((o - 0.5).abs() < 0.05, "{o}"); + assert!((o - 0.5).abs() < 0.005, "{o}"); } /// A value this build does not read keeps the rest of the preferences and reads as the default. @@ -122,7 +122,7 @@ fn the_slider_sets_the_fill_opacity_and_takes_the_arrow_keys() { let at = along(&slider(&p), 0.5); p.fx.click_at(at).idle(2); let o = fill_opacity(&p.app()); - assert!((o - 0.5).abs() < 0.05, "{o}"); + assert!((o - 0.5).abs() < 0.005, "{o}"); let labels = undo_labels(&p.app()); assert_eq!((labels.len(), labels.last().map(String::as_str)), (undo + 1, Some("Opacity"))); assert_eq!(crate::panels::current_paints(&p.app()).0.color().unwrap().to_hex(), "#ff0000"); diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 6dc9853a2a..351efaec28 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -215,8 +215,10 @@ fn filter_dialog_previews_and_commits_one_undo_step() { set_field(&mut h, "amount", json!(50)).unwrap(); step(&mut h); assert!(h.state().session.in_interaction(), "previewing"); - let [r, g, _] = fill_rgb(h.state(), id); - assert!(r < 1.0 && g > 0.0, "half desaturated on the canvas: {r} {g}"); + let [r, g, b] = fill_rgb(h.state(), id); + for (got, want) in [(r, 0.6063), (g, 0.1063), (b, 0.1063)] { + assert!((got - want).abs() < 1e-4, "half desaturated on the canvas: {r} {g} {b}"); + } step(&mut h); let (shown, _) = h.state().canvas.shown.as_ref().expect("a rendered canvas frame"); let shown_fill = shown.node(id).unwrap().appearance.fill_paint().color().unwrap().to_rgb_uncalibrated(); From edcad3c1832ab0eec35b5ea94d3195492c14f501 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:39:39 -0800 Subject: [PATCH 25/32] Tests: test-lint judges negations, cfg escapes and module declarations exactly - census keeps the polarity of a negation: `!parse(x).is_ok()` is a rejection, while `!xs.is_empty()` stays a presence check. - reads-source looks at the last path literal of a read_to_string argument, so `root.join("fixtures.rs").join("input.json")` is not a hit. - never-run reads an escaped cfg string value as unknown, takes every `mod` declaration of a module (`#[cfg(windows)]` and `#[cfg(unix)]` both count), and ties a change to an attribute only when that attribute excludes a CI target. - exact-pixel does not count a coordinate passed to a function. - docs/development.md says when never-run can decide a cfg. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 173 ++++++++++++++++++++++++++++++++++------- 2 files changed, 147 insertions(+), 28 deletions(-) diff --git a/docs/development.md b/docs/development.md index 7a6b8e04cf..4244e28738 100644 --- a/docs/development.md +++ b/docs/development.md @@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that no CI target builds because of a `cfg` on it or on a `mod` above it (`never-run`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` on it or on a `mod` above it excludes from every CI target that builds the crate (`never-run`). `never-run` reports a test only when it can evaluate the `cfg` on every such target; a predicate it does not evaluate, such as a `feature`, counts as unknown, so `#[cfg(all(feature = "gpu", not(feature = "gpu")))]` is not reported. It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index bd00b6e833..57b9cd41d0 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -305,7 +305,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let (module_cfgs, module_sites) = module_ctx(&files, &read); let governed: Vec = module_sites .iter() - .filter(|(p, sites)| !changed.contains_key(*p) && sites.iter().any(|(decl, _, _)| changed.contains_key(decl))) + .filter(|(p, sites)| !changed.contains_key(*p) && sites.iter().any(|(decl, _, _, _)| changed.contains_key(decl))) .map(|(p, _)| p.clone()) .collect(); let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs, module_sites }; @@ -1636,7 +1636,12 @@ fn weak_predicate_within(pred: &str, depth: usize) -> bool { if let Some(at) = boolean_split(pred) { return weak_predicate_within(&pred[..at], depth + 1) && weak_predicate_within(&pred[at + 2..], depth + 1); } - let pred = pred.trim_start_matches('!'); + let bare = pred.trim_start_matches('!'); + if (pred.len() - bare.len()) % 2 == 1 { + // A negated check is a presence check only for `!xs.is_empty()`; `!parse(x).is_ok()` asserts a rejection. + return bare.ends_with(".is_empty()") && !bare.contains(['=', '<', '>']); + } + let pred = bare; if let Some(list) = pred.strip_suffix(".len()>0") { return !list.contains(['=', '<', '>']); } @@ -2954,6 +2959,13 @@ fn sleep_hits(file: &File) -> Vec { .collect() } +/// The contents of the last string literal in `s`, without its quotes. +fn last_literal(s: &str) -> Option<&str> { + let close = s.rfind('"')?; + let open = s[..close].rfind('"')?; + Some(&s[open + 1..close]) +} + fn reads_source_hits(file: &File) -> Vec { if SOURCE_AUDITS.contains(&file.path) { return vec![]; @@ -2976,8 +2988,9 @@ fn reads_source_hits(file: &File) -> Vec { let literal = raw.unwrap_or(&arg); let rs = match word { b"ends_with" => literal == "\".rs\"", - // A path literal anywhere in the argument: `root.join("src/lib.rs")`, `concat!(…, "/x.rs")`. - b"read_to_string" => arg.contains(".rs\""), + // The last path literal in the argument: `root.join("src/lib.rs")`, `concat!(…, "/x.rs")`, but not + // `root.join("fixtures.rs").join("input.json")`. + b"read_to_string" => last_literal(&arg).is_some_and(|l| l.ends_with(".rs")), _ => arg.trim_end_matches('#').ends_with(".rs\""), }; if rs { @@ -3278,6 +3291,10 @@ fn cfg_value(p: &str, t: &Target) -> Option { } // An ordinary or raw string value: `"linux"`, `r"linux"`, `r#"linux"#`. let (key, value) = p.split_once('=').map_or((p, ""), |(k, v)| (k, v.strip_prefix('r').unwrap_or(v).trim_matches('#').trim_matches('"'))); + // An escape in an ordinary string (`"lin\x75x"`) is not decoded, so its value is unknown. + if p.split_once('=').is_some_and(|(_, v)| !v.starts_with('r') && v.contains('\\')) { + return None; + } match key { "test" => Some(true), "unix" => Some(t.family == "unix"), @@ -3339,8 +3356,9 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { /// A file that may declare a module, and the inline module it must be declared in, if any. type Candidate = (String, Option); -/// The predicates on a `mod` declaration and the first and last line of each attribute. -type Declared = (Vec, Vec<(usize, usize)>); +/// The predicates on a `mod` declaration and the first and last line of each attribute, with the +/// predicate that attribute contributes. +type Declared = (Vec, Vec<(usize, usize, String)>); /// A file that declares a module, whether it does so in an inline module, and what it declares. type Owner = (String, bool, Declared); @@ -3386,28 +3404,54 @@ fn declared_cfg_spans(src: &str, name: &str, within: Option<&str>) -> Option> = within.map(|w| { words(&m, b"mod", 0, m.len()).into_iter().filter_map(|at| named(at, w, b'{').and_then(|o| matching(&m, o).map(|c| (o, c)))).collect() }); - let decl = words(&m, b"mod", 0, m.len()) + let decls: Vec = words(&m, b"mod", 0, m.len()) .into_iter() - .find(|&at| named(at, name, b';').is_some() && blocks.as_ref().is_none_or(|bs| bs.iter().any(|&(o, c)| o < at && at < c)))?; - let item = m[..decl].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - let (mut preds, mut lines) = (vec![], vec![]); - for at in words(&m, b"cfg", item, decl) { - let open = skip_ws(&m, at + 3); - let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); - if let Some(close) = (attr && m.get(open) == Some(&b'(')).then(|| matching(&m, open)).flatten() { - preds.push(cfg_text(&src.as_bytes()[open + 1..close])); - lines.push((line_at(&m, at), line_at(&m, close))); - } + .filter(|&at| named(at, name, b';').is_some() && blocks.as_ref().is_none_or(|bs| bs.iter().any(|&(o, c)| o < at && at < c))) + .collect(); + let mut each = decls.iter().map(|&decl| decl_cfg_spans(&m, src, decl)); + let first = each.next()?; + let rest: Vec = each.collect(); + if rest.iter().all(|(p, _)| *p == first.0) { + let mut lines = first.1; + lines.extend(rest.into_iter().flat_map(|(_, l)| l)); + return Some((first.0, lines)); } - for (p, at, end) in cfgs_over(&m, src.as_bytes(), decl) { - preds.push(p); - lines.push((line_at(&m, at), line_at(&m, end))); + // Declarations under different `cfg`s (`#[cfg(windows)] mod child;` and `#[cfg(unix)] mod child;`): + // the module is compiled where any of them holds. + let (mut alts, mut spans) = (vec![], vec![]); + for (p, l) in std::iter::once(first).chain(rest) { + alts.push(format!("all({})", p.join(","))); + spans.extend(l.into_iter().map(|(a, b, _)| (a, b))); } - Some((preds, lines)) + let any = format!("any({})", alts.join(",")); + let lines = spans.into_iter().map(|(a, b)| (a, b, any.clone())).collect(); + Some((vec![any], lines)) } -/// Where a module's `cfg` attributes are: the declaring file and the attribute's first and last line. -pub type CfgSite = (String, usize, usize); +/// The predicates of the `#[cfg(…)]` attributes on the `mod` declaration at `decl` of masked `m` +/// and on the items and file around it, with the first and last line of each attribute. +fn decl_cfg_spans(m: &[u8], src: &str, decl: usize) -> Declared { + let item = m[..decl].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let (mut preds, mut lines) = (vec![], vec![]); + for at in words(m, b"cfg", item, decl) { + let open = skip_ws(m, at + 3); + let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + if let Some(close) = (attr && m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() { + let p = cfg_text(&src.as_bytes()[open + 1..close]); + lines.push((line_at(m, at), line_at(m, close), p.clone())); + preds.push(p); + } + } + for (p, at, end) in cfgs_over(m, src.as_bytes(), decl) { + lines.push((line_at(m, at), line_at(m, end), p.clone())); + preds.push(p); + } + (preds, lines) +} + +/// Where a module's `cfg` attributes are: the declaring file, the attribute's first and last line, +/// and its predicate. +pub type CfgSite = (String, usize, usize, String); /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the /// modules above it, read through `read`, with where those attributes are. When several files @@ -3437,7 +3481,7 @@ fn module_walk(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashM } preds.extend(first.2.0.iter().cloned()); for o in &owners { - sites.extend(o.2.1.iter().map(|&(a, b)| (o.0.clone(), a, b))); + sites.extend(o.2.1.iter().map(|(a, b, p)| (o.0.clone(), *a, *b, p.clone()))); } at = first.0.clone(); } @@ -3470,8 +3514,11 @@ fn never_run(v: &View, ctx: &Ctx) -> Option { // A change to an attribute that turns the test off counts as a change to the test; the // lines between that attribute and the test do not. let lines = &v.file.lines; - hit.also.extend(local.iter().map(|&(_, at, end)| (v.file.path.to_owned(), lines.of(at), lines.of(end)))); - hit.also.extend(ctx.module_sites.get(v.file.path).into_iter().flatten().cloned()); + // An attribute whose predicate holds on every target CI tests on (`unix` without Windows) + // does not turn the test off. + let excludes = |p: &str| !CI_TARGETS.iter().chain(windows).all(|t| cfg_value(p, t) == Some(true)); + hit.also.extend(local.iter().filter(|(p, _, _)| excludes(p)).map(|&(_, at, end)| (v.file.path.to_owned(), lines.of(at), lines.of(end)))); + hit.also.extend(ctx.module_sites.get(v.file.path).into_iter().flatten().filter(|s| excludes(&s.3)).map(|(f, a, b, _)| (f.clone(), *a, *b))); return Some(hit); } None @@ -3522,9 +3569,10 @@ fn names_rect(op: &str) -> bool { let rest = &op[after..]; // The access must end the operand or a tuple or array item: `rect.width() / panel.width()` // is a ratio, not a pixel size. + // A `)` must close a tuple group: in `column_for_x(rect.min.x)` it closes a call's arguments. let ends = |r: &str| { let r = r.strip_prefix(".x").or_else(|| r.strip_prefix(".y")).unwrap_or(r); - r.is_empty() || r.starts_with([',', ')', ']']) + r.is_empty() || r.starts_with([',', ']']) || (r.starts_with(')') && !closes_call(b, op.len() - r.len())) }; if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.strip_prefix(p).is_some_and(ends)) { return true; @@ -3535,6 +3583,22 @@ fn names_rect(op: &str) -> bool { false } +/// Whether the `)` at `close` ends the argument list of a call (`f(…)`, `f!(…)`, `x.f(…)`) rather +/// than a tuple or a parenthesized group. +fn closes_call(b: &[u8], close: usize) -> bool { + let mut depth = 0i32; + for i in (0..close).rev() { + match b[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' if depth > 0 => depth -= 1, + b'(' => return i > 0 && (is_ident(b[i - 1]) || b[i - 1] == b'!' || b[i - 1] == b'>'), + b'[' | b'{' => return false, + _ => {} + } + } + false +} + /// Whether a whitespace-free operand is only numbers, alone or in `pos2`, `vec2` or `Rect` builders. fn only_numbers(op: &str) -> bool { let mut rest = op.trim_start_matches('&').replace("egui::", "").replace("emath::", ""); @@ -5267,6 +5331,8 @@ mod tests { assert_eq!(px("assert_eq!(doc.artboards[1].rect.width(), 100.0);"), [], "document geometry in a UI test"); assert_eq!(px("assert_eq!((rect.x0, rect.y0), (200.0, 200.0));"), [], "document corners"); assert_eq!(px("assert_eq!(rgb8(&fill_color(&app, rect)), [255, 255, 255]);"), [], "a rect passed on"); + assert_eq!(px("assert_eq!(column_for_x(button_rect.min.x), 2);"), [], "a coordinate passed on"); + assert_eq!(px("assert_eq!((button_rect.min.x, button_rect.min.y), (1.0, 2.0));"), [(4, "exact-pixel")], "a tuple of coordinates"); let engine = "#[test]\nfn t() {\n assert_eq!(art_rect.width(), 10.0);\n}\n"; assert_eq!(only("exact-pixel", engine), [], "document geometry outside UI code"); } @@ -5279,5 +5345,58 @@ mod tests { assert_eq!(only("reads-source", data), []); let commented = "#[test]\nfn t() {\n let s = fs::read_to_string(/* formerly \"src/lib.rs\" */ \"fixture.json\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", commented), [], "a path in a comment"); + let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"input.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", dir), [], "a directory whose name ends in .rs"); + } + + #[test] + fn weak_predicates_keep_the_polarity_of_a_negation() { + assert!(weak_predicate("parse(input).is_ok()")); + assert!(weak_predicate("!xs.is_empty()")); + assert!(!weak_predicate("!parse(input).is_ok()"), "a rejection"); + assert!(!weak_predicate("!x.is_some()"), "an absence"); + assert!(weak_predicate("!!x.is_some()")); + } + + #[test] + fn never_run_reads_escaped_values_as_unknown() { + let escaped = "#[cfg(target_os = \"lin\\x75x\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", escaped), []); + } + + #[test] + fn never_run_takes_every_declaration_of_a_module() { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg(windows)]\nmod child;\n#[cfg(unix)]\nmod child;\n"), ("crates/x/src/child.rs", "")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); + let both = Ctx { module_cfgs, module_sites, ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in("crates/x/src/child.rs", test, &both), [], "the unix declaration builds it on Linux"); + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(windows)]\nmod child;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); + let windows = Ctx { module_cfgs, module_sites, ..ctx() }; + assert_eq!(hits_in("crates/x/src/child.rs", test, &windows), [(2, "never-run")]); + } + + #[test] + fn never_run_does_not_count_a_cfg_true_on_every_target() { + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(unix)]\nmod child;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); + let unix = Ctx { module_cfgs, module_sites, ..ctx() }; + let test = "#[cfg(target_os = \"macos\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let found = lint_file("crates/x/src/child.rs", test, &unix); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + let changed = BTreeMap::from([("crates/x/src/lib.rs".to_owned(), Some([1].into_iter().collect()))]); + assert!(!touches_in(hit, &changed), "cfg(unix) holds on Linux and FreeBSD"); + let files: HashMap<&str, &str> = [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod child;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); + let mac = Ctx { module_cfgs, module_sites, ..ctx() }; + let found = lint_file("crates/x/src/child.rs", test, &mac); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(touches_in(hit, &changed), "a macOS-only module cfg"); } } From 0b41498af652c2dc6a42eccfb67fe4f595f73abe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 03:06:35 -0800 Subject: [PATCH 26/32] Tests: test-lint reads format paths, nested mod declarations and call arguments exactly - reads-source checks the format string of a format!(...) path, so a format argument ending in .rs is not taken for the file name. - never-run combines only the mod declarations that load the same file; a declaration inside another inline module loads a file under that module's directory. - exact-pixel treats a comma inside a call's arguments like the closing parenthesis, so f(rect.min.x, 3) is a coordinate passed on. --- xtask/src/test_lint.rs | 57 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 49 insertions(+), 8 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 57b9cd41d0..55b90d8b4a 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2966,6 +2966,16 @@ fn last_literal(s: &str) -> Option<&str> { Some(&s[open + 1..close]) } +/// The literal that ends the path built by `arg`: the format string of a `format!(…)` call, since +/// its arguments fill placeholders inside it, otherwise the last string literal. +fn path_literal(arg: &str) -> Option<&str> { + let Some(at) = arg.find("format!(") else { return last_literal(arg) }; + let rest = &arg[at + "format!(".len()..]; + let open = rest.find('"')?; + let close = rest[open + 1..].find('"')? + open + 1; + Some(&rest[open + 1..close]) +} + fn reads_source_hits(file: &File) -> Vec { if SOURCE_AUDITS.contains(&file.path) { return vec![]; @@ -2989,8 +2999,8 @@ fn reads_source_hits(file: &File) -> Vec { let rs = match word { b"ends_with" => literal == "\".rs\"", // The last path literal in the argument: `root.join("src/lib.rs")`, `concat!(…, "/x.rs")`, but not - // `root.join("fixtures.rs").join("input.json")`. - b"read_to_string" => last_literal(&arg).is_some_and(|l| l.ends_with(".rs")), + // `root.join("fixtures.rs").join("input.json")` or `format!("{}/input.json", "fixtures.rs")`. + b"read_to_string" => path_literal(&arg).is_some_and(|l| l.ends_with(".rs")), _ => arg.trim_end_matches('#').ends_with(".rs\""), }; if rs { @@ -3404,9 +3414,29 @@ fn declared_cfg_spans(src: &str, name: &str, within: Option<&str>) -> Option> = within.map(|w| { words(&m, b"mod", 0, m.len()).into_iter().filter_map(|at| named(at, w, b'{').and_then(|o| matching(&m, o).map(|c| (o, c)))).collect() }); + // Every inline `mod { … }`: a declaration counts only when its innermost enclosing inline + // module is the one `within` names (or, without `within`, when it has none), since a declaration + // nested deeper loads a file under that other module's directory. + let inline: Vec<(usize, usize)> = words(&m, b"mod", 0, m.len()) + .into_iter() + .filter_map(|at| { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + let o = skip_ws(&m, end); + (end > start && m.get(o) == Some(&b'{')).then(|| matching(&m, o).map(|c| (o, c))).flatten() + }) + .collect(); + let innermost = |at: usize| inline.iter().filter(|&&(o, c)| o < at && at < c).max_by_key(|&&(o, _)| o).copied(); let decls: Vec = words(&m, b"mod", 0, m.len()) .into_iter() - .filter(|&at| named(at, name, b';').is_some() && blocks.as_ref().is_none_or(|bs| bs.iter().any(|&(o, c)| o < at && at < c))) + .filter(|&at| { + named(at, name, b';').is_some() + && match (&blocks, innermost(at)) { + (None, inner) => inner.is_none(), + (Some(bs), Some(inner)) => bs.contains(&inner), + (Some(_), None) => false, + } + }) .collect(); let mut each = decls.iter().map(|&decl| decl_cfg_spans(&m, src, decl)); let first = each.next()?; @@ -3569,10 +3599,11 @@ fn names_rect(op: &str) -> bool { let rest = &op[after..]; // The access must end the operand or a tuple or array item: `rect.width() / panel.width()` // is a ratio, not a pixel size. - // A `)` must close a tuple group: in `column_for_x(rect.min.x)` it closes a call's arguments. + // A `)` or `,` must belong to a tuple group: in `column_for_x(rect.min.x)` and + // `f(rect.min.x, 2)` it is part of a call's arguments. let ends = |r: &str| { let r = r.strip_prefix(".x").or_else(|| r.strip_prefix(".y")).unwrap_or(r); - r.is_empty() || r.starts_with([',', ']']) || (r.starts_with(')') && !closes_call(b, op.len() - r.len())) + r.is_empty() || r.starts_with(']') || (r.starts_with([')', ',']) && !closes_call(b, op.len() - r.len())) }; if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.strip_prefix(p).is_some_and(ends)) { return true; @@ -3583,8 +3614,8 @@ fn names_rect(op: &str) -> bool { false } -/// Whether the `)` at `close` ends the argument list of a call (`f(…)`, `f!(…)`, `x.f(…)`) rather -/// than a tuple or a parenthesized group. +/// Whether the `)` or `,` at `close` is in the argument list of a call (`f(…)`, `f!(…)`, `x.f(…)`) +/// rather than in a tuple or a parenthesized group. fn closes_call(b: &[u8], close: usize) -> bool { let mut depth = 0i32; for i in (0..close).rev() { @@ -5264,7 +5295,11 @@ mod tests { let inner = "#![cfg(target_os = \"macos\")]\nmod child;\n"; assert_eq!(declared_cfgs(inner, "child"), Some(vec!["target_os=\"macos\"".to_owned()])); let block = "#[cfg(windows)]\nmod platform {\n mod child;\n}\n"; - assert_eq!(declared_cfgs(block, "child"), Some(vec!["windows".to_owned()])); + assert_eq!(declared_cfg_spans(block, "child", Some("platform")).map(|(p, _)| p), Some(vec!["windows".to_owned()])); + assert_eq!(declared_cfgs(block, "child"), None, "the nested declaration loads platform/child.rs"); + let nested = "#[cfg(windows)]\nmod child;\nmod other {\n mod child;\n}\n"; + assert_eq!(declared_cfgs(nested, "child"), Some(vec!["windows".to_owned()]), "other/child.rs is another file"); + assert_eq!(declared_cfg_spans(nested, "child", Some("other")).map(|(p, _)| p), Some(vec![])); assert_eq!(declared_cfgs("mod child;\n", "child"), Some(vec![])); } @@ -5332,6 +5367,7 @@ mod tests { assert_eq!(px("assert_eq!((rect.x0, rect.y0), (200.0, 200.0));"), [], "document corners"); assert_eq!(px("assert_eq!(rgb8(&fill_color(&app, rect)), [255, 255, 255]);"), [], "a rect passed on"); assert_eq!(px("assert_eq!(column_for_x(button_rect.min.x), 2);"), [], "a coordinate passed on"); + assert_eq!(px("assert_eq!(cell_at(button_rect.min.x, 3), 2);"), [], "a coordinate passed on before another argument"); assert_eq!(px("assert_eq!((button_rect.min.x, button_rect.min.y), (1.0, 2.0));"), [(4, "exact-pixel")], "a tuple of coordinates"); let engine = "#[test]\nfn t() {\n assert_eq!(art_rect.width(), 10.0);\n}\n"; assert_eq!(only("exact-pixel", engine), [], "document geometry outside UI code"); @@ -5347,6 +5383,11 @@ mod tests { assert_eq!(only("reads-source", commented), [], "a path in a comment"); let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"input.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", dir), [], "a directory whose name ends in .rs"); + let formatted = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{}/input.json\", \"fixtures.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", formatted), [], "a format argument that ends in .rs"); + let formatted_rs = + "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{}/lib.rs\", dir)).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", formatted_rs), [(3, "reads-source")]); } #[test] From cefd2ed69ebc1c66fcbdc5e1b27249826a9943e3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 03:32:16 -0800 Subject: [PATCH 27/32] Tests: test-lint reads the path a join adds after a format call read_to_string(PathBuf::from(format!("{}/fixtures.rs", root)).join("input.json")) was reported as reading Rust source, and a join of "lib.rs" after a format call was missed. path_literal now takes a literal after the format call's closing parenthesis as the end of the path. --- xtask/src/test_lint.rs | 39 ++++++++++++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 55b90d8b4a..ebde101afe 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2966,14 +2966,39 @@ fn last_literal(s: &str) -> Option<&str> { Some(&s[open + 1..close]) } -/// The literal that ends the path built by `arg`: the format string of a `format!(…)` call, since -/// its arguments fill placeholders inside it, otherwise the last string literal. +/// The literal that ends the path built by `arg`: the format string of a `format!(…)` call that ends the path, since +/// its arguments fill placeholders inside it, otherwise the last string literal. A literal after the `format!(…)` +/// call (`PathBuf::from(format!(…)).join("lib.rs")`) ends the path instead. fn path_literal(arg: &str) -> Option<&str> { let Some(at) = arg.find("format!(") else { return last_literal(arg) }; let rest = &arg[at + "format!(".len()..]; - let open = rest.find('"')?; - let close = rest[open + 1..].find('"')? + open + 1; - Some(&rest[open + 1..close]) + let b = rest.as_bytes(); + let (mut depth, mut i, mut end) = (0usize, 0, None); + while i < b.len() { + match b[i] { + b'"' => { + i += 1; + while i < b.len() && b[i] != b'"' { + i += if b[i] == b'\\' { 2 } else { 1 }; + } + } + b'(' => depth += 1, + b')' if depth == 0 => { + end = Some(i); + break; + } + b')' => depth -= 1, + _ => {} + } + i += 1; + } + let call = &rest[..end.unwrap_or(rest.len())]; + if let Some(tail) = end.map(|e| &rest[e + 1..]).filter(|t| t.contains('"')) { + return path_literal(tail); + } + let open = call.find('"')?; + let close = call[open + 1..].find('"')? + open + 1; + Some(&call[open + 1..close]) } fn reads_source_hits(file: &File) -> Vec { @@ -5388,6 +5413,10 @@ mod tests { let formatted_rs = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{}/lib.rs\", dir)).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", formatted_rs), [(3, "reads-source")]); + let joined_json = "#[test]\nfn t() {\n let s = fs::read_to_string(PathBuf::from(format!(\"{}/fixtures.rs\", root)).join(\"input.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", joined_json), [], "a join after the format call ends the path"); + let joined_rs = "#[test]\nfn t() {\n let s = fs::read_to_string(PathBuf::from(format!(\"{}/fixtures\", root)).join(\"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", joined_rs), [(3, "reads-source")]); } #[test] From 408661218f87a3d95542151a727f146ec1fc99a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 04:05:40 -0800 Subject: [PATCH 28/32] Test lint: reads-source spans the path; cfg search skips later attributes A reads-source hit now runs through the call's closing parenthesis, so changing a path on a later line of a multiline call counts as a change to the hit. The never-run cfg search skips whole attributes after the cfg, so a `;` inside `#[test_case(1; "one")]` no longer drops the cfg. --- xtask/src/test_lint.rs | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index ebde101afe..4cc143a2d0 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -235,7 +235,7 @@ pub struct Hit { /// The first and last line of what the hit covers: the test, from its attribute to its closing /// brace, for a rule about a whole test or `all-unguarded`, through the second operand for /// `self-compare`, through the variable's name for `env-gate-unset`, through the attribute's - /// `]` for `ignore-without-reason`, else `line`. This span + /// `]` for `ignore-without-reason`, through the call's `)` for `reads-source`, else `line`. This span /// controls changed-line detection; `all-unguarded` and `self-compare` exemptions still apply /// only near `line`. pub first: usize, @@ -3029,7 +3029,10 @@ fn reads_source_hits(file: &File) -> Vec { _ => arg.trim_end_matches('#').ends_with(".rs\""), }; if rs { - out.push(file.hit(at, Rule::ReadsSource, file.test_at(at), note.into())); + // Through the call's `)`, so a change to a path on a later line is a change to the hit. + let mut hit = file.hit(at, Rule::ReadsSource, file.test_at(at), note.into()); + hit.last = file.lines.of(close); + out.push(hit); } } } @@ -3374,7 +3377,12 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { let enclosing = m[..at].iter().rposition(|&c| c == b'{'); enclosing.and_then(|o| matching(m, o).map(|c| (o, c))).unwrap_or((0, m.len())) } else { - let after = end + 1; + // Later attributes can hold `;` (`#[test_case(1; "one")]`); skip them whole, as `fn_after` does. + let mut after = end + 1; + while m[skip_ws(m, after)..].starts_with(b"#[") { + let Some(close) = matching(m, skip_ws(m, after) + 1) else { break }; + after = close + 1; + } let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; match (m[open], matching(m, open)) { (b'{', Some(close)) => (at, close), @@ -5289,6 +5297,16 @@ mod tests { assert_eq!(hits_in("crates/x/src/tests.rs", win, &ctx()), [(3, "never-run")]); let other = "#[cfg(target_os = \"macos\")]\nfn helper() {}\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(only("never-run", other), [], "a cfg on another item"); + let case = "#[cfg(windows)]\n#[test_case(1; \"one\")]\nfn t(n: usize) {\n assert_eq!(f(n), 2);\n}\n"; + assert_eq!(only("never-run", case), [(3, "never-run")], "a `;` inside a later attribute"); + } + + #[test] + fn reads_source_spans_reach_a_path_on_a_later_line() { + let src = "#[test]\nfn t() {\n let s = fs::read_to_string(\n root.join(\"src/lib.rs\"),\n )\n .unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + let found: Vec = lint_file("crates/x/src/tests.rs", src, &ctx()).into_iter().filter(|h| h.rule == Rule::ReadsSource).collect(); + assert_eq!(found.iter().map(|h| (h.line, h.first, h.last)).collect::>(), [(3, 3, 5)]); + assert!(touches(&found[0], Some(&[4].into_iter().collect())), "a change to the path alone"); } #[test] From c52314a75a9554e0de1ac4fdaca3f7d3c5593c55 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 04:11:45 -0800 Subject: [PATCH 29/32] Library panels: build browser rows once per library, not every frame A library panel rebuilt every browser row, with its tooltip and name index, on each frame, and the browser's memo key hashed every row each frame. With a swatch library of thousands of swatches, scrolling the thumbnail grid spent most of each frame on that work. The panel now keeps the rows it built for the library contents it shows and the UI language, and builds them again only when either changes. The memo key names that build instead of hashing the rows. Rows of panels that have closed are dropped when rows are next built. Pattern sources no longer copy every swatch name to find the few patterns. --- crates/ui-egui/src/panels/brushes.rs | 3 + crates/ui-egui/src/panels/graphic_styles.rs | 3 + crates/ui-egui/src/panels/library_panel.rs | 88 +++++++++++++++---- .../ui-egui/src/panels/library_panel/tests.rs | 24 +++++ .../ui-egui/src/panels/swatches/libraries.rs | 5 +- crates/ui-egui/src/panels/symbols.rs | 4 + 6 files changed, 109 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index d8075d4c66..aaccca637b 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -884,6 +884,9 @@ impl LibraryKind for BrushLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option { app.session.brush_libraries.path(id).map(str::to_string) } + fn same(a: &Self::Lib, b: &Self::Lib) -> bool { + Rc::ptr_eq(a, b) + } fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec> { lib.iter().map(|b| Row { name: b.name(), item: Some(b) }).collect() } diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index d9250ad7ee..e6668323a8 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -1004,6 +1004,9 @@ impl LibraryKind for GraphicStyleLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option { app.session.style_libraries.path(id).map(str::to_string) } + fn same(a: &Self::Lib, b: &Self::Lib) -> bool { + Arc::ptr_eq(a, b) + } fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec> { lib.iter().map(|s| Row { name: &s.style().name, item: Some(s) }).collect() } diff --git a/crates/ui-egui/src/panels/library_panel.rs b/crates/ui-egui/src/panels/library_panel.rs index e9fc506ec0..529671ccce 100644 --- a/crates/ui-egui/src/panels/library_panel.rs +++ b/crates/ui-egui/src/panels/library_panel.rs @@ -15,9 +15,11 @@ //! Library… (`ui.libraryPanel.locate`). The find text is the browser's; the selection is panel state //! (`UiState::library_selection`). +use std::any::Any; use std::borrow::Cow; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::collections::HashMap; +use std::rc::Rc; use craft::behavior::{IconId, Selection, SelectionModel}; use craft::host::PickRequest; @@ -25,9 +27,7 @@ use craft::theme::variant::Tone; use craft::ui::contract::{Bind, MemoKey, MemoProps, SelectMode, Show as _, ShowContainer as _, Trigger}; use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::notices::{Notice, NoticeAction, NoticeLayout}; -use craft::ui::patterns::presets::{ - PresetBrowser, PresetEvent, PresetFns, PresetKind, PresetRow, PresetRowMenu, PresetSource, PresetState, PresetView, -}; +use craft::ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFns, PresetRow, PresetRowMenu, PresetSource, PresetState, PresetView}; use craft::ui::primitives::{ContentPainterCx, IconSpec}; use craft::ui::runtime::access::PopupKind; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; @@ -122,7 +122,7 @@ pub(crate) trait LibraryKind { /// The view a panel shows until another is picked. const VIEW: View = View::MediumThumb; /// A library's contents, cheap to clone. - type Lib; + type Lib: Clone + 'static; type Item: Sync; /// What the thumbnails paint with besides each item (a panel setting, the documents a library's patterns come /// from); `()` for nothing. @@ -135,6 +135,9 @@ pub(crate) trait LibraryKind { fn find(app: &VectorcraftApp, key: &str) -> Found; /// The file library `id` was read from, if any. fn path(app: &VectorcraftApp, id: &str) -> Option; + /// Whether `a` and `b` are the same contents, not only equal ones: the panel reuses the browser rows it built for + /// `a` while [`get`](Self::get) returns `b`. + fn same(a: &Self::Lib, b: &Self::Lib) -> bool; /// The rows of library `id`; the browser's search filters what it shows (by the shown name and /// [`PresetRow::search_name`]). fn rows<'a>(lib: &'a Self::Lib, id: &str) -> Vec>; @@ -608,6 +611,7 @@ fn saved_view(view: PresetView, zoom: f64) -> View { /// The browser rows of library `id`'s `rows`, flat: a folder is a row of its own before its items, which a click /// selects as it selects an item (production's folder tiles neither opened nor closed). fn browser_rows(panel: &str, id: &str, rows: &[Row]) -> Vec> { + BUILDS.with(|n| n.set(n.get() + 1)); rows.iter() .map(|r| { let label = K::label(id, r.name); @@ -624,22 +628,73 @@ fn browser_rows(panel: &str, id: &str, rows: &[Row]) -> .collect() } +/// A library panel's browser rows, built for one library's contents in one UI language. +struct BuiltRows { + /// The contents the rows were built from, held so that [`LibraryKind::same`] does not match other contents + /// later stored at the same address. + lib: L, + lang: crate::i18n::Lang, + /// Different for every build, so the browser's memo key changes with the rows. + build: u64, + rows: Rc>>, + /// Each item row's position in [`LibraryKind::rows`], by stored name. + items: Rc>, +} + +thread_local! { + /// Each library panel's [`BuiltRows`], by panel id. + static BUILT_ROWS: RefCell>> = RefCell::new(HashMap::new()); + /// How many times [`browser_rows`] has run, for tests. + static BUILDS: Cell = const { Cell::new(0) }; +} + +/// How many times the panels have built browser rows on this thread. +#[cfg(test)] +pub(crate) fn row_builds() -> u64 { + BUILDS.with(Cell::get) +} + +/// [`BuiltRows::build`], [`BuiltRows::rows`] and [`BuiltRows::items`]. +type Built = (u64, Rc>>, Rc>); + +/// Panel `panel`'s browser rows of `lib`: the ones built before while the panel shows the same contents in the same +/// language, otherwise built now. Building drops the rows of the panels that are no longer open in `ui`. +fn built_rows(ui: &UiState, panel: &str, id: &str, lib: &K::Lib) -> Built { + let lang = crate::i18n::current(); + BUILT_ROWS.with(|cache| { + let mut cache = cache.borrow_mut(); + if let Some(b) = cache.get(panel).and_then(|b| b.downcast_ref::>()) + && b.lang == lang + && K::same(&b.lib, lib) + { + return (b.build, b.rows.clone(), b.items.clone()); + } + let flat = K::rows(lib, id); + let rows = Rc::new(browser_rows::(panel, id, &flat)); + let items = Rc::new(flat.iter().enumerate().filter(|(_, r)| r.item.is_some()).map(|(i, r)| (r.name.to_string(), i)).collect()); + let build = BUILDS.with(Cell::get); + let built = BuiltRows { lib: lib.clone(), lang, build, rows: rows.clone(), items: Rc::clone(&items) }; + cache.retain(|p, _| is_open(ui, p)); + cache.insert(panel.to_string(), Box::new(built)); + (build, rows, items) + }) +} + /// What a library's browser shows: its rows, the items their thumbnails paint and what those paint with. struct Shown<'a, K: LibraryKind> { + /// [`BuiltRows::build`] of `rows`. + build: u64, rows: &'a [PresetRow], - items: HashMap<&'a str, &'a K::Item>, + flat: &'a [Row<'a, K::Item>], + items: &'a HashMap, thumbs: K::Thumbs, } -/// By the rows (each names its library and item, whose look a library keeps) and what the thumbnails paint with. +/// By the build of the rows (each names its library and item, whose look a library keeps) and what the thumbnails +/// paint with. impl MemoProps for Shown<'_, K> { fn key(&self, key: &mut MemoKey) { - for row in self.rows { - row.key.key(key); - row.label.key(key); - row.depth.key(key); - (row.kind == PresetKind::Item).key(key); - } + self.build.key(key); self.rows.len().key(key); self.thumbs.key(key); } @@ -658,15 +713,14 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { }; let panel = panel_id(K::KIND, id); let (view, hide_find) = settings(&app.ui, K::KIND, id).map_or((K::VIEW, false), |s| (s.view.unwrap_or(K::VIEW), s.hide_find)); + let (build, rows, items) = built_rows::(&app.ui, &panel, id, &lib); let flat = K::rows(&lib, id); - let rows = browser_rows::(&panel, id, &flat); - let items = flat.iter().filter_map(|r| r.item.map(|i| (r.name, i))).collect(); let fns = PresetFns::new(|shown: &Shown<'_, K>, _| shown.rows.to_vec()).thumb(|shown, cx, rect, info| { - if let Some(item) = shown.items.get(info.key.name.as_str()) { + if let Some(item) = shown.items.get(info.key.name.as_str()).and_then(|&i| shown.flat.get(i)).and_then(|r| r.item) { K::thumb(&shown.thumbs, cx, rect, item); } }); - let source = PresetSource::new(Shown:: { rows: &rows, items, thumbs: K::thumbs(app, &lib) }, fns); + let source = PresetSource::new(Shown:: { build, rows: &rows, flat: &flat, items: &items, thumbs: K::thumbs(app, &lib) }, fns); let selection = selected(app, &panel); // The search text and the open groups are the browser's; the view is the panel's setting. let state_id = egui::Id::unique(("library-panel-state", &panel)); diff --git a/crates/ui-egui/src/panels/library_panel/tests.rs b/crates/ui-egui/src/panels/library_panel/tests.rs index a08ea664f8..679bd5f983 100644 --- a/crates/ui-egui/src/panels/library_panel/tests.rs +++ b/crates/ui-egui/src/panels/library_panel/tests.rs @@ -786,3 +786,27 @@ fn built_in_library_swatches_are_listed_in_the_ui_language() { assert!(app.session.doc().unwrap().doc.swatch("Clay 1").is_some(), "added under its own name"); crate::i18n::set_current(crate::i18n::Lang::EN); } + +/// A library panel builds its browser rows once for the library it shows, not on every frame, and builds them again +/// when the UI language changes the names it lists. +#[test] +fn library_panel_builds_its_rows_once_per_library_and_language() { + let mut app = app(); + let ctx = context(); + app.run("window.swatchLibrary", json!({"library": "earth-tones"})).unwrap(); + let panel = shown(&app); + app.run("ui.libraryPanel", json!({"panel": panel, "view": "smallList"})).unwrap(); + let draw = |app: &mut VectorcraftApp, ui: &mut Ui| show(app, ui, &panel); + let before = row_builds(); + for _ in 0..4 { + draw_frame(&mut app, &ctx, &draw, vec![]); + } + assert_eq!(row_builds() - before, 1, "four frames of an unchanged library build its rows once"); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").expect("fr registered")); + draw_frame(&mut app, &ctx, &draw, vec![]); + let out = draw_frame(&mut app, &ctx, &draw, vec![]); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(row_builds() - before, 2, "a new UI language builds the rows again, once"); + let painted = crate::tests_labels::shapes_text(&out); + assert!(painted.lines().any(|l| l == "Argile 1"), "the rebuilt rows are in the new language: {painted}"); +} diff --git a/crates/ui-egui/src/panels/swatches/libraries.rs b/crates/ui-egui/src/panels/swatches/libraries.rs index 4f16980b9a..c14d6cb040 100644 --- a/crates/ui-egui/src/panels/swatches/libraries.rs +++ b/crates/ui-egui/src/panels/swatches/libraries.rs @@ -106,6 +106,9 @@ impl LibraryKind for SwatchLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option { app.session.swatch_libraries.path(id).map(str::to_string) } + fn same(a: &Self::Lib, b: &Self::Lib) -> bool { + Arc::ptr_eq(a, b) + } /// Ungrouped swatches, then each colour group's folder and swatches, as in the Swatches panel; the browser's Find /// narrows them. fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec> { @@ -135,7 +138,7 @@ impl LibraryKind for SwatchLibraries { row } fn thumbs(app: &VectorcraftApp, lib: &Self::Lib) -> PatternSources { - PatternSources(lib.iter().filter_map(|w| Some((w.name.clone(), swatchlib::pattern_source(&app.session, w)?))).collect()) + PatternSources(lib.iter().filter_map(|w| swatchlib::pattern_source(&app.session, w).map(|d| (w.name.clone(), d))).collect()) } /// A pattern library's pattern, or a loaded library's, drawn from the library. fn thumb(sources: &PatternSources, cx: &ContentPainterCx<'_>, rect: Rect, w: &Swatch) { diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index e8dbf1a468..cfa24aadec 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -976,6 +976,10 @@ impl LibraryKind for SymbolLibraries { fn path(app: &VectorcraftApp, id: &str) -> Option { app.session.symbol_libraries.path(id).map(str::to_string) } + /// [`get`](LibraryKind::get) wraps the library anew each time: by the library the symbols are in. + fn same(a: &Self::Lib, b: &Self::Lib) -> bool { + a.len() == b.len() && a.first().zip(b.first()).is_none_or(|(a, b)| Arc::ptr_eq(&a.lib, &b.lib)) + } fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec> { lib.iter().map(|s| Row { name: s.name(), item: Some(s) }).collect() } From b26f833acf9e0a48cf51fbd3622b01255f310d8d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 04:37:05 -0800 Subject: [PATCH 30/32] 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 0326297ddf1a4d22f320c50050f9cd956f4fa3c1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 06:26:45 -0800 Subject: [PATCH 31/32] Tests: hold the clock still in the heavy filter shortcut test a_heavy_filter_plugin_runs_from_its_shortcut_as_from_its_menu_item read the wall clock. When more than 0.4 s passed between the frame that started the heavy run and the next one, the run's progress window opened and took the next key, so the filter with parameters did not open its dialog. On a loaded machine this failed some runs of the same tree. The test now sets the app's test clock to a fixed time, as the export_progress tests do, so the progress window stays closed however slowly the frames run. --- crates/ui-egui/src/shortcuts/tests.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index d22d8e9eb6..9b441b1f67 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1838,6 +1838,9 @@ fn a_heavy_filter_plugin_runs_from_its_shortcut_as_from_its_menu_item() { // the key is still running when Cancel stops it, however long the frames take. let jobs = std::sync::Arc::new(craft::host::ManualJobs::new()); app.host = std::sync::Arc::new(craft::host::Host::builder(app.host.app().clone()).i18n(crate::i18n::shared()).jobs(jobs).build()); + // The clock stands still: the run's progress window, which opens once the run is old enough + // and takes the keys, stays closed however slowly the frames run. + app.now_override = Some(0.0); app.session.allow_plugin_grants_from_requests(); app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); let (at_once, asks) = ("test.UI.heavy_filter-at-once", "test.UI.heavy_filter-asks"); From 6f4fd3e187a161075e61d14e01f659eb0b65985a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 06:59:58 -0800 Subject: [PATCH 32/32] 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()