Merge pull request #10636 from dotCooCoo/fix/script-image-read-once

Scripts: placing or relinking an image reads its file once
This commit is contained in:
.CooCoo authored and GitHub committed 2026-12-03 07:32:03 -08:00
commit 9a21dae940
9 files changed
+107 -11

No files matched your search

+3
View File
@@ -87,6 +87,7 @@ pub(crate) use load::decode_native_file;
use load::err;
pub(crate) use load::import_svg;
pub(crate) use load::is_placeholder;
pub(crate) use load::is_raster_image;
pub(crate) use load::page_or_editing_data;
pub(crate) use load::source;
pub use load::{
@@ -146,6 +147,8 @@ mod commands;
mod export_names;
mod formats;
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) use access::FILES_READ;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use access::list_dir;
#[cfg(all(test, not(target_arch = "wasm32")))]
+8
View File
@@ -283,10 +283,18 @@ pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX
#[cfg(not(target_arch = "wasm32"))]
pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB";
#[cfg(all(test, not(target_arch = "wasm32")))]
thread_local! {
/// The paths [`read_file`] has read on this thread, in order.
pub(crate) static FILES_READ: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
use std::io::Read;
may_read(path)?;
#[cfg(test)]
FILES_READ.with(|r| r.borrow_mut().push(path.to_string()));
// A device or pipe may never end: only a regular file is read to its end.
if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() {
return Err(EngineError::Other(format!("{path}: not a file")));
+14
View File
@@ -1160,6 +1160,20 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
(drawn != (w, h)).then(|| format!("an image of {w} × {h} pixels is shown at reduced size"))
}
/// Whether `bytes` start as a file in a format [`raster_image`] reads, whether or not the rest of
/// it can be decoded.
pub(crate) fn is_raster_image(bytes: &[u8]) -> bool {
super::pcraftread::is_pcraft(bytes)
|| psdread::is_psd(bytes)
|| jxlread::is_jxl(bytes)
|| super::jp2read::is_jpeg2000(bytes)
|| super::heifread::is_heif(bytes)
|| super::pxrread::is_pxr(bytes)
|| craft_image_codecs::detect(bytes).is_some()
|| super::tgaread::is_targa(bytes)
|| super::pcxread::is_pcx(bytes)
}
/// Decode an image's header (and, for formats stored as PNG, its pixels). CMYK TIFFs are kept as
/// they are, with their ink amounts ([`ImageBlob::cmyk`]), except that ones storing one plane per
/// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]);
+11 -1
View File
@@ -2392,7 +2392,17 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
}
}
// Read before it is copied: a file that can't be shown isn't copied.
let img = if images.is_empty() { None } else { Some(linked_image(&bytes, Some(&path)).map_err(|e| bad(C, format!("{path}: {e}")))?) };
let img = if images.is_empty() {
None
} else {
Some(linked_image(&bytes, Some(&path)).map_err(|e| {
// A file in no image format; a damaged image keeps its own error.
if s.image_only.get().is_some() && !fileio::is_raster_image(&bytes) && !super::place::dcs::is_dcs(&bytes) {
s.image_only.set(Some(false));
}
bad(C, format!("{path}: {e}"))
})?)
};
// A copy beside the document would point at plate files it can't find there.
if copy_to.is_some() && img.as_ref().is_some_and(|img| !img.blob.plate_files().is_empty()) {
return Err(bad(C, format!("{path}: copy takes a DCS file only when its plates are inside it; relink to it where its plate files are")));
+9
View File
@@ -841,6 +841,15 @@ fn place(s: &mut Session, p: &Value) -> Result<Value> {
Some(read) => read,
None => prepare(s, p)?.read()?,
};
let image = match read.loaded.art {
Art::Image(..) => read.loaded.link.is_some(),
Art::Dcs(_) => true,
_ => false,
};
if s.image_only.get().is_some() && !image {
s.image_only.set(Some(false));
return Err(bad(PLACE, "the file is not an image"));
}
apply(s, read)
}
+4
View File
@@ -328,6 +328,10 @@ pub struct Session {
/// While [`Session::place_read`] runs `file.place`: the file read for it, which the command
/// places instead of reading the file; `None` otherwise.
pub(crate) place_hand_off: Option<cmd::place::PlaceRead>,
/// While a script places or relinks a file as an image: `Some(true)`, and `file.place` or
/// `links.relink` refuses a file that holds no image before the document changes, setting it to
/// `Some(false)`; `None` otherwise.
pub(crate) image_only: std::cell::Cell<Option<bool>>,
/// While [`Session::place_queue_read`] runs `file.place.queue`: the files read for it, which
/// the command loads the place cursor with instead of reading them; `None` otherwise.
pub(crate) queue_hand_off: Option<cmd::place::QueueRead>,
+18 -10
View File
@@ -302,8 +302,8 @@ fn may_read(h: &Host, path: &str) -> bool {
/// The real path of the `File` `d` gives as an image to place or relink: one the script may read
/// ([`super::super::files::Disk::open_target`], as `app.open` reads its file), a regular file of
/// at most [`MAX_PLACED_BYTES`] that holds an image. Its size is read before any of it is, and no
/// error names the path.
/// at most [`MAX_PLACED_BYTES`]. Its size is read before any of it is, and no error names the path.
/// What the file holds is checked by the command that places or relinks it, which reads it once.
fn image_path(h: &Host, d: &Data, what: &str) -> Result<String, HostError> {
let path = file_ref_path(d).ok_or_else(|| HostError::Type(format!("{what} must be a File")))?;
if path.len() > super::super::files::MAX_PATH_CHARS {
@@ -321,13 +321,21 @@ fn image_path(h: &Host, d: &Data, what: &str) -> Result<String, HostError> {
if meta.len() > MAX_PLACED_BYTES {
return Err(HostError::Range(format!("{what} is larger than {} MiB", MAX_PLACED_BYTES >> 20)));
}
let path = crate::cmd::findfiles::plain(real).to_string_lossy().into_owned();
// What the file holds, read the way `file.place` reads it, before the document changes.
let info = command(h, "file.place.info", &json!({"path": path, "link": true}))?;
if field(&info, "pixelWidth").is_none() {
return Err(HostError::Error(NOT_AN_IMAGE.into()));
Ok(crate::cmd::findfiles::plain(real).to_string_lossy().into_owned())
}
/// Runs `f`, which places or relinks a file `image_path` gave, with `file.place` and `links.relink`
/// refusing a file that holds no image before the document changes: that refusal is
/// [`NOT_AN_IMAGE`], which does not name the path. The command reads the file once, for its check
/// and for the image it places.
fn image_only<T>(h: &Host, f: impl FnOnce(&Host) -> Result<T, HostError>) -> Result<T, HostError> {
let kept = h.session.borrow().image_only.replace(Some(true));
let r = f(h);
let refused = h.session.borrow().image_only.replace(kept) == Some(false);
match r {
Err(HostError::Error(_)) if refused => Err(HostError::Error(NOT_AN_IMAGE.into())),
r => r,
}
Ok(path)
}
// ---- PlacedItem ----
@@ -397,7 +405,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer {
// The placement and its check run under one savepoint, so an error after the place leaves
// no linked image behind.
let id = super::atomically(h, |h| {
let (_, placed) = on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true})))?;
let (_, placed) = image_only(h, |h| on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true}))))?;
let first = |v: &serde_json::Value| v.as_u64().or_else(|| v.as_array().and_then(|a| a.first()).and_then(serde_json::Value::as_u64));
let id = first(&placed["image"]).or_else(|| first(&placed["ids"])).map(NodeId);
let linked =
@@ -414,7 +422,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer {
fn placed_relink(h: &Host, a: &[Data]) -> Answer {
let item = this_of(h, a, "PlacedItem")?;
let path = image_path(h, arg(a, 1), "relink's file")?;
edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path}))?;
image_only(h, |h| edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path})))?;
Ok(Data::Undefined)
}
+1
View File
@@ -143,6 +143,7 @@ impl Session {
composite_names_registered: HashSet::new(),
reading: false,
place_hand_off: None,
image_only: std::cell::Cell::new(None),
queue_hand_off: None,
place_queue_roots: None,
place_queue_loads: 0,
@@ -287,6 +287,45 @@ fn a_file_that_is_not_an_image_is_refused_before_placing() {
let _ = std::fs::remove_dir_all(base);
}
/// How many times the engine read the file at `path` on this thread since the last call.
#[cfg(not(target_arch = "wasm32"))]
fn reads_of(path: &Path) -> usize {
let path = path.to_string_lossy();
crate::cmd::fileio::FILES_READ.with(|r| r.take().iter().filter(|p| plain_path(p) == path).count())
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn placing_or_relinking_from_a_script_reads_the_file_once() {
let base = folder("read-once");
let (a, b) = (base.join("main/a.png"), base.join("main/b.png"));
std::fs::write(&a, gray_png(10, 10)).unwrap();
std::fs::write(&b, gray_png(20, 10)).unwrap();
let mut s = session();
reads_of(&a);
log(&mut s, &base, &format!("app.activeDocument.placedItems.add().file = new File('{}');", js_path(&a)));
assert_eq!(reads_of(&a), 1, "placing reads the file once");
log(&mut s, &base, &format!("app.activeDocument.placedItems[0].relink(new File('{}'));", js_path(&b)));
assert_eq!(reads_of(&b), 1, "relinking reads the file once");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn relinking_to_a_file_that_is_not_an_image_keeps_the_link() {
let base = folder("relink-text");
let (a, notes) = (base.join("main/a.png"), base.join("main/notes.txt"));
std::fs::write(&a, gray_png(10, 10)).unwrap();
std::fs::write(&notes, "hello").unwrap();
let mut s = session();
let id = place(&mut s, &a, true);
let before = undo_steps(&s);
let e = failure(&mut s, &base, &format!("app.activeDocument.placedItems[0].relink(new File('{}'));", js_path(&notes)));
assert!(e.contains("The file is not an image") && !e.contains("notes.txt"), "{e}");
assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]);
assert_eq!(undo_steps(&s), before);
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn placed_items_add_is_bounded() {
let base = folder("pending");