PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(engine): Displace on a Smart Object embeds its map in the smart filter, as Photoshop does (#7423)
Korg1ch3c7ee9eded5d
diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rsindex c3059dca2..b3ab2c4be 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<(), Strinpub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result<Value> {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)?;@@ -297,9 +300,24 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result<Value>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())),diff --git a/crates/engine/src/filters_ext.rs b/crates/engine/src/filters_ext.rsindex 0425e1932..16b9493d6 100644--- a/crates/engine/src/filters_ext.rs+++ b/crates/engine/src/filters_ext.rs@@ -450,7 +450,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())),@@ -465,10 +465,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<u64>) -> Result<Option<algo::Image>> {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.rsindex 3ca10083b..4da3d89f1 100644--- a/crates/engine/src/smart_cmds.rs+++ b/crates/engine/src/smart_cmds.rs@@ -1018,10 +1018,40 @@ fn set_filter_visible(s: &mut Session, p: &Value) -> Result<Value> {})}+/// 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<Value> {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];@@ -1032,6 +1062,14 @@ fn set_filter_params(s: &mut Session, p: &Value) -> Result<Value> {(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.rsindex 8993663cc..0843375b0 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<Descriptor, String> {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<J> {+ 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.diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rsindex 5ec4db118..b93231a62 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.rsindex f8bc91c23..9943998bd 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_dlet 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_dat};*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);