From 41c375fa579de106534d35fa764dd386442c3bb5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:30:55 -0800 Subject: [PATCH] Scripts: imageCapture refuses a missing linked file's path Document.imageCapture compared only paths that exist, so a capture to the path of a linked image whose file is missing created the file the document then loads from that link. Each path is now compared as its folder's real path and its name, so a missing file counts too. A name that differs only in letter case is the same file in a folder whose names ignore case: the folder's own entries are looked up with their ASCII letter case swapped, and on macOS the nearest folder above on the same volume. When neither tells, the capture is refused. --- .../engine/src/script/dom/raster_capture.rs | 104 ++++++++++++++++-- .../engine/src/tests/script_raster_capture.rs | 67 +++++++++++ docs/mcp.md | 11 +- 3 files changed, 170 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index a75f1a1c4a..811d0c48c4 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -269,10 +269,10 @@ fn capture_settings(items: Option<&[(String, Data)]>) -> std::result::Result<(f6 /// The files a capture must not write over: the open documents' files and the files their linked /// images and placed documents show, wherever those are stored (opacity masks, symbols, patterns -/// and brushes included), with a DCS image's plate files, by their real paths. A link's stored path -/// and its relative path are each taken from its document's folder, as opening the document reads -/// them. -fn sources_on_disk(h: &Host) -> Vec { +/// and brushes included), with a DCS image's plate files, also when a file is missing, in the form +/// [`placed`] gives. A link's stored path and its relative path are each taken from its +/// document's folder, as opening the document reads them. +fn sources_on_disk(h: &Host) -> Vec { let s = h.session.borrow(); let mut paths: Vec = Vec::new(); for st in s.documents() { @@ -287,7 +287,97 @@ fn sources_on_disk(h: &Host) -> Vec { } } } - paths.iter().filter_map(|p| std::fs::canonicalize(p).ok()).collect() + paths.iter().filter_map(|p| placed(std::path::Path::new(p))).collect() +} + +/// A file as its folder's real path and its name. +type Placed = (std::path::PathBuf, std::ffi::OsString); + +/// `p` as its folder's real path and its file name: from its real path with links followed, or, +/// for a file that is not there, from its folder's real path. `None` when neither the file nor its +/// folder is there. +fn placed(p: &std::path::Path) -> Option { + let real = std::fs::canonicalize(p).ok().or_else(|| Some(std::fs::canonicalize(p.parent()?).ok()?.join(p.file_name()?)))?; + Some((real.parent()?.to_path_buf(), real.file_name()?.to_os_string())) +} + +/// Whether two [`placed`] files are one file: the same folder, and the same name, or names that +/// differ only in letter case in a folder whose volume ignores case. +fn same_file(a: &Placed, b: &Placed) -> bool { + same_folder(&a.0, &b.0) && (a.1 == b.1 || (a.1.to_string_lossy().to_lowercase() == b.1.to_string_lossy().to_lowercase() && ignores_case(&a.0))) +} + +/// Whether two real paths are one file or folder: the same path, or, on Unix, the same device and +/// file number, so a path spelled in another letter case on a volume that ignores case still +/// matches. On Windows a real path carries the letter case stored on disk. +fn same_folder(a: &std::path::Path, b: &std::path::Path) -> bool { + if a == b { + return true; + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if let (Ok(x), Ok(y)) = (std::fs::metadata(a), std::fs::metadata(b)) { + return x.dev() == y.dev() && x.ino() == y.ino(); + } + } + false +} + +/// Whether `other`, a spelling of `entry` in other letter case, finds `entry` itself and not a +/// symbolic link or another file. +fn finds_same(entry: &std::path::Path, other: &std::path::Path) -> bool { + if !std::fs::symlink_metadata(other).is_ok_and(|m| !m.file_type().is_symlink()) { + return false; + } + match (std::fs::canonicalize(entry), std::fs::canonicalize(other)) { + (Ok(a), Ok(b)) => same_folder(&a, &b), + _ => false, + } +} + +/// `name` with the letter case of every ASCII letter swapped, and other characters as they are. +fn swapped_case(name: &str) -> String { + name.chars().map(|c| if c.is_ascii_lowercase() { c.to_ascii_uppercase() } else { c.to_ascii_lowercase() }).collect() +} + +/// Whether file names in the real folder `folder` ignore letter case. Names keep case when two of +/// the folder's first 256 entries differ only in the case of ASCII letters. Otherwise the first of +/// them whose name has an ASCII letter and that is not a symbolic link is looked up with the case +/// of those letters swapped: names ignore case when that finds the same entry. With no such entry +/// on macOS, where a whole volume either ignores or keeps case, the nearest folder at or above +/// `folder` whose name has an ASCII letter, with its parent on the same volume, is looked up the +/// same way in its parent. When neither tells, names are taken to ignore case. +fn ignores_case(folder: &std::path::Path) -> bool { + let entries: Vec = std::fs::read_dir(folder).into_iter().flatten().flatten().take(256).collect(); + let mut folded = std::collections::HashSet::new(); + let names: std::collections::HashSet = entries.iter().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + if !names.iter().all(|n| folded.insert(n.to_ascii_lowercase())) { + return false; + } + for entry in &entries { + let name = entry.file_name().to_string_lossy().into_owned(); + let swapped = swapped_case(&name); + if swapped != name && entry.file_type().is_ok_and(|t| !t.is_symlink()) { + return finds_same(&entry.path(), &folder.join(swapped)); + } + } + #[cfg(target_os = "macos")] + for dir in folder.ancestors() { + use std::os::unix::fs::MetadataExt; + let (Some(parent), Some(name)) = (dir.parent(), dir.file_name()) else { break }; + let device = |p: &std::path::Path| std::fs::metadata(p).map(|m| m.dev()).ok(); + let here = device(folder); + if here.is_none() || device(dir) != here || device(parent) != here { + break; + } + let name = name.to_string_lossy(); + let swapped = swapped_case(&name); + if swapped != name { + return finds_same(dir, &parent.join(swapped)); + } + } + true } /// `document.imageCapture(imageFile, clipBounds?, options?)`: `document.export` of a PNG of the @@ -308,8 +398,8 @@ fn doc_image_capture(h: &Host, a: &[Data]) -> Answer { }; check_size(region, ppi)?; let real = h.disk.borrow().save_target(path).map_err(|m| HostError::Error(format!("{m}: {path}")))?; - let canonical = std::fs::canonicalize(&real).ok(); - if canonical.is_some_and(|c| sources_on_disk(h).contains(&c)) { + let target = placed(&real); + if target.is_some_and(|t| sources_on_disk(h).iter().any(|s| same_file(&t, s))) { return Err(HostError::Error(format!("imageCapture cannot write over an open document or a file it links: {path}"))); } let p = json!({ diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 3385c4dd5c..e48c7a2d46 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -524,6 +524,73 @@ fn capture_denied_or_source_path_writes_nothing() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn capture_to_a_missing_links_path_writes_nothing() { + let base = folder("missing-link"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + // An image linked by a path next to the document whose file is not there. + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: "gone.png".into(), relative: Some("gone.png".into()), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "gone".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); + let gone = dir.join("gone.png"); + assert!(!gone.exists()); + let e = + file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&gone))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert!(!gone.exists(), "nothing written"); + // The same name in other letter case is the linked file only where the volume ignores case. + std::fs::write(dir.join("probe.txt"), b"x").unwrap(); + let volume_ignores_case = dir.join("PROBE.TXT").exists(); + let upper = dir.join("GONE.png"); + let text = format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&upper)); + if volume_ignores_case { + assert!(file_failure(&mut s, &base, &text).contains("cannot write over an open document")); + assert!(!gone.exists(), "nothing written"); + } else { + script(&mut s, &base, &text); + assert!(upper.exists() && !gone.exists(), "a different file on a volume that keeps case"); + // Two names for one file that differ only in case show that the folder keeps case. + let sub = dir.join("sub"); + std::fs::create_dir(&sub).unwrap(); + std::fs::write(sub.join("probe.txt"), b"x").unwrap(); + std::fs::hard_link(sub.join("probe.txt"), sub.join("PROBE.TXT")).unwrap(); + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: "sub/gone.png".into(), relative: Some("sub/gone.png".into()), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "sub-gone".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); + let sub_upper = sub.join("GONE.png"); + script(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&sub_upper))); + assert!(sub_upper.exists() && !sub.join("gone.png").exists()); + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn capture_written_before_a_failure_is_reported() { let base = folder("report"); diff --git a/docs/mcp.md b/docs/mcp.md index 24cda05fea..b58ff4129b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2749,14 +2749,15 @@ app through the global object `vc`, and writes to the Script Console and runs ot document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in a locked layer or group throw an error, and nothing changes. It keeps the selection, less the art it replaces. With `clippingMask` the `RasterItem` is the image inside its clip group. `transparency` wins over `backgroundBlack`, and - `padding` takes 0 to 1,000 points. `convertSpotColors`, `convertTextToOutlines` and `includeLayers` true throw an error that says - they are not available yet. `imageCapture` writes a PNG, and the file's name must end with `.png`. With + `padding` takes 0 to 1,000 points. `convertSpotColors`, `convertTextToOutlines` and `includeLayers` true throw an + error that says they are not available yet. `imageCapture` writes a PNG, and the file's name must end with `.png`. With `transparency` the image keeps its transparency; otherwise it is drawn on `matteColor` with `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0 to 255. The file is checked as a `File` opened for writing is checked, and a path that is an open document's file or a file one of them links throws an - error. An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is drawn or - written, and the resolution is never lowered to make it fit. `Document.windowCapture` throws an error that says it - is not available yet. + error, also when that file is missing. A name that differs from it only in letter case throws the same error in a + folder whose names ignore case, and in a folder where that cannot be told. An image of more than 64 megapixels or + 32,768 pixels a side throws an error before anything is drawn or written, and the resolution is never lowered to + make it fit. `Document.windowCapture` throws an error that says it is not available yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global