Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Smart filters, data sets, video: re-read stored files only when local or on the document's share

aiongg0a328189aaef
diff --git a/crates/engine/src/adjust_cmds.rs b/crates/engine/src/adjust_cmds.rs
index c1393bb94..b9bcd437a 100644
--- a/crates/engine/src/adjust_cmds.rs
+++ b/crates/engine/src/adjust_cmds.rs
@@ -296,6 +296,18 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> {
/// Image › Adjustments run as a smart filter (`image.adjustments.<kind>` recorded on a smart
/// object): the adjustment applied to a copy of `surf`. `None` for kinds or params it can't run.
pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface) -> Option<Surface> {
+ // A Color Lookup filter re-reads its LUT `file`, a path stored in the document: followed only
+ // as `doc_path` allows, else the filter can't run (like a missing file).
+ let resolved;
+ let p = match p.get("file").and_then(Value::as_str).filter(|f| kind == "colorLookup" && !f.is_empty()) {
+ Some(file) => {
+ let mut q = p.clone();
+ q["file"] = json!(crate::doc_path::resolve(file).ok()?.to_str()?);
+ resolved = q;
+ &resolved
+ }
+ None => p,
+ };
let mut out = surf.clone();
if kind == "shadowsHighlights" {
let sh = shadows_highlights_params(p);
diff --git a/crates/engine/src/doc_path/tests.rs b/crates/engine/src/doc_path/tests.rs
index b28fe3fb4..393e85a06 100644
--- a/crates/engine/src/doc_path/tests.rs
+++ b/crates/engine/src/doc_path/tests.rs
@@ -145,3 +145,83 @@ fn psd_saves_embed_only_followed_links() {
let packaged = warnings(s.execute("file.package", json!({"dir": d.join("pkg").to_string_lossy(), "format": "psd"})).unwrap());
assert!(packaged.iter().any(|w| w.contains("is not opened: the path is on another computer")), "{packaged:?}");
}
+
+/// The pixels of the active document after its smart object `id` re-renders with its first smart
+/// filter's params set to `params`.
+fn replayed(s: &mut Session, id: LayerId, params: serde_json::Value) -> Vec<[f32; 4]> {
+ s.edit("Params", |doc, _| {
+ if let Some(LayerContent::Smart(sm)) = doc.layer_mut(id).map(|l| &mut l.content) {
+ sm.smart_filters[0].params = params;
+ }
+ crate::smart_cmds::refresh(doc, id).map(|_| ())
+ })
+ .unwrap();
+ let doc = &s.active().unwrap().doc;
+ photocraft_compose::render(doc, doc.bounds()).px
+}
+
+#[test]
+fn smart_filters_reread_only_followed_files() {
+ let d = dir("filters");
+ png(&d.join("ramp.png"), |x| [(x * 8) as u8, 0, 0]);
+ png(&d.join("map.png"), |_| [255, 255, 255]);
+ // An inverting look: corner (r, g, b) of the cube maps to (1-r, 1-g, 1-b), red fastest.
+ let corners = (0..8).map(|i| format!("{} {} {}\n", 1 - (i & 1), 1 - ((i >> 1) & 1), 1 - ((i >> 2) & 1))).collect::<String>();
+ std::fs::write(d.join("invert.cube"), format!("LUT_3D_SIZE 2\n{corners}")).unwrap();
+ let path = |name: &str| d.join(name).to_string_lossy().into_owned();
+
+ // Displace re-reads its `mapPath`.
+ let (mut s, id) = document(&d, &d.join("ramp.png"));
+ s.execute("filter.distort.displace", json!({"layer": id.0, "mapPath": path("map.png"), "horizontal": 50, "vertical": 0})).unwrap();
+ let displaced = replayed(&mut s, id, json!({"mapPath": path("map.png"), "horizontal": 50, "vertical": 0}));
+ let unfiltered = replayed(&mut s, id, json!({"mapPath": REMOTE, "horizontal": 50, "vertical": 0}));
+ assert_ne!(displaced, unfiltered, "the map moves the pixels");
+ assert_eq!(replayed(&mut s, id, json!({"mapPath": "map.png", "horizontal": 50, "vertical": 0})), displaced, "a relative map next to the document");
+ #[cfg(unix)]
+ assert_eq!(replayed(&mut s, id, json!({"mapPath": network_alias(&d.join("map.png")), "horizontal": 50, "vertical": 0})), unfiltered);
+
+ // Color Lookup re-reads its LUT `file`.
+ let (mut s, id) = document(&d, &d.join("ramp.png"));
+ s.execute("image.adjustments.colorLookup", json!({"layer": id.0, "lut": "none"})).unwrap();
+ let inverted = replayed(&mut s, id, json!({"file": path("invert.cube")}));
+ let unfiltered = replayed(&mut s, id, json!({"file": REMOTE}));
+ assert_ne!(inverted, unfiltered, "the look changes the pixels");
+ assert_eq!(replayed(&mut s, id, json!({"file": "invert.cube"})), inverted, "a relative look next to the document");
+ #[cfg(unix)]
+ assert_eq!(replayed(&mut s, id, json!({"file": network_alias(&d.join("invert.cube"))})), unfiltered);
+}
+
+#[test]
+fn data_sets_and_footage_read_only_followed_files() {
+ let d = dir("datasets");
+ png(&d.join("blue.png"), |_| [0, 0, 255]);
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 32, "height": 32, "background": "#ff0000"})).unwrap();
+ s.active_mut().unwrap().path = Some(d.join("doc.pcraft").to_string_lossy().into_owned());
+ let layer = s.active().unwrap().active_layer.unwrap();
+ s.execute("image.variables.define", json!({"defs": [{"name": "img", "layer": layer.0, "type": "pixelReplacement", "method": "conform"}]})).unwrap();
+ let set = |name: &str, path: &str| json!({"name": name, "values": [{"variable": "img", "kind": "pixels", "value": path}]});
+ s.execute("image.variables.dataSets", json!({"dataSets": [set("remote", REMOTE), set("relative", "blue.png")]})).unwrap();
+ let err = s.execute("image.applyDataSet", json!({"name": "remote"})).unwrap_err().to_string();
+ assert!(err.contains("is not opened: the path is on another computer"), "{err}");
+ assert_eq!(centre(&s), RED);
+ s.execute("image.applyDataSet", json!({"name": "relative"})).unwrap();
+ assert_eq!(centre(&s), BLUE);
+
+ // Reload Frame re-reads the video layer's footage.
+ s.execute("layer.videoLayers.newVideoLayerFromFile", json!({"path": d.join("blue.png").to_string_lossy()})).unwrap();
+ let footage = |s: &mut Session, path: &str| {
+ let id = s.active().unwrap().active_layer.unwrap();
+ s.edit("Footage", |doc, _| {
+ if let Some(v) = doc.layer_mut(id).and_then(|l| l.video.as_mut()) {
+ v.source = photocraft_doc::VideoSource::File { path: path.into() };
+ }
+ Ok(())
+ })
+ .unwrap();
+ s.execute("layer.videoLayers.reloadFrame", json!({})).map_err(|e| e.to_string())
+ };
+ let err = footage(&mut s, REMOTE).unwrap_err();
+ assert!(err.contains("is not opened: the path is on another computer"), "{err}");
+ footage(&mut s, "blue.png").unwrap();
+}
diff --git a/crates/engine/src/filters_ext.rs b/crates/engine/src/filters_ext.rs
index dae5e9b98..e4f6523a1 100644
--- a/crates/engine/src/filters_ext.rs
+++ b/crates/engine/src/filters_ext.rs
@@ -466,13 +466,15 @@ fn map_from_path(path: &str, layer: Option<u64>) -> Result<Option<algo::Image>>
/// The session-free part of [`resolve`]: Displace's `mapPath`. Smart filters record params, not
/// the map, so their re-render reads the map again here; without it the filter passed the pixels
-/// through. `mapDocument` needs the session and is left unresolved.
+/// through. The path is stored in the document, so it is followed only as
+/// [`crate::doc_path::resolve`] allows. `mapDocument` needs the session and is left unresolved.
pub(crate) fn resolve_map_path(fp: &mut FilterParams, p: &Value) -> Result<()> {
if let FilterParams::Displace { map, .. } = fp
&& map.is_none()
&& let Some(path) = map_path(p)
{
- *map = map_from_path(path, p.get("mapLayer").and_then(Value::as_u64))?.map(Arc::new);
+ let file = crate::doc_path::resolve(path).map_err(|why| crate::doc_path::refusal("the displacement map", path, why))?;
+ *map = map_from_path(&file.to_string_lossy(), p.get("mapLayer").and_then(Value::as_u64))?.map(Arc::new);
}
Ok(())
}
diff --git a/crates/engine/src/variables_cmds.rs b/crates/engine/src/variables_cmds.rs
index f42b74484..630826970 100644
--- a/crates/engine/src/variables_cmds.rs
+++ b/crates/engine/src/variables_cmds.rs
@@ -199,7 +199,9 @@ fn replace_pixels(doc: &mut Document, layer: LayerId, path: &str, method: PixelM
return Ok(());
}
let fmt = doc.pixel_format();
- let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("read `{path}`: {e}")))?;
+ // The path is stored in the document's data sets.
+ let file = crate::doc_path::resolve(path).map_err(|why| crate::doc_path::refusal("the image", path, why))?;
+ let bytes = std::fs::read(&file).map_err(|e| EngineError::Other(format!("read `{path}`: {e}")))?;
let src = crate::file_cmds::import(path, &bytes)?;
let img = crate::file_cmds::flattened(&src, fmt);
let (iw, ih) = (src.size.width.max(1) as f64, src.size.height.max(1) as f64);
diff --git a/crates/engine/src/video_cmds.rs b/crates/engine/src/video_cmds.rs
index 6fb9ab457..820745fd3 100644
--- a/crates/engine/src/video_cmds.rs
+++ b/crates/engine/src/video_cmds.rs
@@ -365,7 +365,9 @@ fn reload_frame(s: &mut Session, _p: &Value) -> Result<Value> {
let photocraft_doc::VideoSource::File { path } = src else {
return Err(EngineError::BadParams { cmd: "layer.videoLayers.reloadFrame".into(), msg: "this layer has no file source to reload".into() });
};
- let frames = load_frames(&path, fmt)?.frames;
+ // The footage path is stored in the document.
+ let file = crate::doc_path::resolve(&path).map_err(|why| crate::doc_path::refusal("the footage", &path, why))?;
+ let frames = load_frames(&file.to_string_lossy(), fmt)?.frames;
edit_video(s, "Reload Frame", move |v, _| {
v.original_frames = Some(frames.clone());
v.frames = frames;