diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 31a6a6402d..d98c17fbe4 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -8,7 +8,7 @@ use super::steps_artboard::{artboard_edit_from, artboard_edit_to, artboard_from, use super::steps_channels::{match_color_from, match_color_to, merge_spot_from, merge_spot_to, split_from, split_to, trap_from, trap_to}; use super::steps_content_aware::{caf_from, caf_to}; use super::steps_direct_adjustments::{gradient_from, gradient_to, replace_from, replace_to}; -use super::steps_distort::{PINCH, POLAR, SPHERIZE, TWIRL, ZIGZAG, keys_from, keys_to, shear_from, shear_to, wave_from, wave_to}; +use super::steps_distort::{PINCH, POLAR, SPHERIZE, TWIRL, ZIGZAG, displace_from, displace_to, keys_from, keys_to, shear_from, shear_to, wave_from, wave_to}; use super::steps_doc::{ align_from, align_to, canvas_size_from, canvas_size_to, close_from, close_to, conditional_from, conditional_to, convert_mode_from, convert_mode_to, crop_from, crop_to, export_from, export_to, image_size_from, image_size_to, merge_visible_from, merge_visible_to, open_from, open_to, paste_from, paste_to, @@ -568,6 +568,7 @@ pub(super) const EVENTS: &[Event] = &[ &[F("Hrzn", "horizontal", Kind::Long), F("Vrtc", "vertical", Kind::Long), F("Fl ", "undefinedAreas", Kind::Enum("FlMd", OFFSET_FILL))] ), // Distort (#10605): every key in recorded order, Photoshop's limits and defaults. + Event { code: "", name: "displace", label: "Displace", ids: &["filter.distort.displace"], from: displace_from, to: displace_to }, Event { code: "Shr ", name: "shear", label: "Shear", ids: &["filter.distort.shear"], from: shear_from, to: shear_to }, Event { code: "Pnch", diff --git a/crates/engine/src/cmd/atn_cmds/menu_item.rs b/crates/engine/src/cmd/atn_cmds/menu_item.rs index 69ed161cd6..6aabfff170 100644 --- a/crates/engine/src/cmd/atn_cmds/menu_item.rs +++ b/crates/engine/src/cmd/atn_cmds/menu_item.rs @@ -6,8 +6,8 @@ use super::{AtnEvent, AtnItem, EngineError, Result, Session, Value, bad, json}; /// Find a supported, unambiguous event for a menu step with no settings. fn menu_event(id: &str) -> Option<&'static Event> { - // Camera Raw's ATN mapping requires a verified settings descriptor (#8714). - if id == crate::lens_cmds::RAW || (id != "image.imageSize" && !id.starts_with("filter.")) { + // Camera Raw (#8714) and recorded Displace require verified settings descriptors. + if matches!(id, crate::lens_cmds::RAW | "filter.distort.displace") || (id != "image.imageSize" && !id.starts_with("filter.")) { return None; } EVENTS.iter().find(|e| { diff --git a/crates/engine/src/cmd/atn_cmds/steps_distort.rs b/crates/engine/src/cmd/atn_cmds/steps_distort.rs index 703b2327dd..d37dca24df 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_distort.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_distort.rs @@ -1,11 +1,10 @@ -//! Photoshop's Distort filter steps (#10605): Pinch, Polar Coordinates, Shear, Spherize, Twirl, Wave and -//! ZigZag, each key in recorded order with the limits and defaults Photoshop measures. +//! Photoshop's Distort filter steps, with keys in recorded order and measured limits and defaults. -use super::descriptors::{desc, enm, num, trimmed}; +use super::descriptors::{code, desc, enm, jstr, num, path_text, path_value, trimmed}; use super::events::pixel_target; use super::fields::{Mapped, step}; use super::tables::{lookup, lookup_back}; -use super::{D, Descriptor, Map, Value, json}; +use super::{D, Descriptor, Id, Map, Value, json}; /// Whether every key of `d` is one of `keys` (codes compare without their space padding). fn only_keys(d: &Descriptor, keys: &[&str]) -> bool { @@ -39,6 +38,73 @@ fn enum_of(ty: &str) -> impl Fn(&D) -> Option + '_ { } } +/// Only the measured Windows Displace descriptor has a verified map path and settings. +pub(super) fn displace_from(d: &Descriptor) -> Mapped { + displace_params(d).map_or(Mapped::Unsupported { harmless: false }, |params| step("filter.distort.displace", params)) +} + +/// Decode only the measured, byte-preserving Windows descriptor. +fn displace_params(d: &Descriptor) -> Option { + if d.class_id != code("null") + || d.items.len() != 5 + || d.items.iter().any(|(key, _)| !matches!(key, Id::Code(_))) + || d.get("DspM") != Some(&enm("DspM", "StrF")) + || d.get("UndA") != Some(&enm("UndA", "RptE")) + { + return None; + } + let scale = |key| match d.get(key) { + Some(D::Integer(value)) if (-999..=999).contains(value) => Some(*value), + _ => None, + }; + let horizontal = scale("HrzS")?; + let vertical = scale("VrtS")?; + let wire = d.get("DspF")?; + let path = path_text(wire)?; + // The shared decoder tolerates malformed lengths and UTF-16 for legacy callers. The + // measured form must reproduce every byte, and an embedded NUL is never a file name. + if path.contains('\0') || &path_value(&path) != wire { + return None; + } + // An action file is shared like a document, and playback reads this path. Map only a path a + // document may name: a local absolute file. Others stay kept steps, so playing a downloaded + // set never opens a network share (which sends the user's credentials) or a device. + crate::doc_path::resolve_in(&path, None).ok()?; + Some(json!({"horizontal":horizontal,"vertical":vertical,"fit":"stretch","undefinedAreas":"repeat","mapPath":path})) +} + +/// Write the measured form with native defaults for omitted settings, without dropping +/// settings the descriptor cannot represent. +pub(super) fn displace_to(_: &str, p: &Value) -> Option { + if !pixel_target(p) || !sets_only(p, &["horizontal", "vertical", "fit", "undefinedAreas", "mapPath", "target"]) { + return None; + } + if p.get("fit").is_some_and(|v| v.as_str() != Some("stretch")) || p.get("undefinedAreas").is_some_and(|v| v.as_str() != Some("repeat")) { + return None; + } + let scale = |key| { + let number = match p.get(key) { + None => 10.0, + Some(value) => value.as_f64()?, + }; + let value = number as i32; + ((-999..=999).contains(&value) && f64::from(value) == number).then_some(D::Integer(value)) + }; + let path = jstr(p, "mapPath")?; + // The header carries a u32 byte length, including its 12 bytes and the UTF-16 terminator. + if path.is_empty() || path.contains('\0') || path.len() > ((u32::MAX - 14) / 2) as usize { + return None; + } + Some( + desc("null") + .with("HrzS", scale("horizontal")?) + .with("VrtS", scale("vertical")?) + .with("DspM", enm("DspM", "StrF")) + .with("UndA", enm("UndA", "RptE")) + .with("DspF", path_value(path)), + ) +} + /// One key of a Distort filter's step, in recorded order. pub(super) enum Key { /// An integer clamped to `min..=max` on import, as Photoshop clamps it; `default` when the diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 1c8a2911d8..440116ac6b 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -742,6 +742,7 @@ fn every_mapped_command_exports_and_imports_back() { ("filter.other.offset", json!({"horizontal": 10, "vertical": -5, "undefinedAreas": "wrap"})), ("filter.blur.blur", json!({})), ("file.automate.createDroplet", json!({"path": "/d/Sharpen.pcdroplet", "action": "Sharpen", "set": "Tools", "output": "/d/out", "overrideOpen": true})), + ("filter.distort.displace", json!({"horizontal":-999,"vertical":999,"fit":"stretch","undefinedAreas":"repeat","mapPath":LOCAL_MAP})), ("filter.distort.shear", json!({"points": [[0,0], [0.5,0.25], [1,0]], "undefinedAreas": "repeat"})), ("filter.distort.pinch", json!({"amount": -30})), ("filter.distort.polarCoordinates", json!({"mode": "polarToRectangular"})), @@ -5635,6 +5636,216 @@ fn custom_outside_the_commands_range_is_kept_and_refused() { } } +/// A local absolute map path on this platform: playback may read only such a path. +#[cfg(windows)] +const LOCAL_MAP: &str = r"C:\máp.psd"; +#[cfg(not(windows))] +const LOCAL_MAP: &str = "/máp.psd"; +/// [`LOCAL_MAP`] as a `txtu` path, encoded independently of the production path writer. +#[cfg(windows)] +const LOCAL_MAP_WIRE: &[u8] = b"txtu\x22\0\0\0\x0b\0\0\0C\0:\0\\\0m\0\xe1\0p\0.\0p\0s\0d\0\0\0"; +#[cfg(not(windows))] +const LOCAL_MAP_WIRE: &[u8] = b"txtu\x1e\0\0\0\x09\0\0\0/\0m\0\xe1\0p\0.\0p\0s\0d\0\0\0"; + +/// The selected-map descriptor measured in a Windows Displace recording. +fn displace_descriptor(path: D) -> Descriptor { + desc("null") + .with("HrzS", D::Integer(10)) + .with("VrtS", D::Integer(10)) + .with("DspM", enm("DspM", "StrF")) + .with("UndA", enm("UndA", "RptE")) + .with("DspF", path) +} + +/// Preserve the typed path and materialize native defaults when saving sparse steps. +#[test] +fn recorded_displace_round_trips_text_event_and_typed_path() { + let descriptor = displace_descriptor(D::Path(LOCAL_MAP_WIRE.to_vec())); + let data = set_of("Maps", vec![("A", vec![item("displace", "Displace", Some(descriptor.clone()))])]); + let imported = import(&photocraft_paint::tile::b64_decode(&data).unwrap()).unwrap(); + assert!(imported.unsupported.is_empty()); + let (id, params) = &imported.actions[0].steps[0]; + assert_eq!(id, "filter.distort.displace"); + assert_eq!(*params, json!({"horizontal":10,"vertical":10,"fit":"stretch","undefinedAreas":"repeat","mapPath":LOCAL_MAP})); + let exported = export_item(id, params, "Maps").unwrap(); + assert_eq!(exported.event, AtnEvent::name("displace")); + assert_eq!(exported.descriptor, Some(descriptor.clone())); + let minimal = json!({"mapPath":LOCAL_MAP}); + assert_eq!(export_item(id, &minimal, "Maps").unwrap().descriptor, Some(descriptor.clone())); + for key in ["horizontal", "vertical", "fit", "undefinedAreas"] { + let mut sparse = params.clone(); + sparse.as_object_mut().unwrap().remove(key); + assert_eq!(export_item(id, &sparse, "Maps").unwrap().descriptor, Some(descriptor.clone()), "{key}"); + } + let custom = json!({"horizontal":-7,"mapPath":LOCAL_MAP}); + let mut expected = descriptor; + expected.items[0].1 = D::Integer(-7); + assert_eq!(export_item(id, &custom, "Maps").unwrap().descriptor, Some(expected)); +} + +/// A shared action file must not make playback open a network share, a device or a path taken +/// from the working directory: such a map path stays a kept step with its bytes. +#[test] +fn displace_map_paths_a_document_may_not_name_stay_kept_steps() { + let refused = [r"\\server\share\map.psd", "//server/share/map.psd", r"\\?\UNC\server\share\map.psd", r"\\.\COM1", "file://server/share/map.psd", "map.psd"]; + let cases: Vec<_> = refused.iter().map(|path| item("displace", "Displace", Some(displace_descriptor(path_value(path))))).collect(); + let data = set_of("Maps", vec![("A", cases.clone())]); + let imported = import(&photocraft_paint::tile::b64_decode(&data).unwrap()).unwrap(); + assert_eq!(imported.unsupported.len(), cases.len()); + for ((id, params), expected) in imported.actions[0].steps.iter().zip(cases) { + assert_eq!(id, PHOTOSHOP_STEP, "{params}"); + assert_eq!(export_item(id, params, "Maps").unwrap().descriptor, expected.descriptor); + } +} + +/// Keep unmeasured inputs intact and refuse settings that would be changed by export. +#[test] +fn unmeasured_displace_stays_opaque_and_lossy_export_is_refused() { + assert!(!super::menu_item_commands().contains(&"filter.distort.displace")); + let path = r"C:\map.psd"; + let wire = path_value(path); + let descriptor = displace_descriptor(wire.clone()); + let replace = |key: &str, value: D| { + let mut d = descriptor.clone(); + d.items.iter_mut().find(|(id, _)| id.is(key)).unwrap().1 = value; + d + }; + let alter_path = |i: usize, pair: [u8; 2]| { + let D::Path(mut bytes) = wire.clone() else { panic!("expected a path") }; + bytes[i..i + 2].copy_from_slice(&pair); + D::Path(bytes) + }; + let mut without_path = descriptor.clone(); + without_path.items.retain(|(id, _)| !id.is("DspF")); + let mut string_key = descriptor.clone(); + string_key.items[0].0 = Id::Str(b"HrzS".to_vec()); + let cases = [ + item("displace", "Displace", None), + item("displace", "Displace", Some(without_path)), + item("displace", "Displace", Some(string_key)), + item("displace", "Displace", Some(descriptor.clone().with("HrzS", D::Integer(10)))), + item("displace", "Displace", Some(replace("HrzS", D::Double(10.0)))), + item("displace", "Displace", Some(replace("VrtS", D::Integer(1000)))), + item("displace", "Displace", Some(replace("DspM", enm("DspM", "Tile")))), + item("displace", "Displace", Some(replace("UndA", enm("OtherEnum", "RptE")))), + item("displace", "Displace", Some(replace("DspF", D::Alias(vec![1, 2, 3])))), + item("displace", "Displace", Some(replace("DspF", alter_path(4, [0, 0])))), + item("displace", "Displace", Some(replace("DspF", alter_path(8, [9, 0])))), + item("displace", "Displace", Some(replace("DspF", alter_path(12, [0, 0])))), + item("displace", "Displace", Some(replace("DspF", alter_path(12, [0, 0xd8])))), + item("Dspl", "Displace", Some(descriptor)), + ]; + let data = set_of("Maps", vec![("A", cases.to_vec())]); + let imported = import(&photocraft_paint::tile::b64_decode(&data).unwrap()).unwrap(); + assert_eq!(imported.unsupported.len(), cases.len()); + assert_eq!(imported.actions[0].steps.len(), cases.len()); + for ((id, params), expected) in imported.actions[0].steps.iter().zip(cases) { + assert_eq!(id, PHOTOSHOP_STEP); + let exported = export_item(id, params, "Maps").unwrap(); + assert_eq!(exported.event, expected.event); + assert_eq!(exported.descriptor, expected.descriptor); + } + + let good = json!({"horizontal":10,"vertical":10,"fit":"stretch","undefinedAreas":"repeat","mapPath":path}); + for (key, value) in [ + ("horizontal", json!(10.5)), + ("horizontal", json!(1000)), + ("vertical", json!(-1000)), + ("vertical", json!("10")), + ("fit", json!("tile")), + ("fit", Value::Null), + ("undefinedAreas", json!("wrap")), + ("undefinedAreas", json!(false)), + ("mapPath", json!("x\0y.psd")), + ("mapPath", json!("")), + ("mapLayer", json!(1)), + ("mapDocument", json!(0)), + ("target", json!("mask")), + ] { + let mut params = good.clone(); + params[key] = value; + assert!(export_item("filter.distort.displace", ¶ms, "Maps").is_none(), "{params}"); + } +} + +/// Loading needs no map; playback reads it only after authorization and stretches it. +#[test] +fn recorded_displace_loads_without_map_and_plays_through_the_step_gate() { + use photocraft_geom::Rect; + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("synthetic-map.psd"); + let wire = displace_descriptor(path_value(path.to_str().unwrap())); + let data = set_of("Maps", vec![("A", vec![item("displace", "Displace", Some(wire))])]); + let mut source = Session::new(); + let loaded = source.execute("actions.load", json!({"data":data})).unwrap(); + assert_eq!(loaded["unsupported"], json!([])); + assert!(!path.exists(), "loading the ATN needs no map"); + + let paint_split = |s: &mut Session, side: i32, split: i32, right: [f32; 4]| { + s.execute("file.new", json!({"width":side,"height":side})).unwrap(); + s.edit("Two-tone fixture", |doc, _| { + let id = doc.layers[0].id; + let surface = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + surface.fill_rect(Rect::new(0, 0, split, side), &[0.0, 0.0, 0.0, 1.0]); + surface.fill_rect(Rect::new(split, 0, side, side), &right); + Ok(()) + }) + .unwrap(); + }; + // Offset the source edge so the positive shift crosses it within the white part of the map. + paint_split(&mut source, 64, 48, [1.0, 0.0, 0.0, 1.0]); + source + .edit("Bottom edge fixture", |doc, _| { + let id = doc.layers[0].id; + let surface = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + surface.fill_rect(Rect::new(0, 48, 64, 64), &[0.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + let snapshot = |s: &Session| { + let active = s.active().unwrap(); + (active.revision, active.history.past_len(), photocraft_compose::render(&active.doc, active.doc.bounds()).into_px()) + }; + let before = snapshot(&source); + let missing = source.execute("actions.play", json!({"action":"A"})).unwrap(); + assert_eq!(missing["ran"], 0); + assert_eq!(missing["failed"]["id"], "filter.distort.displace"); + assert!(missing["failed"]["error"].as_str().unwrap().contains("cannot read displacement map")); + assert_eq!(snapshot(&source), before); + + // Leave the map absent so a read before authorization would report the same I/O failure. + source.authorize = Some(|id, p| { + if id == "filter.distort.displace" && p["mapPath"].is_string() { + return Err(EngineError::Other("test denied the map path".into())); + } + Ok(()) + }); + let denied = source.execute("actions.play", json!({"action":"A"})).unwrap(); + assert_eq!(denied["ran"], 0); + assert_eq!(denied["failed"]["id"], "filter.distort.displace"); + assert!(denied["failed"]["error"].as_str().unwrap().contains("test denied the map path")); + assert_eq!(snapshot(&source), before); + + source.authorize = None; + let mut map = Session::new(); + paint_split(&mut map, 16, 8, [1.0, 1.0, 1.0, 1.0]); + let encoded = photocraft_io::export(&map.active().unwrap().doc, "psd", &Default::default()).unwrap(); + std::fs::write(&path, encoded.bytes).unwrap(); + let played = source.execute("actions.play", json!({"action":"A"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert!(played.get("failed").is_none(), "{played}"); + let pixels = snapshot(&source).2; + // With stretch, x=38 samples the white half and shifts into red; tiling samples black. + assert_eq!(before.2[32 * 64 + 38], [0.0, 0.0, 0.0, 1.0]); + assert_eq!(pixels[32 * 64 + 38], [1.0, 0.0, 0.0, 1.0]); + assert_eq!(pixels[32 * 64 + 20], [0.0, 0.0, 0.0, 1.0]); + // The vertical shift crosses into green, then repeats the bottom edge instead of wrapping to red. + assert_eq!(before.2[40 * 64 + 38], [0.0, 0.0, 0.0, 1.0]); + assert_eq!(pixels[40 * 64 + 38], [0.0, 1.0, 0.0, 1.0]); + assert_eq!(pixels[60 * 64 + 38], [0.0, 1.0, 0.0, 1.0]); +} + /// The step `d` of Photoshop event `code`, as PhotoCraft loads it. fn distort(code: &str, d: Descriptor) -> Mapped { let event = AtnEvent::Code(code.as_bytes().try_into().unwrap()); diff --git a/docs/atn.md b/docs/atn.md index f169b86132..a9c272aebd 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -994,7 +994,7 @@ the recorded steps back from the saved Actions panel. Ranges come from the dialo |---|---|---| | Custom (`Cstm`) | `Scl ` long 1..9999, `Ofst` long -9999..9999, `Mtrx` list of 25 longs -999..999 | Without the dialog the step needs all 25 cells, or the application fails. | | Fibers (`Fbrs`) | `Vrnc` long 1..64, `Strg` long 1..64, `RndS` long (seed) | | -| Displace (`Dspl`) | `HrzS`, `VrtS` long -999..999; `DspM` (`StrF` stretch to fit, or tile); `UndA` (`RptE` repeat edge pixels, or wrap around); `DspF` alias: path of the displacement map (.psd) | The map file is chosen after OK. | +| Displace (recorded `displace`) | `HrzS` and `VrtS` long -999..999, `DspM.StrF` (stretch to fit), `UndA.RptE` (repeat edge pixels), and `DspF` as `Pth ` | A later Windows recording measured the `txtu` path to the PSD map chosen after OK. | | Color Lookup (`colorLookup`) | `lookupType` (`colorLookupType`: `3DLUT`, abstract, device link); `Nm ` text: the file's path; `Dthr` bool; `profile` raw data (ICC); `LUTFormat` (`LUTFormatType`, e.g. `LUTFormatLOOK`); `LUT3DFileData` raw data: the LUT file itself; `LUT3DFileName` text | The LUT travels inside the step. | | Shape Blur (`shapeBlur`) | `Rds ` pixels 5..1000; `customShape` object (`Nm ` text, `Idnt` text: the shape's id); `keyOriginType` long (9) | | | Lighting Effects (`lightFilterLightingEffects`) | `k3DLights` list of lights (`Nm `, colour `Rd `/`Grn `/`Bl ` 0..1, `hots`, `FlOf`, `shdw`, attenuation keys, `Type`, `ison`, `key3DMatrix` raw + floats, `X `/`Y `/`Z `, target `tarx`/`tary`/`tarz`, `key3DPosition`), `key3DCurrentCameraPosition`, `Glos`, `Mtrl`, `Exps`, `AmbB`, `AmbC` RGB, `BmpA`, `BmpC` (texture channel by name, localised: "Ohne" = none), `Wdth`, `Hght` | A dialog-less run returns nothing; only a recording shows the keys. | @@ -1852,7 +1852,7 @@ Nested values as recorded (defaults): ### Group C: The Distort filters (Pinch, Polar Coordinates, Shear, Spherize, Twirl, Wave, ZigZag) -The seven Distort events below map to PhotoCraft's `filter.distort.*` commands for their documented supported forms, including complete Shear curves. Displace needs a displacement map file and is listed separately at the end. +The Distort events below map to PhotoCraft's `filter.distort.*` commands for their documented supported forms, including complete Shear curves and the recorded Windows Displace form. #### Pinch @@ -1959,7 +1959,11 @@ Nested values as recorded (defaults): #### Displace -Displace reads a displacement map from a file chosen in a dialog; record one step and add its keys (file path form) before implementing. +The TEXT event `displace` with descriptor class `null` maps to `filter.distort.displace`. + +The measured Windows recording uses `HrzS` and `VrtS` (32-bit integers, −999 to 999), `DspM.StrF` (stretch to fit), `UndA.RptE` (repeat edge pixels), and `DspF` (`Pth `, a `txtu` header with little-endian length and a NUL-terminated UTF-16LE path). Import preserves the map path as text. Playback opens the map through the native Displace command. + +Alias paths, other enum values, and malformed or incomplete descriptors stay as kept Photoshop steps. So does a map path a document may not name (a network share, a device, a URL or a relative path): playing a shared action file never opens it. Export supports the measured path and settings for a pixel target. ### Group D: The Stylize and Pixelate filters