From 9b8461feb590e6ebb348379083f0f292c1f9bba4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:26:20 -0800 Subject: [PATCH 01/18] Scripts: exportFile writes DXF with ExportOptionsAutoCAD - Document.exportFile with ExportType.AutoCAD takes an ExportOptionsAutoCAD object and writes a DXF file through document.export, adding .dxf unless the name ends with it. ExportType.AUTOCAD is the same value as ExportType.AutoCAD. - The options map to the DXF writer: version (AutoCADRelease13, 14, 15, 18, 21 and 24 as the R13, R14, 2000, 2004, 2007 and 2010 formats), unit, unitScaleRatio (drawing units for one unit, more than 0 and at most 1000), colors, rasterFormat, exportOption, alterPathsForAppearance, convertTextToOutlines, exportSelectedArtOnly and scaleLineweights. - An option the object leaves out takes the default the help page gives. colors, rasterFormat, unit and unitScaleRatio have none there and default to true colors, PNG, millimeters and 1. - AutoCADExportFileFormat.DWG, the help page's default, throws an error that says DWG is not available, and nothing is written. - New enumerations: AutoCADColors, AutoCADCompatibility, AutoCADExportFileFormat, AutoCADExportOption, AutoCADRasterFormat and AutoCADUnit. https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 4 +- crates/engine/src/script/dom/save_open.rs | 142 +++++++++++++++++++- crates/engine/src/tests/script_save_open.rs | 83 ++++++++++++ docs/mcp.md | 17 ++- docs/target-app-parity.md | 1 + 5 files changed, 238 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8e6c46e87d..01f4522700 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1808,7 +1808,9 @@ const ENUMS: &[(&str, &[&str])] = &[ /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { for (name, members) in ENUMS.iter().chain(save_open::ENUMS) { - let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + let mut items: Vec<_> = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + let aliases = save_open::ALIASES.iter().filter(|(e, _, _)| e == name); + items.extend(aliases.map(|(_, alias, m)| (alias.to_string(), HostItem::Value(text(format!("{name}.{m}")))))); realm.define_host_object(name, items)?; } let l = link; diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index f54c2f3f0b..e3227da608 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -7,7 +7,8 @@ //! , //! , //! , -//! and +//! , +//! and //! describe. //! //! Each method runs a command (`file.saveAs`, `document.export`, `document.open`) inside the run's @@ -25,6 +26,12 @@ //! one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. //! An SVG with `embedRasterImages` false also writes the document's embedded images beside it, //! and when one of those files may not be written, none of them is. +//! - `ExportType.AUTOCAD` is the same value as `ExportType.AutoCAD`. An AutoCAD export writes DXF +//! (`.dxf`) only: `AutoCADExportFileFormat.DWG`, the default, throws an error that says DWG is not +//! available. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page +//! gives; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to +//! true colors, PNG, millimeters and 1. `unitScaleRatio` is the number of drawing units for one +//! `unit`, more than 0 and at most 1000. //! - An option the classes here map is applied; a listed option that is not mapped is accepted at //! the default its help page gives and throws an error that says it is not available yet at any //! other value; a property the help pages do not list throws an error that names it, unless it is @@ -63,6 +70,15 @@ pub(in crate::script) struct State { /// The enumerations these members use, as `dom`'s are made. pub(super) const ENUMS: &[(&str, &[&str])] = &[ ("ExportType", &["AutoCAD", "FLASH", "GIF", "JPEG", "PNG24", "PNG8", "SVG", "TIFF"]), + ("AutoCADColors", &["Max8Colors", "Max16Colors", "Max256Colors", "TrueColors"]), + ( + "AutoCADCompatibility", + &["AutoCADRelease13", "AutoCADRelease18", "AutoCADRelease14", "AutoCADRelease21", "AutoCADRelease15", "AutoCADRelease24"], + ), + ("AutoCADExportFileFormat", &["DXF", "DWG"]), + ("AutoCADExportOption", &["PreserveAppearance", "MaximizeEditability"]), + ("AutoCADRasterFormat", &["PNG", "JPEG"]), + ("AutoCADUnit", &["Points", "Picas", "Inches", "Millimeters", "Centimeters", "Pixels"]), ( "Compatibility", &[ @@ -88,6 +104,10 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[ ("UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"]), ]; +/// Other names of enumeration members: `(enumeration, name, member)` makes `enumeration.name` the +/// same value as `enumeration.member`. +pub(super) const ALIASES: &[(&str, &str, &str)] = &[("ExportType", "AUTOCAD", "AutoCAD")]; + const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS"; const QUIET: &str = "UserInteractionLevel.DONTDISPLAYALERTS"; @@ -482,9 +502,118 @@ fn svg_starts() -> Vec<(&'static str, Data)> { ] } +/// The members of the enumeration `name` in [`ENUMS`]. +fn members_of(name: &str) -> &'static [&'static str] { + ENUMS.iter().find(|(n, _)| *n == name).map_or(&[][..], |(_, m)| *m) +} + +fn autocad_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("ExportOptionsAutoCAD.{name}"); + let pick = |enumeration: &str| member(d, enumeration, members_of(enumeration), &what); + match name { + "alterPathsForAppearance" => { + p.insert("alterPaths".into(), json!(boolean(d, &what)?)); + } + "colors" => { + let colors = match pick("AutoCADColors")? { + "Max8Colors" => json!(8), + "Max16Colors" => json!(16), + "Max256Colors" => json!(256), + _ => json!("true"), + }; + p.insert("colors".into(), colors); + } + "convertTextToOutlines" => { + p.insert("outlineText".into(), json!(boolean(d, &what)?)); + } + "exportFileFormat" => { + if pick("AutoCADExportFileFormat")? == "DWG" { + return Err(HostError::Error( + "AutoCADExportFileFormat.DWG is not available: set exportFileFormat to AutoCADExportFileFormat.DXF".into(), + )); + } + } + "exportOption" => { + let preserve = if pick("AutoCADExportOption")? == "PreserveAppearance" { "appearance" } else { "editability" }; + p.insert("preserve".into(), json!(preserve)); + } + "exportSelectedArtOnly" => { + p.insert("selectedOnly".into(), json!(boolean(d, &what)?)); + } + "rasterFormat" => { + p.insert("rasterFormat".into(), json!(if pick("AutoCADRasterFormat")? == "JPEG" { "jpeg" } else { "png" })); + } + "scaleLineweights" => { + p.insert("scaleLineweights".into(), json!(boolean(d, &what)?)); + } + "unit" => { + let unit = match pick("AutoCADUnit")? { + "Points" => "pt", + "Picas" => "pc", + "Inches" => "in", + "Millimeters" => "mm", + "Centimeters" => "cm", + _ => "px", + }; + p.insert("unit".into(), json!(unit)); + } + "unitScaleRatio" => { + let n = match d { + Data::Number(n) if n.is_finite() => *n, + _ => return Err(HostError::Type(format!("{what} must be a finite number"))), + }; + if !(n > 0.0 && n <= 1000.0) { + return Err(HostError::Range(format!("{what} must be more than 0 and at most 1000"))); + } + p.insert("scale".into(), json!(n)); + } + "version" => { + let version = match pick("AutoCADCompatibility")? { + "AutoCADRelease13" => "R13", + "AutoCADRelease14" => "R14", + "AutoCADRelease15" => "2000", + "AutoCADRelease18" => "2004", + "AutoCADRelease21" => "2007", + _ => "2010", + }; + p.insert("version".into(), json!(version)); + } + _ => return Ok(false), + } + Ok(true) +} + +fn autocad_starts() -> Vec<(&'static str, Data)> { + vec![ + ("alterPathsForAppearance", Data::Bool(false)), + ("convertTextToOutlines", Data::Bool(false)), + ("exportFileFormat", text("AutoCADExportFileFormat.DWG")), + ("exportOption", text("AutoCADExportOption.MaximizeEditability")), + ("exportSelectedArtOnly", Data::Bool(false)), + ("scaleLineweights", Data::Bool(false)), + ("version", text("AutoCADCompatibility.AutoCADRelease24")), + ] +} + +/// The options object `d` with the options of a new `class` object it leaves out, or holds as +/// `undefined`, added. +fn with_starts(class: &OptionClass, d: &Data) -> Data { + let Data::Object(items) = d else { return d.clone() }; + let mut items = items.clone(); + for (k, v) in (class.starts)() { + match items.iter_mut().find(|(n, _)| n == k) { + Some((_, held)) if matches!(held, Data::Undefined) => *held = v, + Some(_) => {} + None => items.push((k.to_string(), v)), + } + } + Data::Object(items) +} + const PNG24: OptionClass = OptionClass { name: "ExportOptionsPNG24", map: png24_map, kept: PNG24_KEPT, starts: png24_starts }; const JPEG: OptionClass = OptionClass { name: "ExportOptionsJPEG", map: jpeg_map, kept: JPEG_KEPT, starts: jpeg_starts }; const SVG: OptionClass = OptionClass { name: "ExportOptionsSVG", map: svg_map, kept: SVG_KEPT, starts: svg_starts }; +const AUTOCAD: OptionClass = OptionClass { name: "ExportOptionsAutoCAD", map: autocad_map, kept: &[], starts: autocad_starts }; /// An `ExportType`: the format `document.export` writes, the extensions a file name may already /// end with (the first is added), and its option class (`None`: no options are taken). @@ -495,9 +624,9 @@ struct ExportKind { } fn export_kind(d: &Data) -> std::result::Result { - let all = ENUMS.iter().find(|(n, _)| *n == "ExportType").map_or(&[][..], |(_, m)| *m); let raster = |format, extensions| ExportKind { format, extensions, options: None }; - Ok(match member(d, "ExportType", all, "exportType")? { + Ok(match member(d, "ExportType", members_of("ExportType"), "exportType")? { + "AutoCAD" => ExportKind { format: "dxf", extensions: &["dxf"], options: Some(&AUTOCAD) }, "PNG24" => ExportKind { format: "png", extensions: &["png"], options: Some(&PNG24) }, "JPEG" => ExportKind { format: "jpg", extensions: &["jpg", "jpeg"], options: Some(&JPEG) }, "SVG" => ExportKind { format: "svg", extensions: &["svg"], options: Some(&SVG) }, @@ -631,6 +760,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { None => Map::new(), }, Some(o) => match kind.options { + // An AutoCAD option left out takes its help page's default, not the DXF writer's. + Some(class) if class.name == AUTOCAD.name => options_params(class, &with_starts(class, o))?, Some(class) => options_params(class, o)?, None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))), }, @@ -642,7 +773,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into())); } // A raster file has one pixel per point at 100%, whatever the document's raster effects resolution. - if kind.format != "svg" { + // A DXF's `scale` is its drawing units per unit, from `unitScaleRatio`. + if !matches!(kind.format, "svg" | "dxf") { p.insert("scale".into(), json!(hs / 100.0)); } let format = if svgz { "svgz" } else { kind.format }; @@ -740,7 +872,7 @@ pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { /// The option classes: each `new Name()` gives a record with its `typename` and the defaults its /// help page gives for the options mapped here. pub(super) fn classes(link: &Link) -> Vec { - let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG]); + let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG, &AUTOCAD]); all.map(|c| { let l = link.clone(); let f: HostFunction = Rc::new(move |_: Vec| { diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 126c7c3947..9419b65f76 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -153,6 +153,60 @@ fn a_raster_export_at_100_percent_has_a_pixel_per_point() { let _ = std::fs::remove_dir_all(base); } +/// The value of the DXF header variable `name` (the group after its name). +fn dxf_header(dxf: &str, name: &str) -> Option { + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + lines.iter().position(|l| *l == name).and_then(|i| lines.get(i + 2)).map(|v| v.to_string()) +} + +/// The largest x coordinate (group code 10) in the entities of a DXF. +fn dxf_widest(dxf: &str) -> f64 { + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + // The section's name is a value; the group codes start on the line after it. + let start = lines.iter().position(|l| *l == "ENTITIES").map_or(0, |i| i + 1); + lines[start..].chunks(2).filter(|p| p.len() == 2 && p[0] == "10").filter_map(|p| p[1].parse::().ok()).fold(f64::MIN, f64::max) +} + +/// `exportFile` with `ExportType.AutoCAD` writes a DXF with the `ExportOptionsAutoCAD` options, and +/// DWG, the help page's default format, throws without writing a file. +#[test] +fn an_autocad_export_writes_a_dxf_with_its_options() { + let base = folder("autocad"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var o = new ExportOptionsAutoCAD(); vc.log([o.typename, o.exportFileFormat, o.version, ExportType.AUTOCAD === ExportType.AutoCAD]);\n\ + try {{ d.exportFile(new File(dir + '/w'), ExportType.AutoCAD, o); }} catch (e) {{ vc.log(String(e)); }}\n\ + o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease15;\n\ + o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 25.4; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\ + d.exportFile(new File(dir + '/a'), ExportType.AutoCAD, o);\n\ + o.unitScaleRatio = 1; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\ + var u = new ExportOptionsAutoCAD(); u.exportFileFormat = AutoCADExportFileFormat.DXF; u.version = undefined; d.exportFile(new File(dir + '/u'), ExportType.AutoCAD, u);\n\ + d.exportFile(new File(dir + '/c'), ExportType.AutoCAD, {{typename: 'ExportOptionsAutoCAD', exportFileFormat: AutoCADExportFileFormat.DXF, version: undefined}});" + ), + ); + assert_eq!(out[0], json!(["ExportOptionsAutoCAD", "AutoCADExportFileFormat.DWG", "AutoCADCompatibility.AutoCADRelease24", true])); + assert!(out[1].as_str().is_some_and(|e| e.contains("DWG is not available")), "{}", out[1]); + assert!(!dir.join("w.dxf").exists() && !dir.join("w.dwg").exists() && !dir.join("w").exists(), "DWG writes nothing"); + let a = std::fs::read_to_string(dir.join("a.dxf")).unwrap(); + let b = std::fs::read_to_string(dir.join("b.DXF")).unwrap(); + assert!(!dir.join("b.DXF.dxf").exists(), "a name that ends with the extension keeps it"); + assert_eq!(dxf_header(&a, "$ACADVER").as_deref(), Some("AC1015"), "AutoCADRelease15 is the 2000 format"); + assert_eq!(dxf_header(&b, "$INSUNITS").as_deref(), Some("1"), "inches, one drawing unit each"); + assert!(dxf_widest(&a) > dxf_widest(&b) * 20.0, "unitScaleRatio scales the drawing: {} and {}", dxf_widest(&a), dxf_widest(&b)); + for name in ["c.dxf", "u.dxf"] { + let dxf = std::fs::read_to_string(dir.join(name)).unwrap(); + assert_eq!(dxf_header(&dxf, "$ACADVER").as_deref(), Some("AC1024"), "{name}: an option left out or undefined is AutoCADRelease24"); + } + let _ = std::fs::remove_dir_all(base); +} + /// With `pDFPreset` named, the options left at a new object's defaults keep the preset's values, and /// an option the script changes applies over the preset. #[test] @@ -518,6 +572,35 @@ fn bad_arguments_are_refused_with_an_error() { "from 0 to 100", ), (format!("app.activeDocument.exportFile({f}, ExportType.GIF, {{}});"), "not available yet"), + (format!("app.activeDocument.exportFile({f}, ExportType.AutoCAD);"), "DWG is not available"), + ( + format!("var o = new ExportOptionsAutoCAD(); o.exportFileFormat = undefined; app.activeDocument.exportFile({f}, ExportType.AUTOCAD, o);"), + "DWG is not available", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScaleRatio = 2000; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "at most 1000", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = 'AutoCADCompatibility.AutoCADRelease99'; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "AutoCADCompatibility", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.colors = 256; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "AutoCADColors", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScale = 2; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "ExportOptionsAutoCAD has no option unitScale", + ), (format!("app.open({f}, 'RGB');"), "DocumentColorSpace"), (format!("app.open({f}, undefined, {{pageToOpen: 0}});"), "from 1"), (format!("app.open({f}, undefined, {{pDFCropToBox: 'art'}});"), "PDFBoxType"), diff --git a/docs/mcp.md b/docs/mcp.md index 5dd133dc00..8aeda63840 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2709,7 +2709,18 @@ app through the global object `vc`, and writes to the Script Console and runs ot with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, from 1 to 776.19; 100 writes one pixel per point whatever the raster effects resolution), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and `coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and - `includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s + `includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `AutoCAD` (also written + `ExportType.AUTOCAD`) takes `new ExportOptionsAutoCAD()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/) + and writes a DXF file, as `document.export {format: dxf}` does, with `exportFileFormat`, `version` + (`AutoCADRelease13`, `14`, `15`, `18`, `21` and `24` as the R13, R14, 2000, 2004, 2007 and 2010 formats), `unit`, + `unitScaleRatio` (the drawing units for one `unit`, more than 0 and at most 1000), `colors`, `rasterFormat`, + `exportOption`, `alterPathsForAppearance`, `convertTextToOutlines`, `exportSelectedArtOnly` and `scaleLineweights`. + An option the object leaves out takes its help page's default; `colors`, `rasterFormat`, `unit` and + `unitScaleRatio`, which have none there, default to true colors, PNG, millimeters and 1, VectorCraft's own values. + `AutoCADExportFileFormat.DWG`, the help page's default, throws an error that says DWG is not available, so an + AutoCAD export sets `exportFileFormat` to `AutoCADExportFileFormat.DXF`. The enumerations `AutoCADColors`, + `AutoCADCompatibility`, `AutoCADExportFileFormat`, `AutoCADExportOption`, `AutoCADRasterFormat` and `AutoCADUnit` + hold the members the scripting constants page lists. `app.open`'s `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with `pageToOpen` and `pDFCropToBox`. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, @@ -2722,11 +2733,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot files a command reads or writes besides the one named, such as an SVG's linked files, are read and written only where the script's folders allow. `userInteractionLevel` does not change what a command does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the - format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with + format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.dxf`, `.svgz` with `compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and when one of those files may not be written, none of them is. A listed option that is not mapped is accepted at its help page's default, and any other value throws - an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help + an error that says it is not available yet, as does `ExportType.FLASH`. A property the help pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and `parent`), and an `undefined` one is left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default keeps the preset's value. A bad value throws an error before anything is written. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 123604eaec..a407294012 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1027,6 +1027,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.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 52b43e90f08de968117463a91b376b69c18a9ac4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:57:46 -0800 Subject: [PATCH 02/18] Scripts: an AutoCAD export to a DXF before 2004 does not take true color AutoCADRelease13, 14 and 15 write DXF formats that hold no true color. With them, exportFile takes 256 indexed colors when the options leave colors out, and AutoCADColors.TrueColors throws an error instead of writing indexed colors without telling the script. Docs: docs/mcp.md. --- crates/engine/src/script/dom/save_open.rs | 13 +++++++++++++ crates/engine/src/tests/script_save_open.rs | 6 ++++++ docs/mcp.md | 2 ++ 3 files changed, 21 insertions(+) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index e3227da608..6382fabb54 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -766,6 +766,19 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))), }, }; + // A DXF version before 2004 holds no true color: with `colors` left out it takes 256 indexed + // colors, and `AutoCADColors.TrueColors` with it throws. + if kind.format == "dxf" && matches!(p.get("version").and_then(Value::as_str), Some("R13" | "R14" | "2000")) { + match p.get("colors") { + None => { + p.insert("colors".into(), json!(256)); + } + Some(c) if c.as_str() == Some("true") => { + return Err(HostError::Error("AutoCADColors.TrueColors needs AutoCADRelease18 or a later version".into())); + } + Some(_) => {} + } + } let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false); let clip = p.remove("_clip").and_then(|v| v.as_bool()).unwrap_or(false); let (hs, vs) = (p.remove("_h").and_then(|v| v.as_f64()).unwrap_or(100.0), p.remove("_v").and_then(|v| v.as_f64()).unwrap_or(100.0)); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 9419b65f76..fb304236ec 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -601,6 +601,12 @@ fn bad_arguments_are_refused_with_an_error() { ), "ExportOptionsAutoCAD has no option unitScale", ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease14; o.colors = AutoCADColors.TrueColors; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "TrueColors needs AutoCADRelease18", + ), (format!("app.open({f}, 'RGB');"), "DocumentColorSpace"), (format!("app.open({f}, undefined, {{pageToOpen: 0}});"), "from 1"), (format!("app.open({f}, undefined, {{pDFCropToBox: 'art'}});"), "PDFBoxType"), diff --git a/docs/mcp.md b/docs/mcp.md index 8aeda63840..06a97cf28e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2717,6 +2717,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `exportOption`, `alterPathsForAppearance`, `convertTextToOutlines`, `exportSelectedArtOnly` and `scaleLineweights`. An option the object leaves out takes its help page's default; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to true colors, PNG, millimeters and 1, VectorCraft's own values. + `AutoCADRelease13`, `14` and `15` hold no true color: with them `colors` defaults to `Max256Colors`, and + `AutoCADColors.TrueColors` throws an error. `AutoCADExportFileFormat.DWG`, the help page's default, throws an error that says DWG is not available, so an AutoCAD export sets `exportFileFormat` to `AutoCADExportFileFormat.DXF`. The enumerations `AutoCADColors`, `AutoCADCompatibility`, `AutoCADExportFileFormat`, `AutoCADExportOption`, `AutoCADRasterFormat` and `AutoCADUnit` From e654a3d5b99c695e2343a4523448496d7f35fed6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 19:42:05 -0800 Subject: [PATCH 03/18] Scripts: an AutoCAD export in picas writes a DXF ExportOptionsAutoCAD.unit = AutoCADUnit.Picas sent a unit name the DXF writer does not read, so exportFile threw instead of writing the file. Each AutoCADUnit member now goes to the writer by its unit's key. The test also checks that an export without artBoardClipping has its origin at the visible art's bounds. --- crates/engine/src/script/dom/save_open.rs | 15 ++++++------ crates/engine/src/tests/script_save_open.rs | 27 ++++++++++++++++++++- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 6382fabb54..cfd67ab0bb 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -48,6 +48,7 @@ use std::cell::Cell; use std::rc::Rc; use serde_json::{Map, Value, json}; +use vectorcraft_doc::Unit; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; use super::{ @@ -548,14 +549,14 @@ fn autocad_map(name: &str, d: &Data, p: &mut Map) -> std::result: } "unit" => { let unit = match pick("AutoCADUnit")? { - "Points" => "pt", - "Picas" => "pc", - "Inches" => "in", - "Millimeters" => "mm", - "Centimeters" => "cm", - _ => "px", + "Points" => Unit::Points, + "Picas" => Unit::Picas, + "Inches" => Unit::Inches, + "Millimeters" => Unit::Millimeters, + "Centimeters" => Unit::Centimeters, + _ => Unit::Pixels, }; - p.insert("unit".into(), json!(unit)); + p.insert("unit".into(), json!(unit.key())); } "unitScaleRatio" => { let n = match d { diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index fb304236ec..76b4d66c75 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -161,10 +161,30 @@ fn dxf_header(dxf: &str, name: &str) -> Option { /// The largest x coordinate (group code 10) in the entities of a DXF. fn dxf_widest(dxf: &str) -> f64 { + dxf_xs(dxf).into_iter().fold(f64::MIN, f64::max) +} + +/// The smallest x coordinate (group code 10) in the entities of a DXF. +fn dxf_leftmost(dxf: &str) -> f64 { + dxf_xs(dxf).into_iter().fold(f64::MAX, f64::min) +} + +/// The x coordinates (group code 10) of the polyline vertices in a DXF. A hatch's code 10 is its +/// elevation point, so hatches are left out. +fn dxf_xs(dxf: &str) -> Vec { let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); // The section's name is a value; the group codes start on the line after it. let start = lines.iter().position(|l| *l == "ENTITIES").map_or(0, |i| i + 1); - lines[start..].chunks(2).filter(|p| p.len() == 2 && p[0] == "10").filter_map(|p| p[1].parse::().ok()).fold(f64::MIN, f64::max) + let mut entity = ""; + let mut xs = Vec::new(); + for p in lines[start..].chunks(2).filter(|p| p.len() == 2) { + match p[0] { + "0" => entity = p[1], + "10" if entity == "LWPOLYLINE" => xs.extend(p[1].parse::().ok()), + _ => {} + } + } + xs } /// `exportFile` with `ExportType.AutoCAD` writes a DXF with the `ExportOptionsAutoCAD` options, and @@ -187,6 +207,7 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 25.4; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\ d.exportFile(new File(dir + '/a'), ExportType.AutoCAD, o);\n\ o.unitScaleRatio = 1; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\ + o.unit = AutoCADUnit.Picas; d.exportFile(new File(dir + '/p'), ExportType.AutoCAD, o);\n\ var u = new ExportOptionsAutoCAD(); u.exportFileFormat = AutoCADExportFileFormat.DXF; u.version = undefined; d.exportFile(new File(dir + '/u'), ExportType.AutoCAD, u);\n\ d.exportFile(new File(dir + '/c'), ExportType.AutoCAD, {{typename: 'ExportOptionsAutoCAD', exportFileFormat: AutoCADExportFileFormat.DXF, version: undefined}});" ), @@ -203,7 +224,11 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { for name in ["c.dxf", "u.dxf"] { let dxf = std::fs::read_to_string(dir.join(name)).unwrap(); assert_eq!(dxf_header(&dxf, "$ACADVER").as_deref(), Some("AC1024"), "{name}: an option left out or undefined is AutoCADRelease24"); + // The rectangle is 10 pt (3.5 mm) from the artboard's left edge. + assert!(dxf_leftmost(&dxf) < 1.0, "{name}: the origin is at the visible art's bounds: {}", dxf_leftmost(&dxf)); } + let p = std::fs::read_to_string(dir.join("p.dxf")).unwrap(); + assert!(dxf_widest(&p) > dxf_widest(&b) * 5.0, "a pica is a sixth of an inch: {} and {}", dxf_widest(&p), dxf_widest(&b)); let _ = std::fs::remove_dir_all(base); } From d2ae34dfca3e98304bd4c088535f642e710b6df0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:40:42 -0800 Subject: [PATCH 04/18] Tests: the host name check lists the AutoCAD export names The host adds ExportOptionsAutoCAD, the six AutoCAD enumerations and ExportType.AUTOCAD, and every_name_the_host_adds_has_a_row now finds a row for each. The AutoCAD export test checks that the DXF origin is within 1 mm of the art's left edge on either side of zero. --- crates/engine/src/tests/script_save_open.rs | 2 +- .../engine/tests/it/script_host_vs_scriptcheck.rs | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 81283c528a..5b36ffc5da 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -225,7 +225,7 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { let dxf = std::fs::read_to_string(dir.join(name)).unwrap(); assert_eq!(dxf_header(&dxf, "$ACADVER").as_deref(), Some("AC1024"), "{name}: an option left out or undefined is AutoCADRelease24"); // The rectangle is 10 pt (3.5 mm) from the artboard's left edge. - assert!(dxf_leftmost(&dxf) < 1.0, "{name}: the origin is at the visible art's bounds: {}", dxf_leftmost(&dxf)); + assert!(dxf_leftmost(&dxf).abs() < 1.0, "{name}: the origin is at the visible art's bounds: {}", dxf_leftmost(&dxf)); } let p = std::fs::read_to_string(dir.join("p.dxf")).unwrap(); assert!(dxf_widest(&p) > dxf_widest(&b) * 5.0, "a pica is a sixth of an inch: {} and {}", dxf_widest(&p), dxf_widest(&b)); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 5960d189de..7f6afcf448 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -142,6 +142,13 @@ const INSIDE: &[(&str, &str)] = &[ "Compatibility EPSPostScriptLevelEnum EPSPreview ExportType PDFBoxType PDFCompatibility PDFOverprint SaveOptions \ UserInteractionLevel", ), + ("", "AutoCADColors AutoCADCompatibility AutoCADExportFileFormat AutoCADExportOption AutoCADRasterFormat AutoCADUnit"), + ("AutoCADColors.", "Max16Colors Max256Colors Max8Colors TrueColors"), + ("AutoCADCompatibility.", "AutoCADRelease13 AutoCADRelease14 AutoCADRelease15 AutoCADRelease18 AutoCADRelease21 AutoCADRelease24"), + ("AutoCADExportFileFormat.", "DWG DXF"), + ("AutoCADExportOption.", "MaximizeEditability PreserveAppearance"), + ("AutoCADRasterFormat.", "JPEG PNG"), + ("AutoCADUnit.", "Centimeters Inches Millimeters Picas Pixels Points"), ( "Compatibility.", "ILLUSTRATOR10 ILLUSTRATOR11 ILLUSTRATOR12 ILLUSTRATOR13 ILLUSTRATOR14 ILLUSTRATOR15 ILLUSTRATOR16 ILLUSTRATOR17 \ @@ -149,7 +156,7 @@ const INSIDE: &[(&str, &str)] = &[ ), ("EPSPostScriptLevelEnum.", "LEVEL2 LEVEL3"), ("EPSPreview.", "BWTIFF COLORTIFF None TRANSPARENTCOLORTIFF"), - ("ExportType.", "AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"), + ("ExportType.", "AUTOCAD AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"), ("PDFBoxType.", "PDFARTBOX PDFBLEEDBOX PDFBOUNDINGBOX PDFCROPBOX PDFMEDIABOX PDFTRIMBOX"), ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), @@ -160,8 +167,8 @@ const INSIDE: &[(&str, &str)] = &[ /// The classes the host adds with nothing but a prototype and its constructor: the page item types /// and the save and export option classes. const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ - PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 \ - ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; + PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG \ + ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. From 11d20c346fcd0fc6bf239857233f079b598c6187 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:40:01 -0800 Subject: [PATCH 05/18] Scripts: refused saves call no writer, white matte, relative paths, checker reassignments - A save of several files whose file access refuses one returns that error without calling the writer for any file, and the check before the write no longer lists the paths as written. - ExportOptionsPNG24 and ExportOptionsJPEG accept matteColor at its default, white (red, green and blue 255); other colors still throw. - Document.path of a file saved under a relative name is the working folder the engine wrote the file in. - The script checker keeps reporting saveAs and exportFile on a variable holding the script's own object when a declaration follows a label, a function body assigns the variable, a member assignment writes a property of that name, code runs from text, or the script includes another file. - docs/mcp.md: saveAs to a .vctemplate file without options writes a template copy and leaves fullName and the saved state as they were. --- crates/engine/src/cmd/fileio/save.rs | 10 ++- crates/engine/src/file_access.rs | 10 ++- crates/engine/src/script/dom/save_open.rs | 23 +++++-- crates/engine/src/tests/script_save_open.rs | 35 +++++++++-- crates/scriptcheck/src/analyze.rs | 29 +++++++-- crates/scriptcheck/src/analyze/declared.rs | 67 +++++++++++++++++++-- crates/scriptcheck/src/tests.rs | 31 +++++++++- docs/mcp.md | 4 +- 8 files changed, 183 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index cf00d4194a..2234144f54 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1071,15 +1071,13 @@ impl SaveJob { return Ok(stopped); } // Every path is checked against the file access in force before the first file is - // written. A refused file goes to `write` first, which refuses it with the error the - // caller gives (naming the path as the caller does), so none of the files is written. + // written. The first refusal is the save's error, and `write` is not called for any of + // the files. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) + && let Some(e) = files.iter().find_map(|(p, _)| crate::file_access::check_write_unrecorded(p).err()) { - write(p, bytes)?; - // A writer that does not check the file access writes none of the others. - return Err(super::may_write(p).err().unwrap_or_else(|| crate::EngineError::Other(format!("file access denied: {p}")))); + return Err(crate::EngineError::Other(e)); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 5951df8a64..0dd95b7546 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -461,8 +461,7 @@ pub fn is_path_key(key: &str) -> bool { /// May `path` be written here? Always, without roots in force and outside a script's command /// ([`with_script_gate`]). pub fn check_write(path: &str) -> Result<(), String> { - current().map_or(Ok(()), |r| r.check(path, Access::Write))?; - check_gate(path, Access::Write)?; + check_write_unrecorded(path)?; WRITES.with(|w| { if let Some(paths) = w.borrow_mut().as_mut() && !paths.iter().any(|(p, _)| p == path) @@ -473,6 +472,13 @@ pub fn check_write(path: &str) -> Result<(), String> { Ok(()) } +/// [`check_write`] without adding `path` to the files a script run reports as written, for a +/// check made before anything is written. +pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> { + current().map_or(Ok(()), |r| r.check(path, Access::Write))?; + check_gate(path, Access::Write) +} + /// A file's modification time and length; `None` when there is no file at `path`. type Stamp = Option<(Option, u64)>; diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index a091d229f4..3f56e65b8e 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -141,6 +141,9 @@ enum Default { /// An enumerated value, by its enumeration and member (`("DownsampleMethod", "NODOWNSAMPLE")` for /// `DownsampleMethod.NODOWNSAMPLE`). Member(&'static str, &'static str), + /// White as an RGB color: an object whose `red`, `green` and `blue` are 255 (its `typename`, when + /// it has one, `RGBColor`). + White, /// The help page gives no default: any value throws. Unset, } @@ -152,6 +155,15 @@ impl Default { (Default::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9, (Default::Text(a), Data::String(b)) => a == b, (Default::Member(e, m), Data::String(b)) => b.split_once('.').is_some_and(|(be, bm)| be == e && bm == m), + (Default::White, Data::Object(items)) => { + let full = |c: &str| items.iter().any(|(k, v)| k == c && matches!(v, Data::Number(n) if (n - 255.0).abs() < 1e-9)); + let rgb = items.iter().all(|(k, v)| match k.as_str() { + "typename" => matches!(v, Data::String(s) if s == "RGBColor"), + "red" | "green" | "blue" => true, + _ => false, + }); + rgb && ["red", "green", "blue"].into_iter().all(full) + } _ => false, } } @@ -502,7 +514,7 @@ fn png24_map(name: &str, d: &Data, p: &mut Map) -> std::result::R raster_map("ExportOptionsPNG24", name, d, p) } -const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))]; +const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::White), ("saveAsHTML", Default::Bool(false))]; fn png24_starts() -> Vec<(&'static str, Data)> { vec![ @@ -530,7 +542,7 @@ fn jpeg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Re } const JPEG_KEPT: &[(&str, Default)] = - &[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))]; + &[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::White), ("saveAsHTML", Default::Bool(false))]; fn jpeg_starts() -> Vec<(&'static str, Data)> { vec![ @@ -1005,12 +1017,15 @@ fn doc_full_name(h: &Host, a: &[Data]) -> Answer { } /// `document.path`: a `Folder` for the folder of the document's file, or an empty string for a -/// document that has none. +/// document that has none. A file saved under a relative path, which the engine wrote in the +/// process's working folder, is in that folder. fn doc_path(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; let folder = super::with_doc(h, doc, |_, st| { Ok(shown_file(st)?.and_then(|p| { - let parent = std::path::Path::new(p).parent()?.to_string_lossy().into_owned(); + let p = std::path::Path::new(p); + let full = if p.is_relative() { std::env::current_dir().ok()?.join(p) } else { p.to_path_buf() }; + let parent = full.parent()?.to_string_lossy().into_owned(); (!parent.is_empty()).then_some(parent) })) })?; diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 5b36ffc5da..86a6e35807 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -110,13 +110,17 @@ fn omitted_options_are_a_new_options_objects_defaults() { d.exportFile(new File(dir + '/j2'), ExportType.JPEG, new ExportOptionsJPEG());\n\ d.exportFile(new File(dir + '/p1'), ExportType.PNG24);\n\ d.exportFile(new File(dir + '/p2'), ExportType.PNG24, new ExportOptionsPNG24());\n\ + var j3 = new ExportOptionsJPEG(); j3.matteColor = {{red: 255, green: 255, blue: 255}};\n\ + d.exportFile(new File(dir + '/j3'), ExportType.JPEG, j3);\n\ + var p3 = new ExportOptionsPNG24(); p3.matteColor = {{typename: 'RGBColor', red: 255, green: 255, blue: 255}};\n\ + d.exportFile(new File(dir + '/p3'), ExportType.PNG24, p3);\n\ d.exportFile(new File(dir + '/s1'), ExportType.SVG);\n\ d.exportFile(new File(dir + '/s2'), ExportType.SVG, new ExportOptionsSVG());\n\ d.saveAs(new File(dir + '/a1.pdf'));\n\ d.saveAs(new File(dir + '/a2.pdf'), new PDFSaveOptions());" ), ); - for (one, two) in [("j1.jpg", "j2.jpg"), ("p1.png", "p2.png"), ("s1.svg", "s2.svg")] { + for (one, two) in [("j1.jpg", "j2.jpg"), ("j1.jpg", "j3.jpg"), ("p1.png", "p2.png"), ("p1.png", "p3.png"), ("s1.svg", "s2.svg")] { assert!(std::fs::read(dir.join(one)).unwrap() == std::fs::read(dir.join(two)).unwrap(), "{one} and {two} differ"); } for name in ["a1.pdf", "a2.pdf"] { @@ -287,7 +291,7 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() { } /// When the writer a save is given does not check the file access itself, a save of several files -/// still writes none of them after the refused one. +/// whose last file is refused hands none of them to the writer, the refused one included. #[test] fn a_refused_file_stops_a_save_whose_writer_does_not_check() { use crate::cmd::fileio::{SaveMode, save_job, save_plan}; @@ -324,9 +328,10 @@ fn a_refused_file_stops_a_save_whose_writer_does_not_check() { Ok(()) }) }); - assert!(r.is_err(), "{r:?}"); + let e = r.unwrap_err().to_string(); let refused = refused.unwrap(); - assert_eq!(written, std::slice::from_ref(&refused), "only the refused file went to the writer"); + assert!(e.contains(DENIED) && e.contains(&refused), "{e}"); + assert!(written.is_empty(), "no file went to the writer: {written:?}"); let mut perms = std::fs::metadata(&refused).unwrap().permissions(); #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); @@ -583,6 +588,12 @@ fn bad_arguments_are_refused_with_an_error() { (format!("var o = new EPSSaveOptions(); o.postScript = 'LEVEL2'; app.activeDocument.saveAs({f}, o);"), "EPSPostScriptLevelEnum"), (format!("app.activeDocument.exportFile({f}, 'PNG24');"), "ExportType"), (format!("app.activeDocument.exportFile({f}, ExportType.FLASH);"), "is not available yet"), + ( + format!( + "var p = new ExportOptionsPNG24(); p.matteColor = {{red: 255, green: 0, blue: 255}}; app.activeDocument.exportFile({f}, ExportType.PNG24, p);" + ), + "ExportOptionsPNG24.matteColor is not available yet", + ), (format!("app.activeDocument.exportFile({f}, ExportType.PNG24, new ExportOptionsJPEG());"), "ExportOptionsPNG24"), ( format!( @@ -794,6 +805,22 @@ fn full_name_path_saved_and_close_follow_the_documents_file() { let _ = std::fs::remove_dir_all(base); } +/// A document whose file was saved under a relative name is in the working folder the file was +/// written in. +#[test] +fn path_of_a_file_saved_under_a_relative_name_is_the_working_folder() { + let base = folder("relative"); + let mut s = session(&base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.active_mut().unwrap().path = Some("drawing.svg".into()); + let out = logged(&mut s, &base, "var d = app.activeDocument; vc.log([d.path instanceof Folder, d.path === '' ? '' : d.path.fsName]);"); + let cwd = std::env::current_dir().unwrap(); + assert_eq!(out[0][0], json!(true), "{out}"); + let shown = PathBuf::from(out[0][1].as_str().unwrap()); + assert!(shown == cwd || std::fs::canonicalize(&shown).ok() == std::fs::canonicalize(&cwd).ok(), "{shown:?} is not {cwd:?}"); + let _ = std::fs::remove_dir_all(base); +} + /// A document without unsaved changes closes with `SaveOptions.SAVECHANGES` and with no argument. #[test] fn a_document_without_unsaved_changes_closes_with_any_save_options() { diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 8765501507..a4da181c75 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -56,6 +56,9 @@ pub(crate) struct Known { /// A file gives names values the analysis doesn't read ([`Declared::unsure`]): no object counts /// as a Folder object whatever the path names. pub unsure: bool, + /// The script includes another file ([`Declared::includes`]), whose code may give a file's + /// variables values the scan of that file does not read. + pub others: bool, } impl Known { @@ -70,6 +73,7 @@ impl Known { /// object only when both sides say so; otherwise it may hold a File object. pub fn add(&mut self, other: Known, entries: usize) { self.unsure |= other.unsure; + self.others |= other.others; for (name, chain) in other.bound { if self.bound.len() < entries || self.bound.contains_key(&name) { self.bound.entry(name).or_insert(chain); @@ -281,8 +285,8 @@ struct ObjectValue { /// key's whole value, a bit each ([`Analyzer::writers`]). bits: u8, /// It is the value of the first name a `var` statement declares, and the statement is directly - /// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do` or - /// a loop's parentheses: only then does the variable hold `bits` after it. + /// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do`, a + /// loop's parentheses or a label: only then does the variable hold `bits` after it. whole: bool, /// The bit of the method whose value is being read, and how far that value has been read. value: Option<(u8, Value)>, @@ -647,6 +651,8 @@ struct Analyzer<'s, 'a, 'l> { /// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver /// that is not such a variable. index_receiver: u8, + /// The script includes another file ([`Known::others`]): no variable joins [`Analyzer::writers`]. + others: bool, /// This file or what the scan started with gives names values the analysis doesn't read /// ([`Declared::unsure`]): no object counts as a Folder object whatever the path names. unsure: bool, @@ -727,6 +733,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { objects: vec![], closed: None, index_receiver: 0, + others: known.others || declared.includes, unsure: known.unsure || declared.unsure, own_names: HashSet::new(), scopes: vec![], @@ -1386,7 +1393,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let body = self.scopes.last().map_or(0, |s| s.depth); let starts = before.is_none() || [";", "{", "}"].iter().any(|p| is(before, p)) - || (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !word(before, "else") && !word(before, "do")); + || (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !is(before, ":") && !word(before, "else") && !word(before, "do")); let whole = word(declaration, "var") && starts && depth.checked_sub(1) == Some(body); if self.objects.len() < self.acc.limits.nesting { self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole, value: None }); @@ -1432,9 +1439,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// The variable of the [`ObjectValue::whole`] literal whose `}` the token before `t` was joins /// [`Analyzer::writers`] when `t` ends the value (`;`, `,` or a line break). It is read before `t` /// closes a function body, so a literal given to the body's own variable stays inside the body. + /// No variable joins when code the scan does not follow at that point may give it another value: + /// a function body that assigns its name ([`Declared::body_assigned`]), a member assignment of a + /// property of that name, which may be the global object's ([`Declared::rebound`]), code given as + /// text or a `with` statement ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) + && !self.unsure + && !self.others + && !self.declared.rebound.contains(&name) + && !self.declared.body_assigned.contains(name.as_str()) && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { self.writers.insert(name, bits); @@ -1734,7 +1749,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } // A variable that any assignment gave a value that may be a File object leaves as one. let folders = self.folders.iter().filter(|name| self.folder(name)).cloned().collect(); - let known = Known { bound: std::mem::take(&mut self.bound), files: std::mem::take(&mut self.files), folders, unsure: self.unsure }; + let known = Known { + bound: std::mem::take(&mut self.bound), + files: std::mem::take(&mut self.files), + folders, + unsure: self.unsure, + others: self.others, + }; (std::mem::take(&mut self.includes), module, known) } } diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index 48f071d2ac..f00a7240c9 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -1,8 +1,11 @@ //! The names declared, read before the analysis. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; -use super::{Acc, Brackets, Lexer, LineBreaks, Read, Sig, T, catalog, for_in, goes_on_after, goes_on_with, is, member_mark, unquote, word}; +use super::{ + Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, for_in, goes_on_after, goes_on_with, is, member_mark, + unquote, word, +}; /// The names that give variables values the analysis doesn't read: a `with` statement makes an /// object's properties stand for names in its body (ECMA-262 3rd edition, section 12.10), and `eval`, @@ -36,6 +39,14 @@ pub(crate) struct Declared<'s> { /// The property names a member assignment writes (`o.d = …`, `o['d'] = …`). The object may be /// the global object, so a variable of that name may get a value the analysis doesn't read. pub(super) rebound: HashSet, + /// The names a function body assigns by name (`d = …`, `d += …`, `d++`, `for (d in …)`) other than + /// in a `var` statement's declarations, unless a body around the assignment declared the name with + /// `var` before it. The function may run at any time after it is defined, + /// also before its body in the text when it is a declaration, so a variable of that name may lose + /// the value an assignment the analysis read gave it. + pub(super) body_assigned: HashSet<&'s str>, + /// The file has an `#include` line: the included file's code may give its variables values. + pub(super) includes: bool, /// The file gives names values the analysis doesn't read in other ways ([`UNREAD_BINDINGS`] or /// a `constructor` property used, a property read, called or assigned whose name in brackets is /// not one string or number literal, which may be a variable's name on the global object @@ -82,6 +93,9 @@ struct Declarations<'s, 'a, 'l> { assign: Option, /// The function bodies being read, the innermost last, up to [`crate::Limits::nesting`]. bodies: Vec>, + /// The names the bodies being read declare so far, each with the number of those bodies that + /// declare it. + declared_around: HashMap<&'s str, usize>, /// The bracket depth inside the outermost function body past that limit being read. The names /// declared inside it are not kept. untracked: Option, @@ -101,6 +115,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { var_depth: None, assign: None, bodies: vec![], + declared_around: HashMap::new(), untracked: None, keys: vec![], out: Declared::default(), @@ -109,7 +124,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { for t in lexer.by_ref() { match breaks.read(&t) { Read::Skip => {} - Read::Directive => d.directive(), + Read::Directive => d.directive(&t), Read::Token(sig) => d.token(sig), } } @@ -164,9 +179,41 @@ impl<'s> Declarations<'s, '_, '_> { if t.word("function") && !member_mark(h0) && !word(h0, "function") { self.function = Some(depth); } + if !self.bodies.is_empty() || self.untracked.is_some() { + self.body_assignment(&t, depth); + } self.h = [Some(t), h0, h1]; } + /// `t` inside a function body at bracket depth `depth`: the name it assigns, when it assigns one + /// by name outside a `var` statement's declarations, joins [`Declared::body_assigned`]. + fn body_assignment(&mut self, t: &Sig<'s>, depth: usize) { + let [h0, h1, _] = self.h; + let name = |s: Option>| s.filter(|s| s.kind == T::Ident).map(|s| s.text); + let declares = word(h1, "var") || (is(h1, ",") && self.var_depth == Some(depth)); + let assigned = if t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")) { + // `d = …`, `d += …` and `d++`, not `o.d = …` (a member: [`Declared::rebound`]) or `var d = …`. + name(h0).filter(|_| !member_mark(h1) && !(t.text == "=" && declares)) + } else if t.kind == T::Ident && (is(h0, "++") || is(h0, "--")) { + // `++d`. + Some(t.text) + } else if t.word("in") && (is(h1, "(") || word(h1, "var")) { + // `for (d in …)`. + name(h0) + } else { + None + }; + // A name a body around `t` has declared with `var` before it is that body's own. + let own = |name: &str| self.untracked.is_none() && self.declared_around.contains_key(name); + if let Some(name) = assigned.filter(|n| !own(n)) { + if self.out.body_assigned.contains(name) || self.acc.room(self.out.body_assigned.len()) { + self.out.body_assigned.insert(name); + } else { + self.out.unsure = true; + } + } + } + /// `t`, a token before the brackets are followed past it: notes in [`Declared::rebound`] and /// [`Declared::unsure`] the ways the file gives names values the analysis doesn't read. fn unread_binding(&mut self, t: &Sig<'s>) { @@ -261,6 +308,14 @@ impl<'s> Declarations<'s, '_, '_> { } while let Some(body) = self.bodies.pop_if(|b| depth < b.depth) { self.var_depth = body.var_depth; + for name in body.names { + if let Some(n) = self.declared_around.get_mut(name) { + *n = n.saturating_sub(1); + if *n == 0 { + self.declared_around.remove(name); + } + } + } } if self.untracked.is_some_and(|d| depth < d) { self.untracked = None; @@ -285,6 +340,7 @@ impl<'s> Declarations<'s, '_, '_> { if let Some(body) = self.bodies.last_mut() { if (var || body.depth == depth) && !body.names.contains(t.text) && self.acc.room(body.names.len()) { body.names.insert(t.text); + *self.declared_around.entry(t.text).or_insert(0) += 1; if let Some((_, names)) = self.out.bodies.get_mut(body.index) { names.push(t.text); } @@ -297,7 +353,10 @@ impl<'s> Declarations<'s, '_, '_> { /// A preprocessor line ends the statement before it, as in [`Analyzer::directive`]. Inside a /// property's name in brackets it hides the tokens before the name (`this[`, a line, `'eval']`), /// so the name may be any. - fn directive(&mut self) { + fn directive(&mut self, t: &Token<'s>) { + if directives::parse(t.text).known == Some("include") { + self.out.includes = true; + } if self.keys.iter().any(|k| k.member) { self.out.unsure = true; } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 1524d4d7ae..341ad3b3d0 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -615,7 +615,7 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { "a.saveAs(f); b['saveAs'](f); a.n = 1; a.n;\n", "a.saveAs = app.activeDocument.saveAs;\n", "b['saveAs'] = w;\n", - "c[k] = w;\n", + "c = app.activeDocument;\n", "delete d.saveAs;\n", "var h = e;\n", "use(g);\n", @@ -633,6 +633,9 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { "s.saveAs(f);\n", )); assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16, 18, 19, 21, 22][..])); + // A computed key may name any property, a variable's on the global object included. + let r = report("var f = new File(p);\nvar c = {saveAs: function () {}};\nc[k] = w;\nc.saveAs(f);\n"); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..])); } /// Only a `var` statement directly in a function body or the global code that gives its first name @@ -664,6 +667,32 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..])); } +/// A literal's `saveAs` stays the script's own only while no code the check does not follow may give +/// the variable another value: a declaration after a label, which `if` may skip, a function body that +/// assigns the variable (its own method's, or a declaration's that runs before its text), a member +/// assignment of a property of that name, which may be the global object's, code given as text and an +/// included file each leave the write reported. A function that declares its own variable of the name +/// leaves it the script's own. +#[test] +fn a_save_as_other_code_may_replace_writes_a_file() { + let cases: [(&str, &[usize]); 7] = [ + ("var f = new File(p);\nvar d = app.activeDocument;\nif (flag) label:\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[5]), + ( + "var f = new File(p);\nvar d = {\n saveAs: function () {},\n useDocument: function () {\n d = null;\n d = app.activeDocument;\n }\n};\nd.useDocument();\nd.saveAs(f);\n", + &[10], + ), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\nswap();\nd.saveAs(f);\nfunction swap() { d = app.activeDocument; }\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\nthis.d = app.activeDocument;\nd.saveAs(f);\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\neval(s);\nd.saveAs(f);\n", &[4]), + ("#include \"other.jsx\"\nvar f = new File(p);\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\nfunction g() { var d = app.activeDocument; d = 1; }\nd.saveAs(f);\n", &[]), + ]; + for (src, lines) in cases { + let r = report(src); + assert_eq!(feature(&r, "file.write").map_or(&[][..], |f| f.lines.as_slice()), lines, "{src}"); + } +} + /// A `saveAs` key's value is a method of the script's own only when the whole value is one function /// expression: a value that goes on after the function's body, and a literal inside another, leave /// `saveAs` writing the file. A literal given to a function body's own variable at the end of the body diff --git a/docs/mcp.md b/docs/mcp.md index 0c6a0bfcbe..902d38a355 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2895,7 +2895,9 @@ other files through `$`: strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, as described above. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. -- `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. +- `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. A save to a + `.vctemplate` file without options writes a template copy: the document keeps its file, its `fullName` and its + saved state. `Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is. `app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/). From 306c24c120e8e6f02d748d53007a9e6b94597009 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:05:06 -0800 Subject: [PATCH 06/18] Scripts: absolute paths for relative document files, save warnings in the console - Document.fullName of a file saved or opened under a relative path is the file in the process's working folder, as Document.path already was, and close with SaveOptions.SAVECHANGES saves it there. - saveAs, exportFile, app.open and close with SAVECHANGES write each warning their command gives to the Script Console, starting with the method's name. - The checker tests cover a with statement and an include between a literal and its call. --- crates/engine/src/script/dom/save_open.rs | 55 ++++++++++++++------- crates/engine/src/tests/script_save_open.rs | 35 +++++++++++-- crates/scriptcheck/src/tests.rs | 4 +- docs/mcp.md | 7 ++- 4 files changed, 76 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 3f56e65b8e..1eac9cd9cb 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -47,8 +47,8 @@ //! save of one artboard writes only the file at the path, holding that artboard. Without //! `saveMultipleArtboards` the range is not used, but a value that is not written as a range of //! artboard numbers throws. -//! - `Document.path` is a `Folder` for the folder of the document's file. A document that has no -//! file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. +//! - `Document.path` is a `Folder` for the folder of the document's file. A file saved or opened +//! under a relative path is in the process's working folder. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. //! `fullName` and `path` of a document whose file the automation read roots do not allow throw //! `Script file access denied`. Setting `Document.saved` runs `document.setSaved`. //! - `Document.close` with unsaved changes closes without them with @@ -71,8 +71,8 @@ use vectorcraft_doc::Unit; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; use super::{ - Answer, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, current, doc_ref, get, given, method, named, num, on_doc, - property, text, this_doc, whole, + Answer, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, command_value, current, doc_ref, get, given, method, named, num, + on_doc, property, text, this_doc, whole, }; /// The most a scale factor of an export takes, in percent. @@ -863,10 +863,20 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "saveAs", "file.saveAs", &Value::Object(p))))?; Ok(Data::Undefined) } +/// Runs command `id` as [`command`] does, and writes each warning its result gives to the console as +/// `method: warning`, as `addDocument` writes the warnings of `file.new`. +fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer { + let (data, value) = command_value(h, id, p)?; + for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::super::each_line(&format!("{method}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } + Ok(data) +} + /// `path` with the extension of `kind` added, unless its name already ends with one of them. fn with_extension(path: &str, kind: &ExportKind, svgz: bool) -> String { let extensions: &[&str] = if svgz { &["svgz"] } else { kind.extensions }; @@ -933,7 +943,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { let named = with_extension(path, &kind, svgz); let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportFile", "document.export", &Value::Object(p))))?; Ok(Data::Undefined) } @@ -979,7 +989,7 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { } let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); - let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?; + let r = exactly(h, || warned(h, "open", "document.open", &Value::Object(p)))?; let index = match &r { Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { ("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()), @@ -992,15 +1002,25 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { Ok(doc_ref(h, st.uid)) } -/// The document's file, `None` for a document that has none, or `Script file access denied` with -/// the document's name when the automation read roots do not allow the file to be named +/// A document's file as the engine reads and writes it: a relative path is in the process's working +/// folder. It stays as it is when the working folder is not known. +fn absolute(path: &str) -> String { + let p = std::path::Path::new(path); + match std::env::current_dir() { + Ok(cwd) if p.is_relative() => cwd.join(p).to_string_lossy().into_owned(), + _ => path.to_string(), + } +} + +/// The document's file ([`absolute`]), `None` for a document that has none, or `Script file access +/// denied` with the document's name when the automation read roots do not allow the file to be named /// ([`crate::file_access::check_read`]), as `app.getIsFileOpen` reads them. -fn shown_file(st: &crate::DocState) -> std::result::Result, HostError> { +fn shown_file(st: &crate::DocState) -> std::result::Result, HostError> { match st.path.as_deref() { Some(p) if crate::file_access::check_read(p).is_err() => { Err(HostError::Error(format!("{}: {}", super::super::files::ACCESS_DENIED, st.title()))) } - p => Ok(p), + p => Ok(p.map(absolute)), } } @@ -1010,22 +1030,19 @@ fn doc_full_name(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; super::with_doc(h, doc, |_, st| { Ok(match shown_file(st)? { - Some(p) => vectorcraft_js::file_ref(p), + Some(p) => vectorcraft_js::file_ref(&p), None => vectorcraft_js::file_ref(&st.title()), }) }) } /// `document.path`: a `Folder` for the folder of the document's file, or an empty string for a -/// document that has none. A file saved under a relative path, which the engine wrote in the -/// process's working folder, is in that folder. +/// document that has none. fn doc_path(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; let folder = super::with_doc(h, doc, |_, st| { Ok(shown_file(st)?.and_then(|p| { - let p = std::path::Path::new(p); - let full = if p.is_relative() { std::env::current_dir().ok()?.join(p) } else { p.to_path_buf() }; - let parent = full.parent()?.to_string_lossy().into_owned(); + let parent = std::path::Path::new(&p).parent()?.to_string_lossy().into_owned(); (!parent.is_empty()).then_some(parent) })) })?; @@ -1077,12 +1094,12 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { match how { "DONOTSAVECHANGES" => {} "SAVECHANGES" => { - let path = file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?; + let path = absolute(&file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?); // A refusal names the document, as `fullName` does when the read roots hide its file. let name = super::with_doc(h, doc, |_, st| st.title()); let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?; let p = json!({"path": plain(real), "format": format}); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &p)))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "close", "file.saveAs", &p)))?; } _ => return Err(HostError::Error(UNSAVED_CHANGES.into())), } diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 86a6e35807..f0ba05bb6e 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -813,11 +813,40 @@ fn path_of_a_file_saved_under_a_relative_name_is_the_working_folder() { let mut s = session(&base); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); s.active_mut().unwrap().path = Some("drawing.svg".into()); - let out = logged(&mut s, &base, "var d = app.activeDocument; vc.log([d.path instanceof Folder, d.path === '' ? '' : d.path.fsName]);"); + let out = logged( + &mut s, + &base, + "var d = app.activeDocument; vc.log([d.path instanceof Folder, d.path === '' ? '' : d.path.fsName, d.fullName.fsName]);", + ); let cwd = std::env::current_dir().unwrap(); assert_eq!(out[0][0], json!(true), "{out}"); - let shown = PathBuf::from(out[0][1].as_str().unwrap()); - assert!(shown == cwd || std::fs::canonicalize(&shown).ok() == std::fs::canonicalize(&cwd).ok(), "{shown:?} is not {cwd:?}"); + let same = |shown: &str, want: &Path| { + let shown = PathBuf::from(shown); + shown == want || std::fs::canonicalize(&shown).ok().zip(std::fs::canonicalize(want).ok()).is_some_and(|(a, b)| a == b) + }; + assert!(same(out[0][1].as_str().unwrap(), &cwd), "{out} is not in {cwd:?}"); + let file = out[0][2].as_str().unwrap(); + assert!(Path::new(file).is_absolute() && Path::new(file).file_name() == Some("drawing.svg".as_ref()), "{file}"); + assert!(same(&Path::new(file).parent().unwrap().to_string_lossy(), &cwd), "{file} is not in {cwd:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// The warnings a save gives, such as editing data left out of a PDF of one artboard of several, go +/// to the Script Console. +#[test] +fn a_saves_warnings_go_to_the_console() { + let base = folder("warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + let save = format!( + "Folder.userData; var o = new PDFSaveOptions(); o.preserveEditability = true; o.artboardRange = '1';\n\ + app.activeDocument.saveAs(new File({}), o);", + quoted(&dir.join("one.pdf")) + ); + let r = run(&mut s, &base, &save).unwrap(); + let lines = r["console"]["lines"].as_array().unwrap(); + assert!(lines.iter().any(|l| l.as_str().is_some_and(|l| l.starts_with("saveAs: "))), "{lines:?}"); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 341ad3b3d0..fa8d8eecbc 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -675,7 +675,7 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { /// leaves it the script's own. #[test] fn a_save_as_other_code_may_replace_writes_a_file() { - let cases: [(&str, &[usize]); 7] = [ + let cases: [(&str, &[usize]); 9] = [ ("var f = new File(p);\nvar d = app.activeDocument;\nif (flag) label:\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[5]), ( "var f = new File(p);\nvar d = {\n saveAs: function () {},\n useDocument: function () {\n d = null;\n d = app.activeDocument;\n }\n};\nd.useDocument();\nd.saveAs(f);\n", @@ -685,6 +685,8 @@ fn a_save_as_other_code_may_replace_writes_a_file() { ("var f = new File(p);\nvar d = {saveAs: function () {}};\nthis.d = app.activeDocument;\nd.saveAs(f);\n", &[4]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\neval(s);\nd.saveAs(f);\n", &[4]), ("#include \"other.jsx\"\nvar f = new File(p);\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\n#include \"other.jsx\"\nd.saveAs(f);\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\nwith ({d: app.activeDocument}) {\n d.saveAs(f);\n}\n", &[4]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\nfunction g() { var d = app.activeDocument; d = 1; }\nd.saveAs(f);\n", &[]), ]; for (src, lines) in cases { diff --git a/docs/mcp.md b/docs/mcp.md index 902d38a355..809caffb8a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2897,7 +2897,9 @@ other files through `$`: themselves, such as a path's fill, are not defined yet and read as `undefined`. - `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. A save to a `.vctemplate` file without options writes a template copy: the document keeps its file, its `fullName` and its - saved state. + saved state. Each warning the command gives, here and for `exportFile`, `app.open` and `close` with + `SaveOptions.SAVECHANGES`, goes to the Script Console as a line that starts with the method's name, such as + `saveAs: `. `Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is. `app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/). @@ -2964,7 +2966,8 @@ other files through `$`: writes only the file at the path, holding that artboard. Without `saveMultipleArtboards`, a `.ai` or EPS `artboardRange` is not checked against the document's artboards, but one that is not written as a range of artboard numbers (such as `abc` or `0-`) throws. `Document.path` is a `Folder` for the folder of the document's - file. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of + file. A file saved or opened under a relative path is in the working folder of the process that wrote or read it, + for `fullName`, `path` and `close` alike. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. `fullName` and `path` of a document whose file the automation read roots do not allow throw `Script file access denied`. Setting `saved` runs `document.setSaved`: `true` records the document as saved without saving it, so `close()` then closes it, and `false` records it as having unsaved changes; neither adds an From c58763daf6cfb7d7def224487c6e5af4dd8afb29 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:39:33 -0800 Subject: [PATCH 07/18] Save: a refused file of a save without a path is named by its file name A save of several files that the file access refuses before anything is written gave the refused file's full path in its error, also when the client did not give the path and the folder is outside the read roots. The check before the write now names the file as the writer did, so document.save with separateArtboards keeps the folder out of the error. --- crates/engine/src/cmd/fileio/save.rs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 2234144f54..d3b7fd62b8 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -602,6 +602,9 @@ pub struct SaveJob { stamped: Option, /// The artboards also saved to files of their own (`separateArtboards`). boards: Vec, + /// The client did not give the path: a file the file access refuses before anything is + /// written is named as [`super::access::naming_in_error`] names it ([`SaveJob::naming_refusals`]). + hides_paths: bool, } /// Writes the file at a path with what the filler it is given writes into it @@ -963,7 +966,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option Self { + self.hides_paths = true; + self + } + /// The document when the job was made (what counts as saved once the file is written). pub(crate) fn snapshot(&self) -> &Arc { &self.snapshot @@ -1075,9 +1086,10 @@ impl SaveJob { // the files. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some(e) = files.iter().find_map(|(p, _)| crate::file_access::check_write_unrecorded(p).err()) + && let Some((p, e)) = files.iter().find_map(|(p, _)| crate::file_access::check_write_unrecorded(p).err().map(|e| (p, e))) { - return Err(crate::EngineError::Other(e)); + let e = crate::EngineError::Other(e); + return Err(if self.hides_paths { super::access::naming_in_error(e, p) } else { e }); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { @@ -1239,9 +1251,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8]) /// A save command: plan, then write with the file system (a native file as it is encoded). pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result { let plan = save_plan(s, mode, p)?; - let job = save_job(s, plan)?; - let uid = s.doc()?.uid; let given = str_param(p, "path").is_some_and(|g| !g.is_empty()); + let job = save_job(s, plan)?; + let job = if given { job } else { job.naming_refusals() }; + let uid = s.doc()?.uid; // Without a path, the files written are the document's own file and those beside it. let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) }) From b086db0fbbf171d330f76b3618c112cd411fa129 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:49:55 -0800 Subject: [PATCH 08/18] Script check: a function that sets saveAs or exportFile keeps the write reported A function declared before an object literal could replace the literal's saveAs or exportFile method when it ran later, and the check still treated the method as the script's own and left the write out of filesWritten. When any function body assigns a property of that name, no variable's method of that name counts as the script's own. --- crates/scriptcheck/src/analyze.rs | 7 +++++-- crates/scriptcheck/src/analyze/declared.rs | 8 ++++++++ crates/scriptcheck/src/tests.rs | 18 ++++++++++++++---- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index a4da181c75..fbcc62ae0a 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -1441,8 +1441,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// closes a function body, so a literal given to the body's own variable stays inside the body. /// No variable joins when code the scan does not follow at that point may give it another value: /// a function body that assigns its name ([`Declared::body_assigned`]), a member assignment of a - /// property of that name, which may be the global object's ([`Declared::rebound`]), code given as - /// text or a `with` statement ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). + /// property of that name, which may be the global object's ([`Declared::rebound`]), a function + /// body that assigns a `saveAs` or `exportFile` property of any object + /// ([`Declared::body_writer_assigned`]), code given as text or a `with` statement + /// ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) @@ -1450,6 +1452,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { && !self.others && !self.declared.rebound.contains(&name) && !self.declared.body_assigned.contains(name.as_str()) + && !self.declared.body_writer_assigned && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { self.writers.insert(name, bits); diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index f00a7240c9..c03efdd819 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -45,6 +45,11 @@ pub(crate) struct Declared<'s> { /// also before its body in the text when it is a declaration, so a variable of that name may lose /// the value an assignment the analysis read gave it. pub(super) body_assigned: HashSet<&'s str>, + /// A function body assigns a property named as one of [`catalog::DOM_FILE_WRITES`] + /// (`o.saveAs = …`, `this['exportFile'] = …`). The function may run at any time after it is + /// defined, and the object may be any variable's, so no variable's method of that name stays + /// the script's own. + pub(super) body_writer_assigned: bool, /// The file has an `#include` line: the included file's code may give its variables values. pub(super) includes: bool, /// The file gives names values the analysis doesn't read in other ways ([`UNREAD_BINDINGS`] or @@ -245,6 +250,9 @@ impl<'s> Declarations<'s, '_, '_> { None }; if let Some(name) = property { + if (!self.bodies.is_empty() || self.untracked.is_some()) && catalog::DOM_FILE_WRITES.contains(&name.as_str()) { + self.out.body_writer_assigned = true; + } if self.out.rebound.contains(&name) || self.acc.room(self.out.rebound.len()) { self.out.rebound.insert(name); } else { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index fa8d8eecbc..1b931a2cca 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -670,12 +670,13 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { /// A literal's `saveAs` stays the script's own only while no code the check does not follow may give /// the variable another value: a declaration after a label, which `if` may skip, a function body that /// assigns the variable (its own method's, or a declaration's that runs before its text), a member -/// assignment of a property of that name, which may be the global object's, code given as text and an -/// included file each leave the write reported. A function that declares its own variable of the name -/// leaves it the script's own. +/// assignment of a property of that name, which may be the global object's, a function body that +/// assigns a `saveAs` or `exportFile` property of any object, code given as text, a `with` statement +/// and an included file each leave the write reported. A function that declares its own variable of the +/// name, or assigns another property of it, leaves it the script's own. #[test] fn a_save_as_other_code_may_replace_writes_a_file() { - let cases: [(&str, &[usize]); 9] = [ + let cases: [(&str, &[usize]); 12] = [ ("var f = new File(p);\nvar d = app.activeDocument;\nif (flag) label:\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[5]), ( "var f = new File(p);\nvar d = {\n saveAs: function () {},\n useDocument: function () {\n d = null;\n d = app.activeDocument;\n }\n};\nd.useDocument();\nd.saveAs(f);\n", @@ -687,6 +688,15 @@ fn a_save_as_other_code_may_replace_writes_a_file() { ("#include \"other.jsx\"\nvar f = new File(p);\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[4]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\n#include \"other.jsx\"\nd.saveAs(f);\n", &[4]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\nwith ({d: app.activeDocument}) {\n d.saveAs(f);\n}\n", &[4]), + ( + "var f = new File(p);\nfunction replace() { d.saveAs = app.activeDocument.saveAs; }\nvar d = {saveAs: function () {}};\nreplace();\nd.saveAs(f);\n", + &[5], + ), + ( + "var f = new File(p);\nfunction replace(o) { o['exportFile'] = w; }\nvar d = {exportFile: function () {}};\nreplace(d);\nd.exportFile(f);\n", + &[5], + ), + ("var f = new File(p);\nfunction note() { d.n = 1; }\nvar d = {saveAs: function () {}};\nnote();\nd.saveAs(f);\n", &[]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\nfunction g() { var d = app.activeDocument; d = 1; }\nd.saveAs(f);\n", &[]), ]; for (src, lines) in cases { From e46f697d50e43f82b375ea5f3de97ad38fedad8a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 06:10:24 -0800 Subject: [PATCH 09/18] Script check: a nested function that assigns an outer body's variable keeps the write reported A function body's assignment was left out of the names other code may change when any enclosing body had declared the name with var. A nested function such as swap() { d = app.activeDocument; } called before d.saveAs(f) then left d trusted as the script's own literal, and the write went unreported. Only a name the innermost body declared now counts as that body's own; plain, compound, increment and for-in assignments to an outer body's variable all keep the write reported. --- crates/scriptcheck/src/analyze/declared.rs | 21 +++++---------------- crates/scriptcheck/src/tests.rs | 21 +++++++++++++++++++-- 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index c03efdd819..85d1f7eb9c 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -1,6 +1,6 @@ //! The names declared, read before the analysis. -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use super::{ Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, for_in, goes_on_after, goes_on_with, is, member_mark, @@ -98,9 +98,6 @@ struct Declarations<'s, 'a, 'l> { assign: Option, /// The function bodies being read, the innermost last, up to [`crate::Limits::nesting`]. bodies: Vec>, - /// The names the bodies being read declare so far, each with the number of those bodies that - /// declare it. - declared_around: HashMap<&'s str, usize>, /// The bracket depth inside the outermost function body past that limit being read. The names /// declared inside it are not kept. untracked: Option, @@ -120,7 +117,6 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { var_depth: None, assign: None, bodies: vec![], - declared_around: HashMap::new(), untracked: None, keys: vec![], out: Declared::default(), @@ -208,8 +204,10 @@ impl<'s> Declarations<'s, '_, '_> { } else { None }; - // A name a body around `t` has declared with `var` before it is that body's own. - let own = |name: &str| self.untracked.is_none() && self.declared_around.contains_key(name); + // A name the innermost body around `t` has declared with `var` before it is that body's own. A + // name only an outer body declared is that body's variable, which a nested function may assign + // before a call in the outer body runs. + let own = |name: &str| self.untracked.is_none() && self.bodies.last().is_some_and(|b| b.names.contains(name)); if let Some(name) = assigned.filter(|n| !own(n)) { if self.out.body_assigned.contains(name) || self.acc.room(self.out.body_assigned.len()) { self.out.body_assigned.insert(name); @@ -316,14 +314,6 @@ impl<'s> Declarations<'s, '_, '_> { } while let Some(body) = self.bodies.pop_if(|b| depth < b.depth) { self.var_depth = body.var_depth; - for name in body.names { - if let Some(n) = self.declared_around.get_mut(name) { - *n = n.saturating_sub(1); - if *n == 0 { - self.declared_around.remove(name); - } - } - } } if self.untracked.is_some_and(|d| depth < d) { self.untracked = None; @@ -348,7 +338,6 @@ impl<'s> Declarations<'s, '_, '_> { if let Some(body) = self.bodies.last_mut() { if (var || body.depth == depth) && !body.names.contains(t.text) && self.acc.room(body.names.len()) { body.names.insert(t.text); - *self.declared_around.entry(t.text).or_insert(0) += 1; if let Some((_, names)) = self.out.bodies.get_mut(body.index) { names.push(t.text); } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 1b931a2cca..cd97a3b380 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -673,10 +673,11 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { /// assignment of a property of that name, which may be the global object's, a function body that /// assigns a `saveAs` or `exportFile` property of any object, code given as text, a `with` statement /// and an included file each leave the write reported. A function that declares its own variable of the -/// name, or assigns another property of it, leaves it the script's own. +/// name, or assigns another property of it, leaves it the script's own. A nested function that assigns +/// a variable its enclosing body declared leaves the write reported too. #[test] fn a_save_as_other_code_may_replace_writes_a_file() { - let cases: [(&str, &[usize]); 12] = [ + let cases: [(&str, &[usize]); 16] = [ ("var f = new File(p);\nvar d = app.activeDocument;\nif (flag) label:\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[5]), ( "var f = new File(p);\nvar d = {\n saveAs: function () {},\n useDocument: function () {\n d = null;\n d = app.activeDocument;\n }\n};\nd.useDocument();\nd.saveAs(f);\n", @@ -698,6 +699,22 @@ fn a_save_as_other_code_may_replace_writes_a_file() { ), ("var f = new File(p);\nfunction note() { d.n = 1; }\nvar d = {saveAs: function () {}};\nnote();\nd.saveAs(f);\n", &[]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\nfunction g() { var d = app.activeDocument; d = 1; }\nd.saveAs(f);\n", &[]), + ( + "var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d = app.activeDocument; }\n}\nrun();\n", + &[5], + ), + ( + "var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d += 1; }\n}\n", + &[5], + ), + ( + "var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d++; }\n}\n", + &[5], + ), + ( + "var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { for (d in o) {} }\n}\n", + &[5], + ), ]; for (src, lines) in cases { let r = report(src); From cb4c5e5ee9a59616bfac604ecea7f8d9ef8063d4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:24:39 -0800 Subject: [PATCH 10/18] Merge main into feat/scripts-export-autocad --- docs/roadmap.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index ff7e13fae7..4d7902f7b9 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -206,7 +206,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames, and save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | From 73946a86a8479561694834aec1d49ee25b02e96f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 23:03:05 -0800 Subject: [PATCH 11/18] Docs: exportFile names the image files a DXF writes beside it A DXF of a drawing with placed raster images writes each image it exports beside the drawing as a PNG file, or a JPEG file with rasterFormat JPEG. The exportFile paragraph in docs/mcp.md said it writes one file, with only the SVG companion images as an exception. --- docs/mcp.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 19632196b9..46d40b3dc2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3171,8 +3171,9 @@ through `$`: does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.dxf`, `.svgz` with `compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the - visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and - when the script's folders refuse one of those files, none of them is written; a write that fails once the + visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and a + DXF of a drawing with placed raster images writes each image it exports beside it as a PNG file, or a JPEG + file with `rasterFormat` `AutoCADRasterFormat.JPEG`; those files must travel with the DXF. When the script's folders refuse one of those files, none of them is written; a write that fails once the first file is in place leaves the files written before it. A listed option that is not mapped is accepted at its help page's default, and any other value throws an error that says it is not available yet, as does `ExportType.FLASH`. A property the help pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and From 937817609d2347b5bead727b282004dbadca2d69 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:33:34 -0800 Subject: [PATCH 12/18] Tests: the PDF 1.3 transparency check reads dictionaries only pdf_1_3_flattens_all_transparency_and_looks_the_same failed now and then because its transparency check searched the whole file for `/BM`. The file ID, written in the trailer and the XMP stream, is base64 that changes with the export time, so some exports had an ID that spells `/BM` and the check reported a blend mode in a flat file. The check now leaves out literal strings and stream data. A stream is found only by the whole `stream` keyword, not a name such as `/stream`, and its data is skipped by the stream dictionary's own `/Length`, read from the outermost dictionary and from its object when it is indirect. A length that does not end at `endstream`, or a stream with no `endstream`, fails the check. Every dictionary key it looked for is still checked. A new test covers an ID and an XMP packet that spell the keys, nested and escaped parentheses, `endstream` inside stream data, nested and indirect lengths, and wrong lengths. The helper comes from #10537. --- crates/engine/src/cmd/fileio/tests_pdf13.rs | 215 +++++++++++++++++++- 1 file changed, 213 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_pdf13.rs b/crates/engine/src/cmd/fileio/tests_pdf13.rs index 7c0aa4a74b..f3493555c9 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf13.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf13.rs @@ -71,9 +71,157 @@ fn export(s: &mut Session, p: Value) -> (Vec, Vec) { (bytes, v["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect()) } -/// The transparency `pdf` has, in its dictionaries. +/// Whether `b` ends a PDF token: white space or a delimiter. +fn ends_token(b: u8) -> bool { + b.is_ascii_whitespace() || b"()<>[]{}/%".contains(&b) +} + +/// The offset of object `number generation` in the cross-reference tables of `pdf`, starting at the +/// `startxref` at `startxref` and following `/Prev`. +fn xref_offset(pdf: &[u8], number: usize, generation: usize, startxref: usize) -> Option { + let mut offset = String::from_utf8_lossy(&pdf[startxref + b"startxref".len()..]).split_ascii_whitespace().next()?.parse::().ok()?; + let mut visited = vec![]; + loop { + if visited.contains(&offset) { + return None; + } + visited.push(offset); + let table = String::from_utf8_lossy(pdf.get(offset..)?); + let mut words = table.split_ascii_whitespace(); + if words.next()? != "xref" { + return None; + } + loop { + let first = words.next()?; + if first == "trailer" { + break; + } + let first = first.parse::().ok()?; + let count = words.next()?.parse::().ok()?; + for index in 0..count { + let at = words.next()?.parse::().ok()?; + let entry_generation = words.next()?.parse::().ok()?; + let status = words.next()?; + if first.checked_add(index)? == number { + return (status == "n" && entry_generation == generation).then_some(at); + } + } + } + let trailer = table.split_once("trailer")?.1.split_once(">>")?.0; + let mut words = trailer.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty()); + words.find(|&w| w == "Prev")?; + offset = words.next()?.parse().ok()?; + } +} + +/// The `/Length` of the stream dictionary that ends `text`, read from the outermost dictionary +/// after the object's `obj` keyword. An indirect length is read from its object in `pdf`. `None` +/// when it is missing or cannot be read. +fn stream_length(text: &[u8], pdf: &[u8]) -> Option { + let from = text.windows(3).rposition(|w| w == b"obj").map_or(0, |at| at + 3); + let dict = &text[from..]; + let mut i = dict.windows(2).position(|w| w == b"<<")? + 2; + let mut depth = 1usize; + let mut length = None; + while i < dict.len() && depth > 0 { + let rest = &dict[i..]; + if rest.starts_with(b"<<") { + depth += 1; + i += 2; + } else if rest.starts_with(b">>") { + depth -= 1; + i += 2; + } else if rest[0] == b'<' { + // A hex string. + i += rest.iter().position(|&b| b == b'>').map_or(rest.len(), |at| at + 1); + } else if depth == 1 && rest.starts_with(b"/Length") && rest.get(7).is_none_or(|&b| ends_token(b)) { + let value = String::from_utf8_lossy(&rest[7..]); + let words: Vec<&str> = value.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty()).take(3).collect(); + length = match words[..] { + // `n g R` is an indirect length: the integer in object `n g`. + [n, g, "R", ..] => { + let header = format!("{n} {g} obj"); + let read_length = |at: usize| { + let body = String::from_utf8_lossy(&pdf[at + header.len()..]); + match body.split_ascii_whitespace().take(2).collect::>()[..] { + [n, "endobj"] => n.parse::().ok(), + _ => None, + } + }; + if let Some(startxref) = pdf.windows(b"startxref".len()).rposition(|w| w == b"startxref") { + let at = + xref_offset(pdf, n.parse().ok()?, g.parse().ok()?, startxref).expect("stream /Length reference is missing from xref"); + let object = pdf.get(at..).expect("stream /Length xref offset is outside the file"); + assert!(object.starts_with(header.as_bytes()), "stream /Length xref offset has a different object"); + read_length(at) + } else { + pdf.windows(header.len()) + .enumerate() + // An object header starts a line, and the length object holds one integer. + .filter(|&(at, w)| w == header.as_bytes() && (at == 0 || matches!(pdf[at - 1], b'\r' | b'\n'))) + .find_map(|(at, _)| read_length(at)) + } + } + [n, ..] => n.parse::().ok(), + [] => None, + }; + i += 7; + } else { + i += 1; + } + } + length +} + +/// The transparency `pdf` has, in its dictionaries. Stream data and literal strings are left out: +/// the file ID, in the trailer and in the XMP stream, is base64 that changes with the export time +/// and can spell `/BM`. fn transparency(pdf: &[u8]) -> Vec<&'static str> { - let text = String::from_utf8_lossy(pdf); + let mut text = Vec::with_capacity(pdf.len()); + let mut i = 0; + while i < pdf.len() { + let rest = &pdf[i..]; + // A keyword follows white space or a dictionary's `>>`; after `/` it is part of a name. + let keyword_start = i == 0 || pdf[i - 1].is_ascii_whitespace() || pdf[i - 1] == b'>'; + if keyword_start && rest.starts_with(b"endstream") { + text.extend_from_slice(b"endstream"); + i += b"endstream".len(); + } else if keyword_start && rest.starts_with(b"stream") && matches!(rest.get(b"stream".len()), Some(b'\r' | b'\n')) { + // Stream data is the dictionary's `/Length` bytes after the end of line (else it runs to + // `endstream`); its bytes are not PDF syntax. + let start = i + b"stream".len() + if rest[b"stream".len()..].starts_with(b"\r\n") { 2 } else { 1 }; + i = match stream_length(&text, pdf) { + Some(n) => { + let mut end = start.checked_add(n).filter(|&end| end <= pdf.len()).expect("stream /Length is inconsistent with endstream"); + while matches!(pdf.get(end), Some(b'\r' | b'\n')) { + end += 1; + } + assert!(pdf[end..].starts_with(b"endstream"), "stream /Length is inconsistent with endstream"); + end + } + None => i + rest.windows(b"endstream".len()).position(|w| w == b"endstream").expect("stream has no endstream"), + }; + } else if rest[0] == b'(' { + // A literal string: balanced parentheses, with `\` escaping the next byte. + let mut depth = 0usize; + while i < pdf.len() { + match pdf[i] { + b'\\' => i += 1, + b'(' => depth += 1, + b')' => depth -= 1, + _ => {} + } + i += 1; + if depth == 0 { + break; + } + } + } else { + text.push(rest[0]); + i += 1; + } + } + let text = String::from_utf8_lossy(&text); let mut found = vec![]; for (what, there) in [ ("soft masks", text.contains("/SMask") && !text.contains("/SMask/None")), @@ -193,3 +341,66 @@ fn pdf_1_3_files_are_encrypted_with_40_bit_rc4_and_can_be_linearised() { s.execute("document.open", &json!({"dataBase64": vectorcraft_format::base64_encode(&pdf), "name": "old.pdf", "password": "nope"})).is_err() ); } + +/// The file ID is base64 that changes with the export time, so it can spell `/BM`; the check +/// reads the file's dictionaries only, not its strings or its XMP packet. +#[test] +fn the_transparency_check_skips_strings_and_metadata() { + let pdf = b"%PDF-1.3\n5 0 obj\n<>\nendobj\n6 0 obj\n<>\nstream\nq/BMx/S/Transparency\nendstream\nendobj\ntrailer\n<>\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + assert_eq!(transparency(b"<>>>>>"), vec!["blend modes", "opacity"]); + // A `(` in image data starts no string, and nested and escaped parentheses end where the + // string does. + let pdf = b"<>\nstream\n(\x00(\nendstream\n<>\n<>"; + assert_eq!(transparency(pdf), vec!["soft masks", "transparency groups"]); + // Stream data is skipped by its length, even when it holds `endstream` itself. + let pdf = b"1 0 obj\n<>\nstream\nendstream (/BM\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\nstream\nendstream /BM\nendstream\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + let pdf = b"1 0 obj\n<>\nstream\nabc\r\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["soft masks"]); + let pdf = b"1 0 obj\n<>\nstream\nabcendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\nstream\nabc\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["soft masks"]); + // Only the stream dictionary's own `/Length` counts, not one in a nested dictionary. + let pdf = b"1 0 obj\n<>>>\nstream\n/BM \nendstream\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + // `stream` inside a name is not the keyword. + let pdf = b"1 0 obj\n<>\nendobj\n"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\nendobj\n"; + assert_eq!(transparency(pdf), vec!["soft masks"]); + // An indirect length is read from its object, so `endstream` in the data does not end it. + let pdf = b"1 0 obj\n<>\nstream\nendstream /BM\nendstream\nendobj\n2 0 obj\n13\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + let payload = b"2 0 obj\n13\nendobj\nendstream /BM"; + let mut pdf = b"%PDF-1.3\n".to_vec(); + let stream_at = pdf.len(); + pdf.extend_from_slice(b"1 0 obj\n<>\nstream\n"); + pdf.extend_from_slice(payload); + pdf.extend_from_slice(b"\nendstream\nendobj\n"); + let length_at = pdf.len(); + pdf.extend_from_slice(format!("2 0 obj\n{}\nendobj\n", payload.len()).as_bytes()); + let catalog_at = pdf.len(); + pdf.extend_from_slice(b"3 0 obj\n<>\nendobj\n"); + let pages_at = pdf.len(); + pdf.extend_from_slice(b"4 0 obj\n<>\nendobj\n"); + let xref_at = pdf.len(); + pdf.extend_from_slice(b"xref\n0 5\n0000000000 65535 f\r\n"); + for at in [stream_at, length_at, catalog_at, pages_at] { + pdf.extend_from_slice(format!("{at:010} 00000 n\r\n").as_bytes()); + } + pdf.extend_from_slice(format!("trailer\n<>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes()); + assert_eq!(transparency(&pdf), Vec::<&str>::new()); + // A stream with no length and no `endstream` fails rather than hiding the rest of the file. + let pdf = b"1 0 obj\n<<>>\nstream\nabc\n<>"; + assert!(std::panic::catch_unwind(|| transparency(pdf)).is_err()); + for length in [2, 20, 999, usize::MAX] { + let pdf = format!("1 0 obj\n<>\nstream\nabc\nendstream\nendobj\n<>"); + let panic = std::panic::catch_unwind(|| transparency(pdf.as_bytes())).expect_err("an inconsistent stream /Length must panic"); + let message = panic.downcast_ref::<&str>().copied().or_else(|| panic.downcast_ref::().map(String::as_str)); + assert_eq!(message, Some("stream /Length is inconsistent with endstream"), "length {length}"); + } +} From a65d251c87f33a46b80d3e979981766a9887136a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 11:52:55 -0800 Subject: [PATCH 13/18] Scripts: DXF scale tests fail on a drawing with no polyline vertices dxf_widest and dxf_leftmost folded from f64::MIN and f64::MAX, so a DXF that kept its header but lost every vertex gave an infinite product and the unitScaleRatio and pica assertions still passed. Both now reduce the coordinates and fail when there are none. docs/mcp.md: a relative save or open path is resolved against the working folder of the process that wrote or read the file. --- crates/engine/src/tests/script_save_open.rs | 4 ++-- docs/mcp.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 7fd60b9f94..b3dd0d2ded 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -423,12 +423,12 @@ fn dxf_header(dxf: &str, name: &str) -> Option { /// The largest x coordinate (group code 10) in the entities of a DXF. fn dxf_widest(dxf: &str) -> f64 { - dxf_xs(dxf).into_iter().fold(f64::MIN, f64::max) + dxf_xs(dxf).into_iter().reduce(f64::max).expect("DXF contains polyline vertices") } /// The smallest x coordinate (group code 10) in the entities of a DXF. fn dxf_leftmost(dxf: &str) -> f64 { - dxf_xs(dxf).into_iter().fold(f64::MAX, f64::min) + dxf_xs(dxf).into_iter().reduce(f64::min).expect("DXF contains polyline vertices") } /// The x coordinates (group code 10) of the polyline vertices in a DXF. A hatch's code 10 is its diff --git a/docs/mcp.md b/docs/mcp.md index ca6d350642..8a2928c0a8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3301,7 +3301,7 @@ through `$`: writes only the file at the path, holding that artboard. Without `saveMultipleArtboards`, a `.ai` or EPS `artboardRange` is not checked against the document's artboards, but one that is not written as a range of artboard numbers (such as `abc` or `0-`) throws. `Document.path` is a `Folder` for the folder of the document's - file. A file saved or opened under a relative path is in the working folder of the process that wrote or read it, + file. A relative path that a file is saved or opened under is resolved against the working folder of the process that wrote or read it, for `fullName`, `path` and `close` alike. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. `fullName` and `path` of a document whose file the automation read roots do not allow throw `Script file access denied`. Changing `saved` runs `document.setSaved`: `true` records the document as saved From 1c9efecfb65e322518910ca6243841193d65e966 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:20:56 -0800 Subject: [PATCH 14/18] Workspaces: built-in workspaces open their panel again Switching to Essentials Classic, Automation, Layout, Painting, Printing and Proofing, Typography, Web or Touch, or resetting one, brought its panel to the front of its group but no longer opened it from a column collapsed to icons, so the panel stayed hidden. A workspace record keeps the panel open from the icons again: each built-in names its panel, a workspace left or saved keeps the one open then, and switching or Reset opens it. A recorded panel the new layout does not show from icons stays closed. Workspaces saved without the field open none. The Essentials Classic test checks the open panel again, and new tests cover Painting, Automation, switching back as left, Reset, saved workspaces and the preferences' JSON. --- crates/ui-egui/src/workspaces.rs | 77 ++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index 683c087332..5b04aa50f2 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -64,6 +64,10 @@ pub struct WorkspaceRecord { /// Tabs closed together by a panel shortcut. #[serde(skip_serializing_if = "Vec::is_empty")] pub docking_hidden_groups: Vec>, + /// The panel open from a column collapsed to icons (built-in workspaces: the panel the + /// workspace is for; workspaces saved without this field: none). + #[serde(skip_serializing_if = "Option::is_none")] + pub open_panel: Option, /// The tool each flyout group of the main Tools shows (built-in workspaces: the first). pub tools_last_used: LastUsed, /// The toolbars made with New Toolbar in this workspace (built-in workspaces: none). @@ -87,6 +91,7 @@ impl Default for WorkspaceRecord { status_bar: true, help_bar: true, docking_hidden_groups: Vec::new(), + open_panel: None, tools_last_used: LastUsed::default(), toolbars: Vec::new(), } @@ -245,25 +250,30 @@ pub fn builtins() -> Vec { x.rulers = true; x.toolbar_advanced = true; x.task_bar = false; + x.open_panel = Some("color".into()); }), w("Automation", &["layers", "actions"], &|x| { x.control_bar = true; x.toolbar_advanced = true; + x.open_panel = Some("actions".into()); }), w("Layout", &["layers", "align"], &|x| { x.control_bar = true; x.rulers = true; x.toolbar_advanced = true; + x.open_panel = Some("align".into()); }), w("Painting", &["brushes"], &|x| { x.control_bar = true; x.toolbar_advanced = true; + x.open_panel = Some("brushes".into()); }) .double_tools(), w("Printing and Proofing", &["info"], &|x| { x.control_bar = true; x.rulers = true; x.toolbar_advanced = true; + x.open_panel = Some("info".into()); }), w("Tracing", &["layers"], &|x| { x.control_bar = true; @@ -274,16 +284,19 @@ pub fn builtins() -> Vec { x.control_bar = true; x.rulers = true; x.toolbar_advanced = true; + x.open_panel = Some("character".into()); }), w("Web", &["symbols"], &|x| { x.control_bar = true; x.rulers = true; x.toolbar_advanced = true; + x.open_panel = Some("symbols".into()); }), w(TOUCH, &["align"], &|x| { x.control_bar = true; x.toolbar_advanced = true; x.task_bar = true; + x.open_panel = Some("align".into()); }), ] } @@ -387,6 +400,7 @@ pub fn record(ui: &UiState) -> WorkspaceRecord { status_bar: ui.status_bar, help_bar: ui.help_bar, docking_hidden_groups: ui.docking_hidden_groups.clone(), + open_panel: ui.open_panel.clone(), tools_last_used: ui.tools_last_used.clone(), toolbars: ui.custom_toolbars.clone(), } @@ -412,6 +426,7 @@ fn apply_record(ui: &mut UiState, w: &WorkspaceRecord) { ui.status_bar = w.status_bar; ui.help_bar = w.help_bar; ui.docking_hidden_groups = w.docking_hidden_groups.clone(); + ui.open_panel = w.open_panel.clone(); ui.tools_last_used = w.tools_last_used.clone(); ui.custom_toolbars = w.toolbars.clone(); crate::custom_toolbars::sanitize(&mut ui.custom_toolbars); @@ -450,10 +465,19 @@ pub fn switch(app: &mut VectorcraftApp, key: &str) -> Result { let w = ui.workspaces.edited.get(&id).cloned().unwrap_or_else(|| saved_record(&ui.workspaces, &id)); apply_record(ui, &w); crate::panel_docking::reconcile(&mut ui.dock_workspace); + close_stale_flyout(ui); crate::panel_docking::show_panels(app); Ok(name) } +/// Close the open panel when the layout now in use does not show it from a column collapsed to +/// icons (it was moved, expanded or closed). +fn close_stale_flyout(ui: &mut UiState) { + if ui.open_panel.as_ref().is_some_and(|panel| !crate::panel_docking::layout_of(ui).opens_in_flyout(panel)) { + ui.open_panel = None; + } +} + /// Reset the current workspace to the way it was saved, dropping its changes. pub fn reset(app: &mut VectorcraftApp) -> String { let ui = &mut app.ui; @@ -467,6 +491,7 @@ pub fn reset(app: &mut VectorcraftApp) -> String { apply_record(ui, &w); ui.custom_toolbars = toolbars; crate::panel_docking::reconcile(&mut ui.dock_workspace); + close_stale_flyout(ui); crate::panel_docking::show_panels(app); current_name(&app.ui).to_string() } @@ -715,12 +740,64 @@ mod tests { switch(&mut app, "Essentials Classic").unwrap(); assert!(app.ui.control_bar && app.ui.view.rulers && app.ui.toolbar_advanced); assert!(front(&app.ui, "color")); + assert_eq!(app.ui.open_panel.as_deref(), Some("color")); assert_eq!(current_name(&app.ui), "Essentials Classic"); switch(&mut app, "essentials").unwrap(); assert!(!app.ui.control_bar && !app.ui.view.rulers); + assert_eq!(app.ui.open_panel, None); assert_eq!(app.ui.brightness, crate::theme::Brightness::Light); } + /// A built-in workspace shows the panel it is for, from its collapsed column too: the second + /// panel it brings forward (Automation's Actions) as well as the only one (Painting's + /// Brushes). A panel closed there stays closed when the workspace is left and switched back + /// to, and Reset opens it again. + #[test] + fn builtin_workspaces_show_their_panel_after_switch_and_reset() { + let showing = crate::panel_docking::showing; + let mut app = app(); + for (name, panel) in [("Painting", "brushes"), ("Automation", "actions"), ("Essentials Classic", "color")] { + switch(&mut app, name).unwrap(); + assert!(showing(&app.ui, panel), "{name} shows {panel}"); + } + assert!(crate::panel_docking::layout_of(&app.ui).opens_in_flyout(&"color".to_string()), "Classic's Color opens from its icon"); + app.ui.open_panel = None; + switch(&mut app, ESSENTIALS).unwrap(); + assert!(!showing(&app.ui, "color"), "Essentials opens no panel"); + switch(&mut app, "Essentials Classic").unwrap(); + assert!(!showing(&app.ui, "color"), "Classic comes back as it was left"); + reset(&mut app); + assert!(showing(&app.ui, "color"), "Reset Essentials Classic shows Color again"); + } + + /// A saved workspace keeps the panel open from its icons, through the preferences' JSON too; a + /// workspace saved without that field opens none, and one naming a panel its layout does not + /// show from icons opens none either. + #[test] + fn saved_workspaces_restore_the_open_panel() { + let mut app = app(); + switch(&mut app, "Essentials Classic").unwrap(); + save_as(&mut app.ui, "Colors").unwrap(); + switch(&mut app, ESSENTIALS).unwrap(); + assert_eq!(app.ui.open_panel, None); + switch(&mut app, "Colors").unwrap(); + assert_eq!(app.ui.open_panel.as_deref(), Some("color")); + let id = id_of(&app.ui, "Colors"); + let back: UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); + assert_eq!(back.workspaces.records[&id].open_panel.as_deref(), Some("color")); + let mut old = serde_json::to_value(&back.workspaces.records[&id]).unwrap(); + assert!(old.as_object_mut().unwrap().remove("openPanel").is_some()); + let old: WorkspaceRecord = serde_json::from_value(old).unwrap(); + assert_eq!(old.open_panel, None); + switch(&mut app, ESSENTIALS).unwrap(); + app.ui.workspaces.edited.get_mut(&id).unwrap().open_panel = Some("no-such-panel".into()); + switch(&mut app, "Colors").unwrap(); + assert_eq!(app.ui.open_panel, None, "switching opens no panel the layout's icons lack"); + app.ui.workspaces.records.get_mut(&id).unwrap().open_panel = Some("no-such-panel".into()); + reset(&mut app); + assert_eq!(app.ui.open_panel, None, "Reset opens no panel the layout's icons lack"); + } + #[test] fn save_apply_round_trip() { let mut app = app(); From 5ce02bb64bd7aae18ea65c6b90f2bb8c82bdd6a9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:26:00 -0800 Subject: [PATCH 15/18] Flatten Transparency: write rasterized areas as fast-compressed PNGs Since #7669 the flattener's rasters have been encoded through the shared image codec with its default compression (zlib level 6). EPS export, and any other export that flattens, encodes every rasterized area this way and then decodes it again right away, so a document with many live effects exported about 170 ms slower to EPS. The rasters are now written with PngCompression::Fast, as the SVG filter raster already is (crates/effects/src/svg_filter.rs). The pixels and the EPS output bytes do not change. --- crates/engine/src/cmd/flatten/apply.rs | 14 ++++++++++- crates/engine/src/tests/flatten.rs | 35 ++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index fe1e183d16..8a884b67ea 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -692,7 +692,19 @@ fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Optio } } } - let png = img.to_png().map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?; + // The PNG is written with fast compression: the exports that flatten (EPS, PDF 1.3) decode it + // again right away. + let raw = craft_image_codecs::Image::from_raw( + img.width, + img.height, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + img.to_straight(), + ) + .map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?; + let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() }; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &opts) + .map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?; Ok(Raster { blob: ImageBlob::new("image/png", png), width: img.width, height: img.height, xf, clip }) } diff --git a/crates/engine/src/tests/flatten.rs b/crates/engine/src/tests/flatten.rs index 042f741e0e..959c58e9f3 100644 --- a/crates/engine/src/tests/flatten.rs +++ b/crates/engine/src/tests/flatten.rs @@ -350,6 +350,41 @@ fn gradients_rasterize_and_flat_areas_stay_vector() { } } +/// A rasterized area is stored as a PNG written with fast compression: its zlib header (RFC 1950) +/// gives compression level 0, the fastest. +#[test] +fn rasterized_areas_are_png_with_fast_compression() { + let _settings = settings_lock(); + let mut s = session(); + let g = rect(&mut s, 10.0, 10.0, 100.0, 100.0, "#000000"); + run( + &mut s, + "paint.setFill", + json!({"ids": [g], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}), + ); + run(&mut s, "transparency.set", json!({"ids": [g], "opacity": 40})); + let (ids, _, rasterized) = flatten(&mut s, json!({"ids": [g], "preset": "high"})); + assert_eq!(rasterized, 1); + let mut keys = vec![]; + node(&s, ids[0]).walk(&mut |c| { + if let NodeKind::Image(im) = &c.kind { + keys.push(im.key.clone()); + } + }); + let [key] = &keys[..] else { panic!("one image: {keys:?}") }; + let png = &s.doc().unwrap().doc.images[key].bytes; + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "a PNG"); + let mut at = 8; + let level = loop { + let (Some(len), Some(kind)) = (png.get(at..at + 4), png.get(at + 4..at + 8)) else { panic!("a PNG with image data") }; + if kind == b"IDAT" { + break png[at + 9] >> 6; + } + at += 12 + u32::from_be_bytes(len.try_into().unwrap()) as usize; + }; + assert_eq!(level, 0, "zlib FLEVEL of the stored PNG"); +} + #[test] fn a_long_rasterized_area_is_placed_whole() { let _settings = settings_lock(); From f5111b293dd78df3e68c26b84b2696aff04eb234 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:51:35 -0800 Subject: [PATCH 16/18] Home: the title is drawn at 24 points again The compact type was set to 92% of its nominal sizes (body 13 to 12, labels 12.5 to 11.5, captions 11.5 to 10.5), but the display type that draws the Home title stayed at 26 points on a 32-point line, so the title drew about 8.7% larger than in 0.24.1. The display type is now 24 points on a 29-point line, its nominal 26 on 32 at the same scale. A test checks that the title keeps the nominal title-to-body proportion against the compact body type, and that its line keeps the framework's display line proportion. --- crates/ui-egui/src/theme.rs | 38 ++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 09b5eec0b0..b47ef8e91e 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -146,7 +146,8 @@ pub fn root_theme(prefs: &Prefs) -> (ThemeId, ModeChoice, Option) { } /// The app's sizes over the framework's size sets (`sizes.json`): push buttons have the app's 4-point corners -/// where the sets give pills, the Home title is 26-point with a 36-point call to action, 28-point New and Open with 16 +/// where the sets give pills, the Home title is 24-point on a 29-point line (its nominal 26 points on 32 at the 92% +/// the body type below is set at) with a 36-point call to action, 28-point New and Open with 16 /// points beside their labels and 24-point link rows. Home's margin and the gaps between its title, actions, sections, /// headings and links are the framework's page tokens, which follow its spacing scale (`space.gap.*`). The compact set /// takes the reference app's metrics: @@ -159,8 +160,8 @@ pub fn root_theme(prefs: &Prefs) -> (ThemeId, ModeChoice, Option) { const SIZES: &[u8] = br#"{ "all": { "radius.button": 4, - "typography.display.size": 26, - "typography.display.line_height": 32, + "typography.display.size": 24, + "typography.display.line_height": 29, "size.page.action": 36, "size.page.button": 28, "size.page.button_side": 16, @@ -236,6 +237,37 @@ mod tests { assert!(AppSizes::parse(SIZES).is_ok_and(|sizes| !sizes.is_empty())); } + /// The Home title (the display type) is set at the same scale as the compact body type, so it keeps the nominal + /// 26-point title over a 13-point body proportion, and its line keeps the framework's display line proportion. + #[test] + fn the_home_title_is_scaled_with_the_body_type() { + use craft::theme::Size; + use craft::ui::runtime::env::{Env, RootEnv}; + use craft::ui::testing::Fixture; + use std::cell::Cell; + use std::rc::Rc; + const NOMINAL_TITLE_OVER_BODY: f32 = 26.0 / 13.0; + let typography = |sizes: Arc| { + let seen = Rc::new(Cell::new(None)); + let seen_in = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let t = Env::of(ui).tokens.tokens().typography; + seen_in.set(Some((t.display, t.body))); + }); + let mut root = RootEnv::new().density(Size::Compact); + root.sizes = sizes; + fixture.root(root); + fixture.frame(vec![]); + seen.get().expect("the fixture drew a frame") + }; + let (display, body) = typography(app_sizes()); + let ratio = display.size / body.size; + assert!((ratio - NOMINAL_TITLE_OVER_BODY).abs() < 0.05, "a {}-point title over a {}-point body", display.size, body.size); + let (framework, _) = typography(Arc::new(AppSizes::default())); + let (line, framework_line) = (display.line_height / display.size, framework.line_height / framework.size); + assert!((line - framework_line).abs() < 0.05, "a {}-point line for a {}-point title", display.line_height, display.size); + } + /// Home's margin and gaps are the framework's page tokens: no size set gives them points of its own, so they follow /// the framework's spacing scale. #[test] From b7bc86522cbd0a2fc25d417a2b81441367562925 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:52:39 -0800 Subject: [PATCH 17/18] Tools: a strip floated before the canvas is laid out opens beside the rail window.floatTools placed a new strip at the canvas's top left, and fell back to (0,0) when no view had been laid out yet: right after a document opened, or with no document open. The strip then covered the top of the docked Tools rail. Without a laid-out view, the strip now opens beside the docked rail it came from (else the Tools panel's), level with the rail's top and the float space's cascade inset away from it, on the side toward the middle of the window. A dragged tear-off still opens at the pointer. --- crates/ui-egui/src/panel_docking.rs | 22 ++++++++++++++++++++++ crates/ui-egui/src/toolbar.rs | 12 +++++++++--- crates/ui-egui/src/toolbar/tests.rs | 24 ++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 0fd8936a45..1a47d5a7d2 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -301,6 +301,28 @@ pub(crate) fn column_of<'a>(layout: &'a Layout, panel: &str) -> Option<( Some((edge, column)) } +/// Where the dock last drew the docked column holding `panel`; none until the dock has drawn it, and while `panel` +/// floats or is closed. +pub(crate) fn column_rect(app: &VectorcraftApp, panel: &str) -> Option { + let (Some(_), column) = column_of(layout_of(&app.ui), panel)? else { return None }; + app.dock_rt.columns.iter().find(|(first, _)| column.panels().any(|p| p == first)).map(|(_, rect)| *rect) +} + +/// The top left a new floating window of `panel` takes beside the docked column holding `beside`: level with the +/// column's top, the cascade inset away from it on the side toward the middle of the float space. None until the dock +/// has drawn that column. +pub(crate) fn float_origin_beside(app: &VectorcraftApp, panel: &str, beside: &str) -> Option { + let column = column_rect(app, beside)?; + let space = command_space(app); + let x = if column.center().x <= space.area.center().x { + column.right() + space.inset + } else { + let width = space.size_of(&DragUnit::Panel(panel.to_owned()), None).x; + column.left() - space.inset - width + }; + Some(egui::pos2(x, column.top())) +} + /// Is the dock's outer column of panels (Properties · Layers · Libraries) collapsed to icons? pub(crate) fn dock_collapsed(ui: &UiState) -> bool { dock_columns(layout_of(ui)).first().is_some_and(|c| c.iconic) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 34a7829ba9..49da6d5a44 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -294,11 +294,17 @@ pub(crate) fn is_floating(app: &VectorcraftApp, toolbar: Option<&str>, key: &str strips(app, toolbar).iter().any(|g| g.first() == Some(&key)) } -/// Float the group `first` of `owner` as a strip at `at` (none: the canvas's corner). +/// Float the group `first` of `owner` as a strip at `at`. Without `at` the strip opens at the canvas's corner, or, +/// before a view has been laid out, beside `owner`'s docked rail, else beside the Tools panel's. fn place_strip(app: &mut VectorcraftApp, owner: &Owner, first: &str, at: Option) -> Result<(), String> { - let at = at.unwrap_or_else(|| app.canvas_view().map_or(Pos2::ZERO, |v| v.rect.min)); + let id = strip_id(owner, first); + let at = at + .or_else(|| app.canvas_view().map(|v| v.rect.min)) + .or_else(|| crate::panel_docking::float_origin_beside(app, &id, &owner.panel())) + .or_else(|| crate::panel_docking::float_origin_beside(app, &id, TOOLS)) + .unwrap_or(Pos2::ZERO); // A width of 0 leaves the window's width to the panel's grid. - crate::panel_docking::place_floating(app, &strip_id(owner, first), at, 0.0) + crate::panel_docking::place_floating(app, &id, at, 0.0) } /// Float the toolbar group (of the current layout) holding `tool` as a strip of tool buttons, put diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 91becce66b..2abb2f3cc1 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -483,6 +483,30 @@ fn window_float_tools_floats_and_puts_back_a_group() { assert!(strip_rect(&app, "rectangle").is_none() && !is_floating(&app, None, "pen")); } +/// `window.floatTools` run before a view has been laid out (right after a document opens, or with none open) floats the +/// strip beside the docked Tools rail, not over it, and the strip stays clear of the rail once the frames are drawn. +#[test] +fn a_strip_floated_before_a_view_is_laid_out_opens_beside_the_tools_rail() { + for (case, document) in [("document just opened", true), ("no document", false)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = crate::testing::ui_context(); + settled(&mut app, &ctx, 0.0, 900.0); + if document { + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + } + assert!(app.canvas_view().is_none(), "{case}: no view has been laid out yet"); + let rail = crate::panel_docking::column_rect(&app, TOOLS).unwrap_or_else(|| panic!("{case}: the Tools rail is docked")); + app.run("window.floatTools", json!({"tool": "pen"})).unwrap(); + let strip = strip_rect(&app, "pen").unwrap_or_else(|| panic!("{case}: the Pen strip floats")); + assert!(strip.left() >= rail.right(), "{case}: the strip {strip:?} opens right of the rail {rail:?}"); + assert!((strip.top() - rail.top()).abs() <= f32::EPSILON, "{case}: the strip {strip:?} is level with the rail {rail:?}"); + settled(&mut app, &ctx, 1.0, 900.0); + let rail = crate::panel_docking::column_rect(&app, TOOLS).unwrap_or_else(|| panic!("{case}: the Tools rail stays docked")); + let strip = strip_rect(&app, "pen").unwrap_or_else(|| panic!("{case}: the Pen strip still floats")); + assert!(!strip.intersects(rail), "{case}: the strip {strip:?} is clear of the rail {rail:?}"); + } +} + /// A floated group is a panel of the workspace's layout: a saved workspace brings it back, the built-in ones have none. #[test] fn workspaces_keep_floating_flyouts_and_reset_puts_them_back() { From f24eff296329cf96f3fe3ae54833a2a84205738d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:11:32 -0800 Subject: [PATCH 18/18] PDF: stream length test helper ignores names ending in obj stream_length took the last "obj" substring in the text as the object header, so a stream dictionary name such as /Tag/obj moved the scan past the outer dictionary and lost its /Length. The keyword now counts only at the start of the text or after PDF white space. --- crates/engine/src/cmd/fileio/tests_pdf13.rs | 25 ++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_pdf13.rs b/crates/engine/src/cmd/fileio/tests_pdf13.rs index f3493555c9..fc386ac09c 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf13.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf13.rs @@ -115,10 +115,16 @@ fn xref_offset(pdf: &[u8], number: usize, generation: usize, startxref: usize) - } /// The `/Length` of the stream dictionary that ends `text`, read from the outermost dictionary -/// after the object's `obj` keyword. An indirect length is read from its object in `pdf`. `None` -/// when it is missing or cannot be read. +/// after the object's `obj` keyword. The keyword counts only at the start of `text` or after white +/// space, so a name such as `/Tag/obj` is not taken for it. An indirect length is read from its +/// object in `pdf`. `None` when it is missing or cannot be read. fn stream_length(text: &[u8], pdf: &[u8]) -> Option { - let from = text.windows(3).rposition(|w| w == b"obj").map_or(0, |at| at + 3); + let from = text + .windows(3) + .enumerate() + .rev() + .find(|&(at, w)| w == b"obj" && (at == 0 || matches!(text[at - 1], b'\0' | b'\t' | b'\n' | b'\x0c' | b'\r' | b' '))) + .map_or(0, |(at, _)| at + 3); let dict = &text[from..]; let mut i = dict.windows(2).position(|w| w == b"<<")? + 2; let mut depth = 1usize; @@ -404,3 +410,16 @@ fn the_transparency_check_skips_strings_and_metadata() { assert_eq!(message, Some("stream /Length is inconsistent with endstream"), "length {length}"); } } + +/// A name that ends in `obj`, such as `/Tag/obj`, is not the object's `obj` keyword, so the +/// stream's `/Length` is still read from the outer dictionary. +#[test] +fn the_stream_length_skips_names_that_end_in_obj() { + let text = b"1 0 obj\n<>\nstream\n"; + assert_eq!(stream_length(text, text), Some(5)); + // NUL is PDF white space, so it may separate the generation number from `obj`. + let text = b"1 0 obj\n<>\nstream\nabc\nendstream\nendobj\n2 0\0obj\n<>\nstream\n"; + assert_eq!(stream_length(text, text), Some(5)); + let pdf = b"1 0 obj\n<>\nstream\nendstream /BM\nendstream\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); +}