diff --git a/crates/automation/tests/smart_filter_authorization.rs b/crates/automation/tests/smart_filter_authorization.rs index 30f17b795bf..594832c41d9 100644 --- a/crates/automation/tests/smart_filter_authorization.rs +++ b/crates/automation/tests/smart_filter_authorization.rs @@ -257,3 +257,26 @@ fn an_ambient_map_or_lut_never_renders_unfiltered_pixels_into_the_stack_cache() assert_eq!(bytes, smart_cmds::stack_cache_bytes(), "a denied render cached no stage"); } } + +/// Choosing another Displace map through `setParams` embeds it (#7423), so the new map is read +/// before the edit: a path outside the workspace is refused before that read, and the filter +/// keeps the map it had. +#[test] +fn a_new_displace_map_outside_the_workspace_is_refused_before_it_is_read() { + let f = Fixture::new(); + let (mut h, layer) = f.setup(false); + let params = |h: &Headless| { + let d = h.session.active().unwrap(); + let LayerContent::Smart(sm) = &d.doc.layer(layer).unwrap().content else { panic!("smart object") }; + sm.smart_filters[0].params.clone() + }; + let before = params(&h); + let map = photocraft_io::smart_map::displace_embedded_map(&before).expect("the open document's map, embedded"); + assert!(map.data.iter().all(|v| *v < 0.9), "the grey map"); + let doc = h.session.active().unwrap().doc.clone(); + let edit = json!({"layer": layer.0, "params": {"mapPath": f.outside("white.png")}}); + assert_denied(h.session.execute("layer.smartFilter.setParams", edit.clone())); + assert_denied(h.handle("engine.execute", json!({"command": "layer.smartFilter.setParams", "params": edit}))); + assert!(Arc::ptr_eq(&doc, &h.session.active().unwrap().doc)); + assert_eq!(params(&h), before, "no white map was read into the filter"); +} diff --git a/crates/engine/src/doc_path/tests.rs b/crates/engine/src/doc_path/tests.rs index 393e85a062b..1881860ae11 100644 --- a/crates/engine/src/doc_path/tests.rs +++ b/crates/engine/src/doc_path/tests.rs @@ -191,6 +191,36 @@ fn smart_filters_reread_only_followed_files() { assert_eq!(replayed(&mut s, id, json!({"file": network_alias(&d.join("invert.cube"))})), unfiltered); } +/// #7423 (review on #7799): Displace on a Smart Object keeps a `mapPath` as a path, as before +/// (only a map from an open document is embedded). A path relative to the saved document, set +/// through the filter's own edit, displaces as the absolute one did, and the dialog's "None" +/// (`mapDocument: -1`) names no map instead of failing. +#[test] +fn smart_displace_keeps_a_relative_map_path() { + let d = dir("displace-relative"); + png(&d.join("ramp.png"), |x| [(x * 8) as u8, 0, 0]); + png(&d.join("map.png"), |_| [255, 255, 255]); + let (mut s, id) = document(&d, &d.join("ramp.png")); + let path = d.join("map.png").to_string_lossy().into_owned(); + let unfiltered = photocraft_compose::render(&s.active().unwrap().doc, s.active().unwrap().doc.bounds()).px; + s.execute("filter.distort.displace", json!({"layer": id.0, "mapPath": path, "horizontal": 50, "vertical": 0})).unwrap(); + let state = |s: &Session| { + let doc = &s.active().unwrap().doc; + let Some(LayerContent::Smart(sm)) = doc.layer(id).map(|l| &l.content) else { panic!("a smart object") }; + (sm.smart_filters[0].params.clone(), photocraft_compose::render(doc, doc.bounds()).px) + }; + let (params, displaced) = state(&s); + assert_eq!(params["mapPath"], json!(path)); + assert!(photocraft_io::smart_map::displace_embedded_map(¶ms).is_none(), "a path, not an embedded map"); + assert_ne!(displaced, unfiltered, "the map moves the pixels"); + s.execute("layer.smartFilter.setParams", json!({"layer": id.0, "index": 0, "params": {"mapPath": "map.png"}})).unwrap(); + let (params, relative) = state(&s); + assert_eq!(params["mapPath"], json!("map.png")); + assert_eq!(relative, displaced, "a relative map next to the document"); + s.execute("layer.smartFilter.setParams", json!({"layer": id.0, "index": 0, "params": {"mapDocument": -1}})).unwrap(); + assert_eq!(state(&s).1, displaced, "\"None\" changes nothing"); +} + #[test] fn data_sets_and_footage_read_only_followed_files() { let d = dir("datasets"); diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs index 12437fa81ef..b115a9f5e04 100644 --- a/crates/engine/src/filters.rs +++ b/crates/engine/src/filters.rs @@ -234,7 +234,10 @@ pub(crate) fn has_filterable_layer(s: &Session) -> std::result::Result<(), Strin pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result { validate_params(id, p)?; // Session state some filters read (colours) becomes explicit params; external inputs resolve here. - let prepared = crate::filters_ext::prepare(s, id, p); + let mut prepared = crate::filters_ext::prepare(s, id, p); + if id == "filter.distort.displace" { + prepared = crate::filters_ext::displace_request(&prepared); + } let p = &prepared; let mut fp = params_for(id, p).ok_or_else(|| EngineError::Other(format!("unknown filter {id}")))?; crate::filters_ext::resolve(s, &mut fp, p)?; @@ -298,9 +301,24 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result if matches!(fp, FilterParams::LensBlur { depth: algo::DepthSource::Channel, .. }) { return Err(EngineError::Other("Lens Blur can't read an alpha channel as depth on a Smart Object: rasterize the layer first".into())); } + // A smart filter re-renders from its params alone: a Displace map read from an + // open document, which the re-render can't read again, is kept in them, as + // Photoshop embeds it (#7423). A `mapPath` stays a path, read next to the + // document on each re-render. + let params = match &fp { + FilterParams::Displace { map: Some(map), .. } + if photocraft_io::smart_map::displace_embedded_map(¶ms).is_none() && crate::filters_ext::map_path(¶ms).is_none() => + { + photocraft_io::smart_map::displace_embed_map(¶ms, map).ok_or_else(|| { + EngineError::Other( + "Displace: the displacement map is too large to keep in a Smart Object's filter: rasterize the layer first".into(), + ) + })? + } + _ => params.clone(), + }; // Non-destructive: record the filter and re-render the smart object from its source. - let sf = - SmartFilter { command: id.clone(), params: params.clone(), blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true }; + let sf = SmartFilter { command: id.clone(), params, blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true }; return crate::smart_cmds::add_smart_filter(doc, layer, sf, selection.as_ref()).map(|()| fp); } _ => return Err(EngineError::Other("not a pixel layer".into())), @@ -935,4 +953,65 @@ mod tests { assert!(calls.load(std::sync::atomic::Ordering::SeqCst) > 2); assert!(new.tiles().all(|(c, _)| got.tile(*c).is_some())); } + + /// #7423: Displace on a Smart Object keeps its map (read from an open document) in the smart + /// filter, as Photoshop embeds it, so the filter displaces and keeps displacing when the + /// object re-renders. A map chosen again replaces it. + #[test] + fn displace_on_a_smart_object_embeds_its_map() { + let mut s = Session::new(); + // Documents 0 and 1: a white and a black displacement map. + s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "black"})).unwrap(); + s.execute("file.new", json!({"width": 48, "height": 32, "background": "transparent"})).unwrap(); + s.edit("square", |doc, active| { + let fmt = doc.pixel_format(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(photocraft_geom::Rect::new(10, 10, 20, 12), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + Ok(()) + }) + .unwrap(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let original = { + let d = s.active().unwrap(); + let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not a smart object") }; + sm.cache.as_ref().unwrap().read_region(d.doc.bounds()) + }; + let smart = |s: &Session| { + let d = s.active().unwrap(); + let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not a smart object") }; + (sm.smart_filters[0].params.clone(), sm.cache.as_ref().unwrap().read_region(d.doc.bounds())) + }; + let first_value = |params: &Value| photocraft_io::smart_map::displace_embedded_map(params).expect("an embedded map").data[0]; + + s.execute("filter.distort.displace", json!({"horizontal": 10, "vertical": 0, "mapDocument": 0})).unwrap(); + let (params, displaced) = smart(&s); + assert!(params.get("mapDocument").is_none(), "{params}"); + assert_eq!(first_value(¶ms), 1.0, "the white map"); + assert_ne!(displaced, original, "the smart object is displaced"); + // Re-rendered from its params alone (the filter hidden and shown again): still displaced. + s.execute("layer.smartFilter.setVisible", json!({"index": 0, "visible": false})).unwrap(); + assert_eq!(smart(&s).1, original); + s.execute("layer.smartFilter.setVisible", json!({"index": 0, "visible": true})).unwrap(); + assert_eq!(smart(&s).1, displaced); + + // Another map chosen for the filter replaces the embedded one. + s.execute("layer.smartFilter.setParams", json!({"index": 0, "params": {"mapDocument": 1}})).unwrap(); + let (params, again) = smart(&s); + assert!(params.get("mapDocument").is_none(), "{params}"); + assert_eq!(first_value(¶ms), 0.0, "the black map"); + assert_ne!(again, displaced, "displaced the other way"); + + // The stored params passed back whole (the old embedded map included) with another map + // named: the named map wins, for the filter's own edit and for a new Displace alike. + let mut back = params.as_object().unwrap().clone(); + back.insert("mapDocument".into(), json!(0)); + s.execute("layer.smartFilter.setParams", json!({"index": 0, "params": back.clone()})).unwrap(); + assert_eq!(first_value(&smart(&s).0), 1.0, "the white map, not the embedded black one"); + back.insert("mapDocument".into(), json!(1)); + s.execute("filter.distort.displace", Value::Object(back)).unwrap(); + let d = s.active().unwrap(); + let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not a smart object") }; + assert_eq!(first_value(&sm.smart_filters[1].params), 0.0, "the black map, not the passed-back white one"); + } } diff --git a/crates/engine/src/filters_ext.rs b/crates/engine/src/filters_ext.rs index 3eaa4f00bbe..ce6f7c012f1 100644 --- a/crates/engine/src/filters_ext.rs +++ b/crates/engine/src/filters_ext.rs @@ -457,7 +457,7 @@ pub(crate) fn resolve(s: &Session, fp: &mut FilterParams, p: &Value) -> Result<( let layer = p.get("mapLayer").and_then(Value::as_u64); let img = if let Some(path) = map_path(p) { map_from_path(path, layer)? - } else if let Some(d) = p.get("mapDocument") { + } else if let Some(d) = map_document(p) { let docs = s.documents(); let found = match d { Value::String(name) => docs.iter().find(|ds| ds.doc.name == *name || ds.path.as_deref() == Some(name.as_str())), @@ -472,10 +472,23 @@ pub(crate) fn resolve(s: &Session, fp: &mut FilterParams, p: &Value) -> Result<( Ok(()) } -fn map_path(p: &Value) -> Option<&str> { +/// Displace's params as a request for its map: a map named in them (`mapPath` or `mapDocument`) +/// wins over the one already embedded, which is read only when none is named. Otherwise a dialog +/// or agent passing the filter's stored params back with a new map got the old map again. +pub(crate) fn displace_request(p: &Value) -> Value { + if map_path(p).is_some() || map_document(p).is_some() { photocraft_io::smart_map::displace_without_map(p) } else { p.clone() } +} + +pub(crate) fn map_path(p: &Value) -> Option<&str> { p.get("mapPath").and_then(Value::as_str).filter(|p| !p.is_empty()) } +/// Displace's `mapDocument`: an index or a name. Null and a negative index (the dialog's "None") +/// name no document. +pub(crate) fn map_document(p: &Value) -> Option<&Value> { + p.get("mapDocument").filter(|d| !d.is_null() && !d.as_i64().is_some_and(|i| i < 0)) +} + /// Displace's map read from a file (flattened, or its `mapLayer`). fn map_from_path(path: &str, layer: Option) -> Result> { let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("cannot read displacement map `{path}`: {e}")))?; diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rs index 0d93631f3f0..d337e64d3fd 100644 --- a/crates/engine/src/smart_cmds.rs +++ b/crates/engine/src/smart_cmds.rs @@ -1041,10 +1041,40 @@ fn set_filter_visible(s: &mut Session, p: &Value) -> Result { }) } +/// The Displace filter, whose map a smart filter keeps embedded in its params. +const DISPLACE: &str = "filter.distort.displace"; + fn set_filter_params(s: &mut Session, p: &Value) -> Result { const CMD: &str = "layer.smartFilter.setParams"; let new = p.get("params").cloned().ok_or_else(|| bad(CMD, "pass `params` (merged into the filter's parameters)"))?; let authorize = s.authorize; + // A Displace given another open document as its map embeds that one in place of the old + // (#7423). It is read here, before the edit, from the session; the request is authorized + // first, as the merged params are below. A new `mapPath` stays a path (read next to the + // document on each re-render) and only drops the old embedded map; an empty one, or a + // negative `mapDocument` (the dialog's "None"), names no map. + let new_map_asked = crate::filters_ext::map_document(&new).is_some(); + let new_path = crate::filters_ext::map_path(&new).is_some(); + let displace = { + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let sm = smart(doc, layer_param(s, p)?)?; + sm.smart_filters.get(filter_index(CMD, p, sm)?).is_some_and(|f| f.command == DISPLACE) + }; + let new_map = if displace && new_map_asked { + // The old embedded map, if the edit passed it back, gives way to the one named. + let request = crate::filters_ext::displace_request(&new); + if let Some(gate) = authorize { + gate(DISPLACE, &request)?; + } + let mut fp = crate::filters::params_for(DISPLACE, &request).ok_or_else(|| bad(CMD, "unreadable Displace settings"))?; + crate::filters_ext::resolve(s, &mut fp, &request)?; + match fp { + photocraft_algo::FilterParams::Displace { map, .. } => map, + _ => None, + } + } else { + None + }; edit_filters(s, p, "Edit Smart Filter", |sm| { let i = filter_index(CMD, p, sm)?; let f = &mut sm.smart_filters[i]; @@ -1055,6 +1085,14 @@ fn set_filter_params(s: &mut Session, p: &Value) -> Result { (Value::Object(old), Value::Object(n)) => old.extend(n), (slot, n) => *slot = n, } + if f.command == DISPLACE { + if let Some(map) = &new_map { + f.params = photocraft_io::smart_map::displace_embed_map(&f.params, map) + .ok_or_else(|| bad(CMD, "the displacement map is too large to keep in a Smart Object's filter"))?; + } else if new_path { + f.params = photocraft_io::smart_map::displace_without_map(&f.params); + } + } // Authorize the underlying command with the complete merged params, including paths // already stored in the document, before committing the edit or starting a worker. if let Some(gate) = authorize { diff --git a/crates/io/src/displace_map.rs b/crates/io/src/displace_map.rs index 8993663cc0c..48b34c4b010 100644 --- a/crates/io/src/displace_map.rs +++ b/crates/io/src/displace_map.rs @@ -38,6 +38,10 @@ const HEADER: usize = 10; const MODE_TWO_PLANES: u16 = 3; /// 8K × 8K: far beyond the observed document-sized maps, and bounds the f32 map we build. const MAX_MAP_PIXELS: usize = 1 << 26; +/// 4K × 4K: the largest map PhotoCraft embeds itself. Params hold it as hex, about 4 bytes per +/// pixel, copied with every history state and written into `.pcraft`'s manifest, so a few of the +/// largest readable maps would make a file the reader refuses. +const MAX_EMBED_PIXELS: usize = 1 << 24; /// The template is the item plus the map; a little room for the rest of the descriptor. const MAX_TEMPLATE_BYTES: usize = 2 * MAX_MAP_PIXELS + (1 << 20); @@ -156,6 +160,69 @@ pub(super) fn export_item(params: &J) -> Result { Ok(item) } +/// `filter.distort.displace` params with `map` embedded the way Photoshop embeds a Displace +/// smart filter's map: a `filterFX` item ([`TEMPLATE_KEY`]) holding it as two 8-bit planes. A +/// smart filter re-renders from its params alone, so a map read from a file or an open document +/// must travel with them (#7423); embedded, it also saves to `.pcraft` and PSD like an imported +/// one. `map`'s first channel is the horizontal map and its second the vertical one (the first +/// again for one or two channels), as the filter reads them. `mapPath`, `mapDocument` and +/// `mapLayer` are dropped: `map` was already read from them (from that layer, when one was +/// named), and the embedded map replaces them. `None` for params that are not an +/// object, or an empty, short or oversized map. +pub fn embed_map(params: &J, map: &Image) -> Option { + let (w, h) = (map.rect.width(), map.rect.height()); + let n = usize::try_from(w).ok()?.checked_mul(usize::try_from(h).ok()?)?; + if n == 0 || n > MAX_EMBED_PIXELS || map.ch == 0 || map.data.len() < n.checked_mul(map.ch)? { + return None; + } + let vertical = if map.ch >= 3 { 1 } else { 0 }; + let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + let pixels = || map.data.chunks_exact(map.ch).take(n); + let mut planes = Vec::with_capacity(HEADER + 2 * n); + planes.extend(h.to_le_bytes()); + planes.extend(w.to_le_bytes()); + planes.extend(MODE_TWO_PLANES.to_le_bytes()); + planes.extend(pixels().map(|px| px.first().map_or(0, |v| byte(*v)))); + planes.extend(pixels().map(|px| px.get(vertical).map_or(0, |v| byte(*v)))); + let enumerated = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; + // The settings here are placeholders: the params' own replace them when the filter renders + // and when it is written to PSD (`export_item`). + let neutral = SmartFilter { command: String::new(), params: J::Null, blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true }; + let item = Descriptor::new("filterFX") + .with("Nm ", Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul("Displace..."))) + .with("blendOptions", blend_options(&neutral)) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with( + "Fltr", + Value::Descriptor( + Descriptor::new(CLASS) + .with("HrzS", Value::Integer(10)) + .with("VrtS", Value::Integer(10)) + .with("DspM", enumerated("DspM", "StrF")) + .with("UndA", enumerated("UndA", "RptE")) + .with("EmbF", Value::Boolean(true)) + .with(MAP_KEY, Value::RawData(planes)), + ), + ) + .with("filterID", Value::Integer(FILTER_ID)); + let mut out = params.as_object()?.clone(); + for key in ["mapPath", "mapDocument", "mapLayer"] { + out.remove(key); + } + out.insert(TEMPLATE_KEY.into(), json!(to_hex(&item.to_bytes()))); + Some(J::Object(out)) +} + +/// `params` without the embedded map, for a Displace that names another one to read instead. +pub fn without_map(params: &J) -> J { + let mut out = params.clone(); + if let J::Object(m) = &mut out { + m.remove(TEMPLATE_KEY); + } + out +} + /// The displacement map embedded in Displace params imported from PSD (`None` when there is /// none or it is unreadable). The two planes become the first two channels; identical planes /// (every file seen so far) become one channel, which Displace reads for both directions. @@ -340,4 +407,38 @@ mod tests { } assert!(embedded_map(&json!({TEMPLATE_KEY: "0".repeat(MAX_TEMPLATE_BYTES * 2 + 2)})).is_none()); } + + /// #7423: a map from a file or an open document, embedded for a smart filter, is read back as + /// the filter's map and written to PSD like an imported one. + #[test] + fn an_embedded_map_reads_back_and_exports() { + let rect = Rect::new(0, 0, 3, 2); + // RGBA: red is the horizontal map, green the vertical one. + let rgba = Image { rect, ch: 4, data: (0..6).flat_map(|i| [i as f32 / 5.0, 1.0 - i as f32 / 5.0, 0.0, 1.0]).collect() }; + let params = json!({"horizontal": 20, "vertical": -5, "fit": "tile", "undefinedAreas": "wrap", "mapDocument": 0, "mapLayer": 3}); + let embedded = embed_map(¶ms, &rgba).unwrap(); + for key in ["mapPath", "mapDocument", "mapLayer"] { + assert!(embedded.get(key).is_none(), "{key}"); + } + assert_eq!(embedded["horizontal"], json!(20)); + let map = embedded_map(&embedded).unwrap(); + assert_eq!((map.rect, map.ch), (rect, 3)); + let h: Vec = map.data.chunks(3).map(|p| p[0]).collect(); + let v: Vec = map.data.chunks(3).map(|p| p[1]).collect(); + assert_eq!(h, [0.0, 51.0 / 255.0, 102.0 / 255.0, 153.0 / 255.0, 204.0 / 255.0, 1.0]); + assert_eq!(v, [1.0, 204.0 / 255.0, 153.0 / 255.0, 102.0 / 255.0, 51.0 / 255.0, 0.0]); + // Written to PSD with the params' own settings. + let f = export_item(&embedded).unwrap(); + let fltr = get_desc(&f, "Fltr").unwrap(); + assert_eq!(num(fltr.get("HrzS")), Some(20.0)); + assert_eq!(enum_of(fltr, "DspM"), Some(&b"Tile"[..])); + // A grey map displaces the same both ways. + let grey = Image { rect, ch: 1, data: vec![0.25; 6] }; + let map = embedded_map(&embed_map(&json!({}), &grey).unwrap()).unwrap(); + assert_eq!(map.ch, 1); + // Nothing to embed. + assert!(embed_map(&json!({}), &Image { rect: Rect::new(0, 0, 0, 0), ch: 4, data: vec![] }).is_none()); + assert!(embed_map(&json!({}), &Image { rect, ch: 4, data: vec![0.0; 5] }).is_none(), "short data"); + assert!(embed_map(&json!(3), &grey).is_none(), "params not an object"); + } } diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rs index 08f9a874b2a..f18dd444b6f 100644 --- a/crates/io/src/smart_map.rs +++ b/crates/io/src/smart_map.rs @@ -46,7 +46,7 @@ mod hue_sat; #[path = "perspective_warp_map.rs"] mod perspective_warp; -pub use displace::embedded_map as displace_embedded_map; +pub use displace::{embed_map as displace_embed_map, embedded_map as displace_embedded_map, without_map as displace_without_map}; /// Command id of a Photoshop smart filter PhotoCraft does not implement. Its params hold the /// filter's name, Photoshop filter id and descriptor (`psd`, hex); it renders as a pass-through. diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs index f8bc91c23b7..ad185f315c2 100644 --- a/crates/ui-egui/src/filter_dialog.rs +++ b/crates/ui-egui/src/filter_dialog.rs @@ -1114,11 +1114,10 @@ fn add_source_documents(s: &mut photocraft_engine::Session, doc_id: photocraft_d let Some(spec) = photocraft_engine::commands::find(command) else { return }; let Some(o) = p.as_object_mut() else { return }; let mut added: Vec<(usize, usize)> = Vec::new(); - for param in parse_spec(spec.params).into_iter().filter(|p| p.kind == Kind::Document) { - let Some(v) = o.get_mut(¶m.key) else { continue }; - let Some(i) = v.as_u64().and_then(|i| usize::try_from(i).ok()) else { continue }; + let mut remap = |v: &mut Value| { + let Some(i) = v.as_u64().and_then(|i| usize::try_from(i).ok()) else { return }; // An index past the open documents stays as given, so the preview fails like OK would. - let Some(src) = documents.get(i) else { continue }; + let Some(src) = documents.get(i) else { return }; let at = if src.id == doc_id { 0 } else if let Some(&(_, at)) = added.iter().find(|(j, _)| *j == i) { @@ -1129,6 +1128,18 @@ fn add_source_documents(s: &mut photocraft_engine::Session, doc_id: photocraft_d at }; *v = json!(at); + }; + for param in parse_spec(spec.params).into_iter().filter(|p| p.kind == Kind::Document) { + if let Some(v) = o.get_mut(¶m.key) { + remap(v); + } + } + // A smart filter being edited carries its filter's params one level down: Displace's + // `mapDocument` there names an open document too. + if command == SMART_FILTER_SET_PARAMS + && let Some(v) = o.get_mut("params").and_then(Value::as_object_mut).and_then(|f| f.get_mut("mapDocument")) + { + remap(v); } // Adding a document makes it active: the command still runs on the edited one. s.set_active(0); @@ -1768,6 +1779,52 @@ mod tests { assert_eq!(label("wavelengthMin"), "Wavelength Min"); } + /// #7423 (review on #7799): re-editing a Displace smart filter and picking another open + /// document as its map previews with that document, as OK applies it. The preview session held + /// only the edited document, and the map's `mapDocument` sits inside the filter's `params`. + #[test] + fn smart_displace_preview_uses_the_map_document() { + let mut s = photocraft_engine::Session::new(); + // Documents 0 and 1: a white and a black map, opened before the edited one. + s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "black"})).unwrap(); + s.execute("file.new", json!({"width": 48, "height": 32, "background": "transparent"})).unwrap(); + s.edit("square", |doc, active| { + let fmt = doc.pixel_format(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(photocraft_geom::Rect::new(10, 10, 20, 12), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + Ok(()) + }) + .unwrap(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("filter.distort.displace", json!({"horizontal": 10, "vertical": 0, "mapDocument": 0})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let layer = s.active().unwrap().active_layer; + let documents: Vec<_> = s.documents().iter().map(|d| d.doc.clone()).collect(); + for map in [1, 0] { + let p = json!({"index": 0, "params": {"mapDocument": map}}); + let mut applied = photocraft_engine::Session::new(); + for d in &documents { + applied.add_document((**d).clone(), None); + } + applied.execute(SMART_FILTER_SET_PARAMS, p.clone()).unwrap(); + let want = photocraft_compose::render(&applied.active().unwrap().doc, doc.bounds()).px; + let preview = preview_document_for_target( + &doc, + layer, + SMART_FILTER_SET_PARAMS, + &p, + 1, + None, + photocraft_engine::channel_cmds::ChannelTarget::Composite, + &documents, + &ColorSettings::default(), + ) + .unwrap_or_else(|| panic!("map {map}: no preview")); + assert!(photocraft_compose::render(&preview, doc.bounds()).px == want, "map {map}: the preview differs from what OK applies"); + } + } + /// Match Color's preview reads the Source document from the open documents, as OK does: the /// preview session held only the edited document, so a Source showed no change (#4851). #[test]