PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Linked smart objects: follow stored paths only to local files or the document's share
aiongg87918a6c850b
diff --git a/Cargo.lock b/Cargo.lockindex 138ca3d81..e1206c227 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1222,6 +1222,10 @@ dependencies = ["libc",]+[[package]]+name = "craft-docpath"+version = "0.1.0"+[[package]]name = "craft-print"version = "0.1.0"@@ -4869,6 +4873,7 @@ name = "photocraft-io"version = "0.9.0"dependencies = ["blake3",+ "craft-docpath","crc32fast","flate2","photocraft-affinity",diff --git a/Cargo.toml b/Cargo.tomlindex 0d0f93ae7..f215b0d04 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -39,6 +39,7 @@ photocraft-tablet = { path = "crates/tablet" }# externalcraft-print = { git = "https://github.com/storytold/craft-libs", rev = "3d37da389a3618ab9b76109da11416e9ca4ea719" }+craft-docpath = { path = "../secfix-craft-libs/crates/docpath" }thiserror = "2"serde = { version = "1", features = ["derive", "rc"] }serde_json = "1"diff --git a/crates/engine/src/doc_path.rs b/crates/engine/src/doc_path.rsnew file mode 100644index 000000000..b51d164e7--- /dev/null+++ b/crates/engine/src/doc_path.rs@@ -0,0 +1,58 @@+//! Paths stored in a document reach the file system only through [`resolve`] (built on+//! [`photocraft_io::doc_path::resolve`]): linked smart objects, the Displace map and Color Lookup+//! file a smart filter re-reads, data-set images and video footage. A refused path is handled like+//! a missing file: the layer keeps its last rendering, and commands that need the file say why.+//!+//! Smart-object rendering has no `Session` argument, so the path of the document being worked on+//! travels in a thread-local scope, entered where commands run ([`crate::Session::edit`], command+//! dispatch, background jobs). Outside a scope there is no document: relative paths are refused+//! and only local absolute paths are followed.++use std::cell::RefCell;+use std::path::{Path, PathBuf};++pub use photocraft_io::doc_path::NotFollowed;++thread_local! {+ static DOCUMENT: RefCell<Option<PathBuf>> = const { RefCell::new(None) };+}++/// Restores the previous document path when dropped.+pub(crate) struct DocumentScope(Option<PathBuf>);++impl Drop for DocumentScope {+ fn drop(&mut self) {+ let previous = self.0.take();+ DOCUMENT.with(|d| *d.borrow_mut() = previous);+ }+}++/// Resolve stored paths against `document` (the path of the document being worked on, `None`+/// for one without a file) until the returned scope is dropped.+pub(crate) fn scope(document: Option<&Path>) -> DocumentScope {+ let next = document.filter(|d| !d.as_os_str().is_empty()).map(Path::to_path_buf);+ DocumentScope(DOCUMENT.with(|d| d.replace(next)))+}++/// The document path of the current scope (to carry it to another thread).+pub(crate) fn current() -> Option<PathBuf> {+ DOCUMENT.with(|d| d.borrow().clone())+}++/// The file to open for `stored`, a path stored in the document of the current scope.+pub fn resolve(stored: &str) -> Result<PathBuf, NotFollowed> {+ resolve_in(stored, current().as_deref())+}++/// The file to open for `stored`, a path stored in the document saved at `document`.+pub fn resolve_in(stored: &str, document: Option<&Path>) -> Result<PathBuf, NotFollowed> {+ photocraft_io::doc_path::resolve(stored, document)+}++/// The message for a stored path that is not followed.+pub(crate) fn refusal(what: &str, stored: &str, why: NotFollowed) -> crate::EngineError {+ crate::EngineError::Other(format!("{what} {stored} is not opened: {why}"))+}++#[cfg(test)]+mod tests;diff --git a/crates/engine/src/doc_path/tests.rs b/crates/engine/src/doc_path/tests.rsnew file mode 100644index 000000000..6b8657911--- /dev/null+++ b/crates/engine/src/doc_path/tests.rs@@ -0,0 +1,129 @@+//! Each kind of place that follows a path stored in a document goes through [`super::resolve`]: a+//! link to another computer is never followed, and a relative link next to the document is.++use std::path::{Path, PathBuf};++use photocraft_doc::{LayerContent, LayerId, SmartSource};+use photocraft_geom::Rect;+use serde_json::json;++use crate::Session;++/// A link to a share on a TEST-NET-1 address, which never answers.+const REMOTE: &str = r"\\192.0.2.1\share\x.png";++/// An empty folder of its own (tests run in parallel).+fn dir(name: &str) -> PathBuf {+ let d = std::env::temp_dir().join(format!("photocraft-doc-path-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ d+}++/// A 32×32 PNG whose pixel at column `x` is `rgb(x)`.+fn png(path: &Path, rgb: impl Fn(u32) -> [u8; 3]) {+ let mut px = Vec::new();+ for _ in 0..32 {+ for x in 0..32 {+ px.extend(rgb(x));+ }+ }+ let image = photocraft_codecs::Image::from_u8(32, 32, photocraft_codecs::ChannelLayout::Rgb, px).unwrap();+ std::fs::write(path, photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap();+}++/// On Unix `//` followed by an absolute path names that same local file, while the resolver sees a+/// path on another computer: a place that skipped the resolver would read the file.+#[cfg(unix)]+fn network_alias(p: &Path) -> String {+ format!("/{}", p.display())+}++/// A 32×32 white document saved (as far as its links know) at `d/doc.pcraft`, with `file` placed+/// linked → (session, layer id).+fn document(d: &Path, file: &Path) -> (Session, LayerId) {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 32, "height": 32})).unwrap();+ s.active_mut().unwrap().path = Some(d.join("doc.pcraft").to_string_lossy().into_owned());+ s.execute("file.placeLinked", json!({"path": file.to_string_lossy()})).unwrap();+ let id = s.active().unwrap().active_layer.unwrap();+ (s, id)+}++/// Point smart object `id` at `path` without re-rendering it.+fn relink(s: &mut Session, id: LayerId, path: &str) {+ s.edit("Relink", |doc, _| {+ if let Some(LayerContent::Smart(sm)) = doc.layer_mut(id).map(|l| &mut l.content) {+ sm.source = SmartSource::Linked { path: path.into() };+ }+ Ok(())+ })+ .unwrap();+}++fn centre(s: &Session) -> [f32; 3] {+ let p = photocraft_compose::render(&s.active().unwrap().doc, Rect::new(16, 16, 17, 17)).px[0];+ [p[0], p[1], p[2]]+}++const RED: [f32; 3] = [1.0, 0.0, 0.0];+const BLUE: [f32; 3] = [0.0, 0.0, 1.0];++fn update(s: &mut Session) -> Result<serde_json::Value, String> {+ s.execute("layer.smartObjects.updateModifiedContent", json!({})).map_err(|e| e.to_string())+}++#[test]+fn linked_smart_objects_follow_only_local_files() {+ let d = dir("links");+ png(&d.join("red.png"), |_| [255, 0, 0]);+ png(&d.join("blue.png"), |_| [0, 0, 255]);+ let (mut s, id) = document(&d, &d.join("red.png"));+ assert_eq!(centre(&s), RED);++ relink(&mut s, id, REMOTE);+ s.start_link_scan();+ assert!(s.link_scan.is_none(), "no look at a file on another computer");+ assert_eq!(s.execute("layer.smartObjects.updateChanged", json!({})).unwrap(), json!({"updated": []}));+ let err = update(&mut s).unwrap_err();+ assert!(err.contains("is not opened: the path is on another computer"), "{err}");+ assert_eq!(centre(&s), RED, "the layer keeps its rendering");+ #[cfg(unix)]+ {+ relink(&mut s, id, &network_alias(&d.join("blue.png")));+ assert!(update(&mut s).is_err());+ assert_eq!(centre(&s), RED, "the file was not read");+ }++ // A relative link is taken from the document's folder.+ relink(&mut s, id, "blue.png");+ update(&mut s).unwrap();+ assert_eq!(centre(&s), BLUE);+ s.start_link_scan();+ assert!(s.link_scan.is_some(), "a followed link is looked at");+}++#[test]+fn package_copies_only_followed_links() {+ let d = dir("package");+ png(&d.join("red.png"), |_| [255, 0, 0]);+ let (mut s, id) = document(&d, &d.join("red.png"));+ relink(&mut s, id, "red.png");+ #[allow(unused_mut)]+ let mut remote = vec![REMOTE.to_string()];+ #[cfg(unix)]+ remote.push(network_alias(&d.join("red.png")));+ for path in &remote {+ s.execute("file.placeLinked", json!({"path": d.join("red.png").to_string_lossy()})).unwrap();+ let other = s.active().unwrap().active_layer.unwrap();+ relink(&mut s, other, path);+ }+ let r = s.execute("file.package", json!({"dir": d.join("pkg").to_string_lossy()})).unwrap();+ let mut missing: Vec<String> = serde_json::from_value(r["missing"].clone()).unwrap();+ missing.sort();+ remote.sort();+ assert_eq!(missing, remote);+ let links = r["links"].as_array().unwrap();+ assert_eq!(links.len(), 1);+ assert!(links[0].as_str().unwrap().ends_with("red.png"), "{links:?}");+}diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rsindex 43828b76b..d9eb4d10c 100644--- a/crates/engine/src/file_cmds.rs+++ b/crates/engine/src/file_cmds.rs@@ -578,7 +578,16 @@ fn place(s: &mut Session, p: &Value, linked: bool) -> Result<Value> {let cmd = if linked { "file.placeLinked" } else { "file.placeEmbedded" };let path = str_param(p, "path", cmd)?.to_string();let bytes = read_file(&path)?;- place_bytes(s, &path, bytes, linked.then(|| path.clone()), p)+ // The link is stored absolute: a relative one would later be taken from the document's+ // folder (`doc_path`), not the working directory the path was given in.+ let link = linked.then(|| {+ if std::path::Path::new(&path).is_relative() {+ std::path::absolute(&path).map_or_else(|_| path.clone(), |a| a.to_string_lossy().into_owned())+ } else {+ path.clone()+ }+ });+ place_bytes(s, &path, bytes, link, p)}// ---------- File Info (XMP) ----------diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rsindex 3cc72c30c..624edfdd3 100644--- a/crates/engine/src/file_cmds/tests.rs+++ b/crates/engine/src/file_cmds/tests.rs@@ -1033,7 +1033,7 @@ fn reveal_in_finder_reveals_the_documents_saved_path() {let path = "/tmp/pics/a.psd";s.active_mut().unwrap().path = Some(path.into());let r = s.execute("file.revealInFinder", json!({"dryRun": true})).unwrap();- let (program, args) = crate::layer_menu_cmds::reveal_command(path);+ let (program, args) = crate::layer_menu_cmds::reveal_command(path).unwrap();assert_eq!(r["program"], json!(program));assert_eq!(r["args"], json!(args));// The tab menu names a background tab: the active document is not the one revealed.diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rsindex de2afd155..0e9569d71 100644--- a/crates/engine/src/jobs.rs+++ b/crates/engine/src/jobs.rs@@ -323,6 +323,9 @@ pub fn run<T: Send + 'static>() -> Result<Value> {let authorization = s.authorize.or_else(|| RENDER_AUTHORIZATION.with(std::cell::Cell::get));let _authorization = AuthorizationScope::enter(authorization);+ // The job's document: stored paths it follows are resolved against it on any thread.+ let document = s.active().and_then(|d| d.path.as_deref()).map(std::path::PathBuf::from);+ let _document = crate::doc_path::scope(document.as_deref());if !s.jobs.spawn || cfg!(target_arch = "wasm32") {let t = work(&s.jobs.inline.clone().unwrap_or_default())?;return apply(s, t);@@ -337,8 +340,10 @@ pub fn run<T: Send + 'static>(};let ctx = JobCtx::new();let (tx, rx) = std::sync::mpsc::channel::<Result<Payload>>();+ let apply_document = document.clone();let erased: Apply = Box::new(move |s, any| {let _authorization = AuthorizationScope::enter(authorization);+ let _document = crate::doc_path::scope(apply_document.as_deref());let t = any.downcast::<T>().map_err(|_| EngineError::Other("internal error: job result type mismatch".into()))?;apply(s, *t)});@@ -352,6 +357,7 @@ pub fn run<T: Send + 'static>(// no way to get it back, so the error is reported instead.let spawned = std::thread::Builder::new().name(format!("photocraft-job-{}", id.0)).spawn(move || {let _authorization = AuthorizationScope::enter(authorization);+ let _document = crate::doc_path::scope(document.as_deref());let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| work(&wctx).map(|t| Box::new(t) as Payload))).unwrap_or_else(|_| Err(EngineError::Other(format!("`{label_w}` failed with an internal error (logged); the document is unchanged"))));// The receiver is gone when the job was cancelled: nothing to report.@@ -694,6 +700,7 @@ impl Session {gate(id, ¶ms)?;}let _authorization = AuthorizationScope::enter(self.authorize);+ let _document = crate::doc_path::scope(self.active().and_then(|d| d.path.as_deref()).map(std::path::Path::new));// Last Filter runs as the filter it repeats: journaled, recorded in an action, faded and// run as a job like that filter, so a recorded step replays the same filter anywhere// (#3089), as Transform Again records its transform (#1440). With no filter yet it fallsdiff --git a/crates/engine/src/layer_menu_cmds.rs b/crates/engine/src/layer_menu_cmds.rsindex 366f9c8d3..8e033b244 100644--- a/crates/engine/src/layer_menu_cmds.rs+++ b/crates/engine/src/layer_menu_cmds.rs@@ -373,14 +373,17 @@ fn reveal_in_finder(s: &mut Session, p: &Value) -> Result<Value> {let SmartSource::Linked { path } = &sm.source else {return Err(other("embedded smart objects have no file to reveal"));};- reveal(path, p.get("dryRun").and_then(Value::as_bool).unwrap_or(false))+ // The path is stored in the document: shown only when it would be followed.+ let file =+ crate::doc_path::resolve_in(path, d.path.as_deref().map(std::path::Path::new)).map_err(|why| crate::doc_path::refusal("the linked file", path, why))?;+ reveal(&file.to_string_lossy(), p.get("dryRun").and_then(Value::as_bool).unwrap_or(false))}/// Show `path` in the platform file manager ([`reveal_command`] + [`spawn`]); `dry_run` answers/// the program and arguments instead (tests). Shared by the smart-object command and the document/// tab's Reveal in Finder (UI-217-6).pub(crate) fn reveal(path: &str, dry_run: bool) -> Result<Value> {- let (program, args) = reveal_command(path);+ let (program, args) = reveal_command(path)?;if dry_run {return Ok(json!({"program": program, "args": args}));}@@ -389,14 +392,23 @@ pub(crate) fn reveal(path: &str, dry_run: bool) -> Result<Value> {}/// The file-manager invocation that selects `path` on this platform.-pub fn reveal_command(path: &str) -> (&'static str, Vec<String>) {- if cfg!(target_os = "macos") {- ("open", vec!["-R".into(), path.into()])- } else if cfg!(target_os = "windows") {- ("explorer", vec![format!("/select,{path}")])- } else {- let parent = std::path::Path::new(path).parent().map_or_else(|| ".".to_string(), |p| p.to_string_lossy().into_owned());- ("xdg-open", vec![parent])+pub fn reveal_command(path: &str) -> Result<(&'static str, Vec<String>)> {+ reveal_command_on(std::env::consts::OS, path)+}++/// [`reveal_command`] on the platform `os` (a `std::env::consts::OS` value).+fn reveal_command_on(os: &str, path: &str) -> Result<(&'static str, Vec<String>)> {+ match os {+ // `--` ends the options: a path starting with `-` is not read as one.+ "macos" => Ok(("open", vec!["-R".into(), "--".into(), path.into()])),+ // Explorer splits `/select,` arguments at commas and reads quotes itself, so such a path+ // would select something else.+ "windows" if path.contains([',', '"']) => Err(other(format!("{path} can't be shown in Explorer: its path contains a comma or a quotation mark"))),+ "windows" => Ok(("explorer", vec![format!("/select,{path}")])),+ _ => {+ let parent = std::path::Path::new(path).parent().map_or_else(|| ".".to_string(), |p| p.to_string_lossy().into_owned());+ Ok(("xdg-open", vec![parent]))+ }}}diff --git a/crates/engine/src/layer_menu_cmds/tests.rs b/crates/engine/src/layer_menu_cmds/tests.rsindex 46688500b..72ace605c 100644--- a/crates/engine/src/layer_menu_cmds/tests.rs+++ b/crates/engine/src/layer_menu_cmds/tests.rs@@ -465,16 +465,13 @@ fn stack_mode_rejects_sources_without_visible_layers() {#[test]fn reveal_in_finder_dry_run_and_enabled() {+ let link = std::env::temp_dir().join("pics").join("a.png").to_string_lossy().into_owned();let mut s = session(8, "rgb");assert!(!s.is_enabled("layer.smartObjects.revealInFinder"));s.edit("linked", |doc, active| {let mut l = Layer::new("linked",- LayerContent::Smart(photocraft_doc::SmartObject::new(- SmartSource::Linked { path: "/tmp/pics/a.png".into() },- photocraft_geom::Affine::IDENTITY,- None,- )),+ LayerContent::Smart(photocraft_doc::SmartObject::new(SmartSource::Linked { path: link.clone() }, photocraft_geom::Affine::IDENTITY, None)),);l.visible = true;*active = Some(doc.insert_above(*active, l));@@ -483,11 +480,41 @@ fn reveal_in_finder_dry_run_and_enabled() {.unwrap();assert!(s.is_enabled("layer.smartObjects.revealInFinder"));let r = s.execute("layer.smartObjects.revealInFinder", json!({"dryRun": true})).unwrap();- let (prog, args) = reveal_command("/tmp/pics/a.png");+ let (prog, args) = reveal_command(&link).unwrap();assert_eq!(r["program"], json!(prog));assert_eq!(r["args"], json!(args));}+#[test]+fn reveal_follows_linked_paths_like_the_link_and_passes_paths_as_paths() {+ let mut s = session(8, "rgb");+ let folder = std::env::temp_dir().join("pics");+ s.active_mut().unwrap().path = Some(folder.join("doc.pcraft").to_string_lossy().into_owned());+ let mut link = |path: &str| {+ s.edit("linked", |doc, active| {+ let so = photocraft_doc::SmartObject::new(SmartSource::Linked { path: path.into() }, photocraft_geom::Affine::IDENTITY, None);+ *active = Some(doc.insert_above(*active, Layer::new("linked", LayerContent::Smart(so))));+ Ok(())+ })+ .unwrap();+ s.execute("layer.smartObjects.revealInFinder", json!({"dryRun": true})).map_err(|e| e.to_string())+ };+ let err = link(r"\\192.0.2.1\share\x.png").unwrap_err();+ assert!(err.contains("is not opened: the path is on another computer"), "{err}");+ // A relative link is shown next to the document.+ let r = link("a.png").unwrap();+ assert_eq!(r["args"], json!(reveal_command(&folder.join("a.png").to_string_lossy()).unwrap().1));+ // The document's own file is shown wherever it is, a network share included.+ s.active_mut().unwrap().path = Some(r"\\192.0.2.1\share\doc.psd".into());+ s.execute("file.revealInFinder", json!({"dryRun": true})).unwrap();++ assert_eq!(reveal_command_on("macos", "-a.png").unwrap(), ("open", vec!["-R".to_string(), "--".into(), "-a.png".into()]));+ assert_eq!(reveal_command_on("windows", r"C:\pics\a.png").unwrap(), ("explorer", vec![r"/select,C:\pics\a.png".to_string()]));+ for path in [r"C:\pics\a,b.png", r#"C:\pics\a".png"#] {+ assert!(reveal_command_on("windows", path).is_err(), "{path}");+ }+}+#[test]fn mask_all_objects_masks_the_subject() {let mut s = session(8, "rgb");diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex b8d6167c3..c46db72b8 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -34,6 +34,7 @@ mod crop_fill;pub mod cutout_cmds;pub mod display_color;pub mod distort_cmds;+pub mod doc_path;pub mod document_preset_cmds;pub mod edit_cmds;pub mod edit_menu_cmds;@@ -782,6 +783,7 @@ impl Session {// Every mutation path (linked-file refresh, transform, place) re-renders smart objects// through this entry; the requesting session's authority must reach those renders.let _authorization = crate::jobs::render_authorization_scope(self.authorize);+ let _document = crate::doc_path::scope(self.active().and_then(|d| d.path.as_deref()).map(std::path::Path::new));let restrict = self.color_restrict;let sampler_map = self.sampler_map.take();let st = self.active_mut().ok_or(EngineError::NoDocument)?;diff --git a/crates/engine/src/link_watch.rs b/crates/engine/src/link_watch.rsindex 5c235fb91..1885812ce 100644--- a/crates/engine/src/link_watch.rs+++ b/crates/engine/src/link_watch.rs@@ -32,15 +32,17 @@ pub type Stamp = (u64, u128);/// ids, stamp)]).pub type LinkScan = Arc<Mutex<Option<(u64, Vec<(String, Vec<u64>, Option<Stamp>)>)>>>;+/// Stamps `file`, a linked path resolved by [`crate::doc_path`]; `None` (not looked at, like a+/// missing file) when it is not followed.#[cfg(not(target_arch = "wasm32"))]-fn stamp(path: &str) -> Option<Stamp> {- let meta = std::fs::metadata(path).ok()?;+fn stamp(file: Option<&std::path::Path>) -> Option<Stamp> {+ let meta = std::fs::metadata(file?).ok()?;let modified = meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?;Some((meta.len(), modified.as_nanos()))}#[cfg(target_arch = "wasm32")]-fn stamp(_: &str) -> Option<Stamp> {+fn stamp(_: Option<&std::path::Path>) -> Option<Stamp> {None}@@ -61,11 +63,24 @@ pub fn linked_files(d: &Document) -> Vec<(String, Vec<u64>)> {/// the layers of the ones that changed.pub(crate) fn update_changed(s: &mut Session, _: &Value) -> Result<Value> {let st = s.active().ok_or(EngineError::NoDocument)?;- let (doc, files) = (st.doc.id.0, linked_files(&st.doc));- let now = files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p))).collect();+ let (doc, files) = (st.doc.id.0, resolved_files(st));+ let now = files.into_iter().map(|(p, file, ids)| (p, ids, stamp(file.as_deref()))).collect();s.apply_link_stamps(doc, now)}+/// [`linked_files`] of `st`'s document with the file each path resolves to, or `None` for a path+/// that is not followed ([`crate::doc_path`]).+fn resolved_files(st: &crate::DocState) -> Vec<(String, Option<std::path::PathBuf>, Vec<u64>)> {+ let document = st.path.as_deref().map(std::path::Path::new);+ linked_files(&st.doc)+ .into_iter()+ .map(|(p, ids)| {+ let file = crate::doc_path::resolve_in(&p, document).ok();+ (p, file, ids)+ })+ .collect()+}+impl Session {/// Start stamping the active document's linked files on a worker thread, unless a look is/// still running (or the build has no files to look at: the web app).@@ -74,14 +89,15 @@ impl Session {return;}let Some(st) = self.active() else { return };- let (doc, files) = (st.doc.id.0, linked_files(&st.doc));- if files.is_empty() {+ let (doc, files) = (st.doc.id.0, resolved_files(st));+ // Nothing to look at: no links, or none that is followed.+ if files.iter().all(|(_, file, _)| file.is_none()) {return;}let slot: LinkScan = Arc::default();let out = slot.clone();let spawned = std::thread::Builder::new().name("link-watch".into()).spawn(move || {- let stamps = files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p))).collect();+ let stamps = files.into_iter().map(|(p, file, ids)| (p, ids, stamp(file.as_deref()))).collect();*out.lock().unwrap_or_else(PoisonError::into_inner) = Some((doc, stamps));});if spawned.is_ok() {diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rsindex 9a0af4a05..de16a94ac 100644--- a/crates/engine/src/print_cmds.rs+++ b/crates/engine/src/print_cmds.rs@@ -602,8 +602,12 @@ fn print_one_copy(s: &mut Session, p: &Value) -> Result<Value> {fn package(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "file.package";let dir = p.get("dir").and_then(Value::as_str).filter(|v| !v.is_empty()).ok_or_else(|| bad(cmd, "missing \"dir\" (where to create the package folder)"))?;+ // The copies are relinked by absolute path: a relative one would be resolved against the+ // package document's folder, not the working directory `dir` is relative to.+ let dir = std::path::absolute(dir).map_or_else(|_| dir.to_string(), |d| d.to_string_lossy().into_owned());let d = s.active().ok_or(EngineError::NoDocument)?;let doc = (*d.doc).clone();+ let document = d.path.clone();let name = stem(&d.path.clone().unwrap_or_else(|| doc.name.clone()));// The native format keeps external links; our PSD writer has no `lnkE` (external linked// file) support yet, so a PSD package would embed or flatten them.@@ -612,7 +616,7 @@ fn package(s: &mut Session, p: &Value) -> Result<Value> {Some(f) => return Err(bad(cmd, format!("unknown package format `{f}` (pcraft|psd|psb)"))),None => "pcraft".into(),};- let folder = join(dir, &crate::file_cmds::sanitize(&name));+ let folder = join(&dir, &crate::file_cmds::sanitize(&name));let links_dir = join(&folder, "Links");// Copy every linked file once; relink the copy of the document to the copies.let mut copied: Vec<(String, String)> = Vec::new();@@ -629,7 +633,12 @@ fn package(s: &mut Session, p: &Value) -> Result<Value> {fname = format!("{}-{}", copied.len(), fname);}let t = join(&links_dir, &fname);- match read_file(path) {+ // A path that is not followed is packaged as missing, like a file that is gone.+ let Ok(file) = crate::doc_path::resolve_in(path, document.as_deref().map(std::path::Path::new)) else {+ missing.push(path.clone());+ continue;+ };+ match read_file(&file.to_string_lossy()) {Ok(bytes) => {write_file(&t, &bytes)?;copied.push((path.clone(), t.clone()));diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rsindex 6ffc89e67..1f1cde798 100644--- a/crates/engine/src/smart_cmds.rs+++ b/crates/engine/src/smart_cmds.rs@@ -77,8 +77,13 @@ fn base_name(path: &str) -> String {path.rsplit(['/', '\\']).next().unwrap_or(path).to_string()}+/// A linked file's bytes; `None` when it is missing or its path is not followed+/// ([`crate::doc_path::resolve`]).fn read_file(path: &str) -> Option<Vec<u8>> {- if path.is_empty() { None } else { photocraft_format::read_file(std::path::Path::new(path)).ok() }+ if path.is_empty() {+ return None;+ }+ photocraft_format::read_file(&crate::doc_path::resolve(path).ok()?).ok()}/// The source file of a smart object: embedded bytes, the PSD's embedded linked-layer data (PSD@@ -492,10 +497,14 @@ fn refresh_or_fail(doc: &mut Document, id: LayerId) -> Result<()> {fn refresh_or_fail_in(doc: &mut Document, id: LayerId, ctx: &JobCtx) -> Result<()> {if refresh_in(doc, id, ctx)? {- Ok(())- } else {- Err(other("the smart object's contents are unavailable (missing linked file?), so it can't be re-rendered"))+ return Ok(());+ }+ if let SmartSource::Linked { path } = &smart(doc, id)?.source+ && let Err(why @ crate::doc_path::NotFollowed::Refused(_)) = crate::doc_path::resolve(path)+ {+ return Err(crate::doc_path::refusal("the linked file", path, why));}+ Err(other("the smart object's contents are unavailable (missing linked file?), so it can't be re-rendered"))}fn smart(doc: &Document, id: LayerId) -> Result<&SmartObject> {diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.tomlindex 9bd4c559c..eb8c0b00d 100644--- a/crates/io/Cargo.toml+++ b/crates/io/Cargo.toml@@ -31,6 +31,7 @@ photocraft-text = { workspace = true }photocraft-paint = { workspace = true }photocraft-vector = { workspace = true }photocraft-format = { path = "../format" }+craft-docpath = { workspace = true }thiserror = { workspace = true }serde_json = { workspace = true }blake3 = { version = "1.8", default-features = false, features = ["pure"] }diff --git a/crates/io/src/doc_path.rs b/crates/io/src/doc_path.rsnew file mode 100644index 000000000..37e7daf21--- /dev/null+++ b/crates/io/src/doc_path.rs@@ -0,0 +1,59 @@+//! Files named by paths stored in a document: linked smart objects, the Displace map and Color+//! Lookup file of a smart filter, data-set images, video footage.+//!+//! Such a path is followed only through [`resolve`]: a relative path is taken from the document's+//! folder, and only local files, or files on the network share the document itself is on, are+//! opened (see `craft_docpath`). A refused path is treated like a missing file.++use std::fmt;+use std::path::{Path, PathBuf};++pub use craft_docpath::Refused;++/// Why a stored path is not followed.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum NotFollowed {+ /// The path is not a local file, or is not on the document's own share.+ Refused(Refused),+ /// The path is relative and the document has no file to take it from.+ NoDocumentFolder,+}++impl fmt::Display for NotFollowed {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::Refused(r) => r.fmt(f),+ Self::NoDocumentFolder => f.write_str("the path is relative and the document has not been saved"),+ }+ }+}++impl std::error::Error for NotFollowed {}++/// The file to open for `stored`, a path or `file:` URL stored in a document, or why it is not+/// followed. `document` is the path of the document it is stored in, if the document has a file;+/// a relative `document` is taken from the working directory, where it was opened from.+pub fn resolve(stored: &str, document: Option<&Path>) -> Result<PathBuf, NotFollowed> {+ let document = document.map(|d| if d.is_relative() { std::path::absolute(d).unwrap_or_else(|_| d.to_path_buf()) } else { d.to_path_buf() });+ let path = craft_docpath::resolve(stored, document.as_deref()).map_err(NotFollowed::Refused)?;+ // A path that is still relative would be taken from the working directory, which the+ // document does not choose.+ if path.is_relative() {+ return Err(NotFollowed::NoDocumentFolder);+ }+ Ok(path)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn relative_paths_are_taken_from_the_document_folder() {+ let doc = std::env::temp_dir().join("art").join("poster.pcraft");+ assert_eq!(resolve("logo.png", Some(&doc)), Ok(std::env::temp_dir().join("art").join("logo.png")));+ assert_eq!(resolve("logo.png", None), Err(NotFollowed::NoDocumentFolder));+ assert_eq!(resolve(r"\\192.0.2.1\share\x.png", Some(&doc)), Err(NotFollowed::Refused(Refused::Network)));+ assert_eq!(resolve("//192.0.2.1/share/x.png", None), Err(NotFollowed::Refused(Refused::Network)));+ }+}diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rsindex 24b8b3f94..e3c6365d9 100644--- a/crates/io/src/lib.rs+++ b/crates/io/src/lib.rs@@ -40,6 +40,7 @@ pub mod blocks;pub mod camera_raw_xmp;mod channel_map;pub mod comps_map;+pub mod doc_path;pub mod effects_map;pub mod exr_parts;mod flat;