Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Links: an unchanged linked image is not read again on every poll (#2164)

Paul Gemignani7d0f141b52af
diff --git a/crates/engine/src/cmd/interchange.rs b/crates/engine/src/cmd/interchange.rs
index 4ca22309c..32c87d9f5 100644
--- a/crates/engine/src/cmd/interchange.rs
+++ b/crates/engine/src/cmd/interchange.rs
@@ -525,7 +525,7 @@ mod tests {
assert_eq!(*asset.data, png, "the packaged graphic must render even when its author-machine path no longer exists");
let resolved = std::path::absolute(&path).unwrap();
assert_eq!(asset.link.as_deref(), resolved.to_str(), "remember the resolved link so update and preflight use the packaged file");
- assert_eq!(super::super::links::status(asset, None), "ok");
+ assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "ok");
std::fs::remove_dir_all(dir).unwrap();
}
@@ -542,7 +542,7 @@ mod tests {
let asset = doc.assets.values().next().unwrap();
assert_eq!(*asset.data, png);
assert_eq!(asset.link.as_deref(), std::path::absolute(&path).unwrap().to_str());
- assert_eq!(super::super::links::status(asset, None), "ok");
+ assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "ok");
std::fs::remove_dir_all(dir).unwrap();
}
@@ -558,7 +558,7 @@ mod tests {
let asset = doc.assets.values().next().unwrap();
assert_eq!(*asset.data, png);
assert_eq!(asset.link.as_deref(), std::path::absolute(&path).unwrap().to_str());
- assert_eq!(super::super::links::status(asset, None), "ok");
+ assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "ok");
std::fs::remove_dir_all(dir).unwrap();
}
@@ -578,7 +578,7 @@ mod tests {
let asset = doc.assets.values().next().unwrap();
assert_eq!(std::path::Path::new(asset.link.as_deref().unwrap()), original.as_path(), "an existing original stays authoritative");
assert_eq!(*asset.data, png);
- assert_eq!(super::super::links::status(asset, None), "modified");
+ assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "modified");
std::fs::remove_file(&original).unwrap();
std::fs::write(&copy, b"modified packaged copy").unwrap();
@@ -586,7 +586,7 @@ mod tests {
let asset = doc.assets.values().next().unwrap();
assert_eq!(asset.link.as_deref(), copy.to_str());
assert_eq!(*asset.data, png, "rebinding must not replace embedded pixels");
- assert_eq!(super::super::links::status(asset, None), "modified");
+ assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "modified");
std::fs::remove_file(&copy).unwrap();
let packaged = package.join("x.idml");
@@ -595,7 +595,7 @@ mod tests {
let asset = doc.assets.values().next().unwrap();
assert_eq!(std::path::Path::new(asset.link.as_deref().unwrap()), original.as_path(), "keep a missing link when there is no candidate");
assert_eq!(*asset.data, png);
- assert_eq!(super::super::links::status(asset, None), "missing");
+ assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "missing");
}
let oversized = "a/".repeat(MAX_LINK_PATH_BYTES);
assert!(packaged_link_candidates(&oversized, Some(&packaged)).is_empty());
@@ -643,7 +643,7 @@ mod tests {
assert!(seen.iter().all(|p| p.starts_with(&dir) || itself.as_ref() == Some(p)), "{link}: {seen:?}");
let asset = doc.assets.values().next().unwrap();
assert!(asset.data.is_empty(), "{link}");
- assert_eq!(super::super::links::status(asset, None), "missing", "{link}");
+ assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "missing", "{link}");
}
// An image elsewhere on this computer is read, and so is one beside the package.
let away = outside.join("logo.png");
@@ -652,7 +652,7 @@ mod tests {
let doc = import(&idml, Some(&package)).unwrap();
let asset = doc.assets.values().next().unwrap();
assert_eq!((&*asset.data, asset.link.as_deref()), (&png, away.to_str()));
- assert_eq!(super::super::links::status(asset, None), "ok");
+ assert_eq!(super::super::links::status_cached(asset, None, &mut Default::default()), "ok");
std::fs::write(dir.join("Links").join("logo.png"), &png).unwrap();
let (idml, _) = linked_idml("Links/logo.png", false).unwrap();
let doc = import(&idml, Some(&package)).unwrap();
diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs
index 4f5368af6..1ad60b30f 100644
--- a/crates/engine/src/cmd/links.rs
+++ b/crates/engine/src/cmd/links.rs
@@ -27,8 +27,10 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(query "links.list", "Links", [], None, "{} → [{asset, name, path, status: ok|modified|missing|embedded, refused?: why a missing link isn't followed (a path on another computer, a device), pixels, pdfCrop (placed PDFs: the box shown), uses: [{id, page, ppi}]}], then linked text files: [{story, name, path, status (also tooLarge: unchanged size, too big to check), edited (the story was changed in the layout), uses: [{id, page}]}]", has_doc, |s, _| {
// Taken out for the call so the document needn't be cloned on every poll.
let mut checks = std::mem::take(&mut s.text_link_checks);
- let links = s.doc().map(|d| list(&d.doc, &s.cache, d.path.as_deref().map(Path::new), &mut checks));
+ let mut images = std::mem::take(&mut s.image_link_checks);
+ let links = s.doc().map(|d| list(&d.doc, &s.cache, d.path.as_deref().map(Path::new), &mut checks, &mut images));
s.text_link_checks = checks;
+ s.image_link_checks = images;
Ok(Value::Array(links?))
}),
cmd!(
@@ -137,7 +139,7 @@ pub fn refused(link: &str, document: Option<&Path>) -> Option<crate::io::Refused
crate::io::document_path(link, document).err()
}
-/// Whether an asset's linked file is gone ([`status`] "missing" without reading the file). An
+/// Whether an asset's linked file is gone ([`status_cached`] "missing" without reading the file). An
/// asset can hold data while its file is missing: the document's preview of it. `document` is
/// the document's file, which relative links are resolved against.
pub fn link_missing(a: &designcraft_doc::Asset, document: Option<&Path>) -> bool {
@@ -155,7 +157,18 @@ pub fn link_missing(a: &designcraft_doc::Asset, document: Option<&Path>) -> bool
/// Link status of an asset in the document at `document`. Only a regular file is compared, so a
/// link to a device (`/dev/zero`) or a FIFO is missing rather than read.
-pub fn status(a: &designcraft_doc::Asset, document: Option<&Path>) -> &'static str {
+/// Linked images checked this session: (asset, the identity of its bytes, link) → (the file's size
+/// and time when it was read, whether it matched the bytes). The bytes' identity (their `Arc`'s
+/// address, as the render cache keys them) changes with every relink, update or undo, so a
+/// remembered answer can never describe other bytes.
+pub(crate) type ImageChecks = std::collections::HashMap<(AssetId, usize, String), (Fingerprint, bool)>;
+
+/// Link status of a placed graphic (`ok`, `modified`, `missing`, `embedded`), reading the file
+/// only when its size is the asset's and its time isn't the one remembered from the last read
+/// (`checks`): the Links panel polls twice a second, and a document
+/// of press-size images would otherwise be read whole on every poll. A file changed in the last
+/// two seconds is never remembered (see [`settled`]).
+pub(crate) fn status_cached(a: &designcraft_doc::Asset, document: Option<&Path>, checks: &mut ImageChecks) -> &'static str {
let Some(link) = &a.link else { return "embedded" };
// Nothing was read from the file (a package's link that wasn't followed): missing, as in
// Preflight.
@@ -168,20 +181,32 @@ pub fn status(a: &designcraft_doc::Asset, document: Option<&Path>) -> &'static s
if !crate::io::is_file(&path) {
return "missing";
}
- match crate::io::metadata(&path) {
- Err(_) => "missing",
- Ok(m) if m.len() as usize != a.data.len() => "modified",
- // Same size: compare the bytes (cheap for the sizes involved, and exact).
- Ok(_) => match crate::io::read_capped(&path, a.data.len() as u64) {
- Ok(b) if b == *a.data => "ok",
- Ok(_) => "modified",
- Err(_) => "missing",
- },
+ let now = match crate::io::metadata(&path) {
+ Err(_) => return "missing",
+ Ok(m) => super::datamerge::fingerprint_from(&m),
+ };
+ if now.size != a.data.len() as u64 {
+ return "modified";
+ }
+ let key = (a.id, Arc::as_ptr(&a.data) as usize, link.clone());
+ if let Some((at, same)) = checks.get(&key)
+ && *at == now
+ {
+ return if *same { "ok" } else { "modified" };
+ }
+ let same = match crate::io::read_capped(&path, a.data.len() as u64) {
+ Ok(b) => b == *a.data,
+ Err(_) => return "missing",
+ };
+ // The time from before the read: a change during it is seen next time.
+ if settled(&now) {
+ checks.insert(key, (now, same));
}
+ if same { "ok" } else { "modified" }
}
#[cfg(target_arch = "wasm32")]
{
- let _ = (link, document);
+ let _ = (link, document, checks);
"ok"
}
}
@@ -317,7 +342,9 @@ fn shown<'a>(d: &'a Document, cache: &Cache, aid: AssetId) -> Vec<Shown<'a>> {
out
}
-fn list(d: &Document, cache: &Cache, document: Option<&Path>, checks: &mut TextChecks) -> Vec<Value> {
+/// `links.list`: every used placed graphic, then every linked text file, each with its status
+/// (`images` and `checks` remember what was read this session, so a poll reads nothing unchanged).
+fn list(d: &Document, cache: &Cache, document: Option<&Path>, checks: &mut TextChecks, images: &mut ImageChecks) -> Vec<Value> {
let texts = d.stories.values().filter_map(|st| {
let l = st.file_link.as_ref()?;
let uses: Vec<Value> = st.frames.iter().map(|id| json!({"id": id.0, "page": d.page_of_item(*id).map(|p| d.page_name(p))})).collect();
@@ -350,7 +377,7 @@ fn list(d: &Document, cache: &Cache, document: Option<&Path>, checks: &mut TextC
.collect();
let pdf_crop = (a.mime == "application/pdf").then(|| a.pdf_crop.name());
let why = a.link.as_deref().and_then(|l| refused(l, document)).map(|r| r.to_string());
- json!({"asset": a.id.0, "name": a.name, "path": a.link, "status": status(a, document), "refused": why, "pixels": a.pixels, "pdfCrop": pdf_crop, "uses": uses})
+ json!({"asset": a.id.0, "name": a.name, "path": a.link, "status": status_cached(a, document, images), "refused": why, "pixels": a.pixels, "pdfCrop": pdf_crop, "uses": uses})
})
.chain(texts)
.collect()
@@ -450,6 +477,7 @@ fn relinked_asset(a: &designcraft_doc::Asset, read: &Path, link: &str) -> Result
Ok(Arc::new(a))
}
+/// `links.relink`: a placed graphic or linked text file takes its bytes from `path` from now on.
fn relink(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("links.relink", "missing path"))?.to_string();
if let Some(sid) = story_param(p) {
@@ -464,13 +492,17 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
let a = s.doc()?.doc.assets.get(&aid).ok_or_else(|| bad("links.relink", "no such graphic"))?;
// Build the replacement before the edit: a file that cannot be read leaves the document as it was.
let fresh = relinked_asset(a, Path::new(&path), &path)?;
- s.edit(|d, _| {
+ let r = s.edit(|d, _| {
let name = fresh.name.clone();
d.assets.insert(aid, fresh);
Ok(json!({"name": name}))
- })
+ });
+ s.image_link_checks.clear();
+ r
}
+/// `links.relinkFolder`: relink graphics to same-named files in a folder and/or with another
+/// extension (the missing ones by default).
fn relink_folder(s: &mut Session, p: &Value) -> Result<Value> {
let dir = str_param(p, "dir").map(std::path::PathBuf::from);
if let Some(dir) = &dir {
@@ -486,12 +518,13 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result<Value> {
}
let missing_only = p.get("missingOnly").and_then(Value::as_bool).unwrap_or(dir.is_some() && ext.is_none());
let only: Option<Vec<u64>> = p.get("assets").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect());
+ let mut images = std::mem::take(&mut s.image_link_checks);
let st = s.doc()?;
let (d, document) = (&st.doc, st.path.as_deref().map(Path::new));
let mut todo: Vec<(AssetId, std::path::PathBuf)> = Vec::new();
let mut not_found = Vec::new();
for a in d.assets.values() {
- if only.as_ref().is_some_and(|o| !o.contains(&a.id.0)) || (missing_only && status(a, document) != "missing") {
+ if only.as_ref().is_some_and(|o| !o.contains(&a.id.0)) || (missing_only && status_cached(a, document, &mut images) != "missing") {
continue;
}
let old = std::path::PathBuf::from(a.link.clone().unwrap_or_else(|| a.name.clone()));
@@ -538,10 +571,13 @@ fn relink_folder(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(())
})?;
+ images.clear();
}
+ s.image_link_checks = images;
Ok(json!({"relinked": n, "notFound": not_found}))
}
+/// `links.update`: re-read the modified links (one, or every one) from where they resolve.
fn update(s: &mut Session, p: &Value) -> Result<Value> {
let (d, document) = {
let st = s.doc()?;
@@ -549,6 +585,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
};
let document = document.as_deref().map(Path::new);
let checks = &mut s.text_link_checks;
+ let images = &mut s.image_link_checks;
let (only_asset, only_story) = (p.get("asset").and_then(Value::as_u64), story_param(p));
let all = only_asset.is_none() && only_story.is_none();
// A link craft-docpath refuses is missing, so it is never read or refreshed.
@@ -563,7 +600,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
})
.collect();
let mut fresh = Vec::new();
- for a in d.assets.values().filter(|a| all || only_asset == Some(a.id.0)).filter(|a| status(a, document) == "modified") {
+ for a in d.assets.values().filter(|a| all || only_asset == Some(a.id.0)).filter(|a| status_cached(a, document, images) == "modified") {
// The bytes come from where the stored link resolves; the link itself stays as the
// document stored it, so refreshing never rewrites a relative link to an absolute one.
if let Some((link, at)) = a.link.as_deref().and_then(|l| resolved(l).map(|at| (l, at))) {
@@ -579,7 +616,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
if n == 0 {
return Ok(json!({"updated": 0}));
}
- s.edit(|d, _| {
+ let r = s.edit(|d, _| {
for (aid, a) in fresh {
d.assets.insert(aid, a);
}
@@ -588,7 +625,9 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
warnings.extend(reimport(d, *sid, path, bytes, *before)?);
}
Ok(json!({"updated": n, "warnings": warnings}))
- })
+ });
+ s.image_link_checks.clear();
+ r
}
#[cfg(test)]
diff --git a/crates/engine/src/cmd/links/tests.rs b/crates/engine/src/cmd/links/tests.rs
index 8089b24ce..c3391b333 100644
--- a/crates/engine/src/cmd/links/tests.rs
+++ b/crates/engine/src/cmd/links/tests.rs
@@ -4,6 +4,78 @@ fn png(w: u32, h: u32) -> Vec<u8> {
designcraft_render::Rendered { width: w, height: h, pixels: vec![200u8; (w * h * 4) as usize] }.to_png()
}
+/// The Links panel polls `links.list` twice a second: a linked image whose file keeps its size
+/// and time is not read again (press-size images would otherwise be read whole on every poll).
+/// A new time is read once; changed bytes show as modified; an update is remembered.
+#[cfg(all(unix, not(target_arch = "wasm32")))]
+#[test]
+fn unchanged_linked_images_are_not_read_again() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = std::env::temp_dir().join(format!("dc-image-link-poll-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("photo.png");
+ // Two valid images of the same byte length (a uniform fill compresses to the same size
+ // whatever its value), so a change shows only in the bytes.
+ let a = png(40, 40);
+ let b = designcraft_render::Rendered { width: 40, height: 40, pixels: vec![100u8; 40 * 40 * 4] }.to_png();
+ assert_eq!(a.len(), b.len(), "the test needs two files of one size");
+ assert_ne!(a, b);
+ std::fs::write(&path, &a).unwrap();
+ // Unreadable: a status that reads the file would say missing.
+ let readable = |on: bool| std::fs::set_permissions(&path, std::fs::Permissions::from_mode(if on { 0o644 } else { 0o000 })).unwrap();
+ // A time `secs` ago (a file changed in the last two seconds is always read).
+ let touch = |secs: u64| {
+ let f = std::fs::File::options().write(true).open(&path).unwrap();
+ f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(secs)).unwrap();
+ };
+ touch(60);
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true})).unwrap();
+ let status = |s: &mut Session| {
+ let l = s.execute("links.list", &json!({})).unwrap();
+ l.as_array().unwrap().iter().find(|r| r.get("asset").is_some()).unwrap()["status"].as_str().unwrap().to_string()
+ };
+
+ // First poll reads and remembers; the second doesn't read.
+ assert_eq!(status(&mut s), "ok");
+ readable(false);
+ if std::fs::read(&path).is_ok() {
+ // Running as root: permissions don't stop reads, so this can't be observed.
+ let _ = std::fs::remove_dir_all(&dir);
+ return;
+ }
+ assert_eq!(status(&mut s), "ok", "same size and time: not read");
+ // Saved again unchanged (a new time): read once, then not again.
+ readable(true);
+ touch(30);
+ assert_eq!(status(&mut s), "ok");
+ readable(false);
+ assert_eq!(status(&mut s), "ok", "the second poll doesn't read it");
+ // Changed, same size, new time: modified — and remembered, not re-read.
+ readable(true);
+ std::fs::write(&path, &b).unwrap();
+ touch(20);
+ assert_eq!(status(&mut s), "modified");
+ readable(false);
+ assert_eq!(status(&mut s), "modified", "a modified answer is remembered too");
+ // Updated: the document's bytes are the file's, so the next poll reads once and says ok.
+ readable(true);
+ assert_eq!(s.execute("links.update", &json!({})).unwrap()["updated"], 1);
+ assert_eq!(status(&mut s), "ok");
+ readable(false);
+ assert_eq!(status(&mut s), "ok", "remembered after the update");
+ // A different size needs no read at all.
+ readable(true);
+ std::fs::write(&path, png(41, 41)).unwrap();
+ touch(10);
+ readable(false);
+ assert_eq!(status(&mut s), "modified", "size differs: decided from metadata");
+ readable(true);
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
/// A linked file's size is the document's choice, so a link is read under a cap (#1596).
#[cfg(not(target_arch = "wasm32"))]
#[test]
@@ -154,7 +226,7 @@ fn eps_status_tracks_source_bytes_across_save_update_relink_and_embed() {
std::fs::remove_file(&replacement).unwrap();
let embedded = designcraft_format::load(&designcraft_format::save(&s.doc().unwrap().doc).unwrap()).unwrap();
// The asset is embedded, so no link is followed and the document is irrelevant.
- assert_eq!(status(&embedded.assets[&aid], None), "embedded");
+ assert_eq!(status_cached(&embedded.assets[&aid], None, &mut Default::default()), "embedded");
assert_eq!(embedded.assets[&aid].data.as_slice(), changed);
assert!(designcraft_render::decode_pixmap(&embedded.assets[&aid].data).is_some());
let _ = std::fs::remove_dir_all(dir);
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index f42dc5b13..aee87f2ee 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -435,6 +435,9 @@ pub struct Session {
/// Linked text files checked by the Links panel: path → the size and modification time the
/// file had and the hash of its contents then, so a file touched but not changed is read once.
pub(crate) text_link_checks: std::collections::HashMap<String, (designcraft_doc::Fingerprint, String)>,
+ /// Linked images checked against their files this session (`links.list` polls twice a second):
+ /// a file of the recorded size and time isn't read again.
+ pub(crate) image_link_checks: std::collections::HashMap<(designcraft_doc::AssetId, usize, String), (designcraft_doc::Fingerprint, bool)>,
}
impl Default for Session {
@@ -467,6 +470,7 @@ impl Session {
recovery_dir: None,
text_clipboard: None,
text_link_checks: Default::default(),
+ image_link_checks: Default::default(),
ui_requests: vec![],
loaded: None,
transforms: Default::default(),