Skip to content

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

Merge PR #5249: PSD: Distort smart filters and Invert open and save like Photoshop

David Mann7cfa2786ffa1
diff --cc crates/io/src/smart_map.rs
index 4ce416fcc,2951cc76e..9dfeec858
--- a/crates/io/src/smart_map.rs
+++ b/crates/io/src/smart_map.rs
@@@ -150,7 -145,7 +151,7 @@@ const fn code(c: &[u8; 4]) -> i32
i32::from_be_bytes(*c)
}
- const KNOWN: [Known; 41] = [
-const KNOWN: [Known; 22] = [
++const KNOWN: [Known; 49] = [
Known { class: "GsnB", filter_id: code(b"GsnB"), name: "Gaussian Blur...", command: "filter.blur.gaussianBlur" },
Known { class: "boxblur", filter_id: 840, name: "Box Blur...", command: "filter.blur.boxBlur" },
Known { class: "MtnB", filter_id: code(b"MtnB"), name: "Motion Blur...", command: "filter.blur.motionBlur" },
@@@ -182,77 -161,41 +183,97 @@@
Known { class: "Crvs", filter_id: code(b"Crvs"), name: "Curves...", command: "image.adjustments.curves" },
// Shadows/Highlights at its defaults stores no `Fltr` (`hasoptions` false).
Known { class: "adaptCorrect", filter_id: 781, name: "Shado&ws/Highlights...", command: "image.adjustments.shadowsHighlights" },
+ // Filters without options (measured in Photoshop): `hasoptions` false, no `Fltr`, only the
+ // four-char `filterID`. The class is that code; see `NO_OPTIONS`.
+ Known { class: "Blr ", filter_id: code(b"Blr "), name: "Blur", command: "filter.blur.blur" },
+ Known { class: "BlrM", filter_id: code(b"BlrM"), name: "Blur More", command: "filter.blur.blurMore" },
+ Known { class: "Avrg", filter_id: code(b"Avrg"), name: "Average", command: "filter.blur.average" },
+ Known { class: "Dspc", filter_id: code(b"Dspc"), name: "Despeckle", command: "filter.noise.despeckle" },
+ Known { class: "FndE", filter_id: code(b"FndE"), name: "Find Edges", command: "filter.stylize.findEdges" },
+ Known { class: "Fct ", filter_id: code(b"Fct "), name: "Facet", command: "filter.pixelate.facet" },
+ Known { class: "Frgm", filter_id: code(b"Frgm"), name: "Fragment", command: "filter.pixelate.fragment" },
+ Known { class: "Shrp", filter_id: code(b"Shrp"), name: "Sharpen", command: "filter.sharpen.sharpen" },
+ Known { class: "ShrM", filter_id: code(b"ShrM"), name: "Sharpen More", command: "filter.sharpen.sharpenMore" },
+ Known { class: "ShrE", filter_id: code(b"ShrE"), name: "Sharpen Edges", command: "filter.sharpen.sharpenEdges" },
+ Known { class: "Slrz", filter_id: code(b"Slrz"), name: "Solarize", command: "filter.stylize.solarize" },
+ // Smart Sharpen has a numeric filterID and a stringID class, like Box Blur.
+ Known { class: SMART_SHARPEN, filter_id: 1131, name: "Smart Sharpen...", command: "filter.sharpen.smartSharpen" },
+ Known { class: "DstS", filter_id: code(b"DstS"), name: "Dust & Scratches...", command: "filter.noise.dustAndScratches" },
+ // Distort (Photoshop 27, `corpus`-style check: one smart object per filter saved from Photoshop
+ // and read back). Shear isn't mapped yet: its curve lives on Photoshop's own grid.
+ Known { class: "Pnch", filter_id: code(b"Pnch"), name: "Pinch...", command: "filter.distort.pinch" },
+ Known { class: "Plr ", filter_id: code(b"Plr "), name: "Polar Coordinates...", command: "filter.distort.polarCoordinates" },
+ Known { class: "Rple", filter_id: code(b"Rple"), name: "Ripple...", command: "filter.distort.ripple" },
+ Known { class: "Sphr", filter_id: code(b"Sphr"), name: "Spherize...", command: "filter.distort.spherize" },
+ Known { class: "Twrl", filter_id: code(b"Twrl"), name: "Twirl...", command: "filter.distort.twirl" },
+ Known { class: "Wave", filter_id: code(b"Wave"), name: "Wave...", command: "filter.distort.wave" },
+ Known { class: "ZgZg", filter_id: code(b"ZgZg"), name: "ZigZag...", command: "filter.distort.zigZag" },
+ // Image › Adjustments › Invert on a smart object: no settings, so no `Fltr` (`hasoptions` false).
+ Known { class: "Invr", filter_id: code(b"Invr"), name: "Invert", command: "image.adjustments.invert" },
];
+/// Classes of the filters that have no options: Photoshop stores them without a `Fltr`.
+const NO_OPTIONS: [&str; 11] = ["Blr ", "BlrM", "Avrg", "Dspc", "FndE", "Fct ", "Frgm", "Shrp", "ShrM", "ShrE", "Slrz"];
+
+// ---------- Smart Sharpen and Dust & Scratches ----------
+//
+// Measured in Photoshop (applied through Action Manager to a smart object, saved, `filterFX` read
+// back):
+//
+// ```text
+// Smart Sharpen (filterID 1131): smartSharpen { presetKind = presetKindType enum (only on the
+// default entry), useLegacy bool, Amnt UntF #Prc, Rds UntF #Pxl, noiseReduction UntF #Prc,
+// blur = blurType enum (GsnB | lensBlur | MtnB), Angl long (Motion Blur only) }
+// Dust & Scratches (filterID DstS): DstS { Rds long, Thsh long }
+// ```
+//
+// PhotoCraft's Smart Sharpen removes a Gaussian blur, non-legacy: Lens Blur, Motion Blur, legacy
+// mode, Shadow/Highlight settings or any other key keep the whole entry verbatim. `presetKind`
+// only names the dialog's preset: it is accepted on open but not kept (the engine takes no such
+// parameter) and not written (Photoshop leaves it out of entries with explicit values).
+
+const SMART_SHARPEN: &str = "smartSharpen";
+const SMART_SHARPEN_KEYS: [&str; 6] = ["presetKind", "useLegacy", "Amnt", "Rds ", "noiseReduction", "blur"];
+
+/// A `UntF` value in `unit`, finite and within `lo..=hi`.
+fn unit_in(d: &Descriptor, key: &str, u: &[u8; 4], lo: f64, hi: f64) -> Option<f64> {
+ match d.get(key)? {
+ Value::UnitFloat { unit, value } if unit == u && value.is_finite() && (lo..=hi).contains(value) => Some(*value),
+ _ => None,
+ }
+}
+
+/// `filter.sharpen.smartSharpen` params; `None` for a setting PhotoCraft doesn't render.
+fn smart_sharpen_params(f: &Descriptor) -> Option<J> {
+ if f.items.iter().any(|(k, _)| !SMART_SHARPEN_KEYS.iter().any(|x| k.is(x))) {
+ return None;
+ }
+ let Some(Value::Boolean(false)) = f.get("useLegacy") else { return None };
+ let Some(Value::Enumerated { type_id, value }) = f.get("blur") else { return None };
+ if !type_id.is("blurType") || !value.is("GsnB") {
+ return None;
+ }
+ let mut out = Map::new();
+ out.insert("amount".into(), json!(unit_in(f, "Amnt", b"#Prc", 1.0, 500.0)?));
+ out.insert("radius".into(), json!(unit_in(f, "Rds ", b"#Pxl", 0.1, 64.0)?));
+ out.insert("reduceNoise".into(), json!(unit_in(f, "noiseReduction", b"#Prc", 0.0, 100.0)?));
+ match f.get("presetKind") {
+ None => {}
+ Some(Value::Enumerated { type_id, .. }) if type_id.is("presetKindType") => {}
+ Some(_) => return None,
+ }
+ Some(J::Object(out))
+}
+
+ /// Photoshop enum codes ↔ PhotoCraft parameter values, per filter setting.
+ const RIPPLE_SIZE: [(&[u8; 4], &str); 3] = [(b"Sml ", "small"), (b"Mdm ", "medium"), (b"Lrg ", "large")];
+ const SPHERIZE_MODE: [(&[u8; 4], &str); 3] = [(b"Nrml", "normal"), (b"HrzO", "horizontalOnly"), (b"VrtO", "verticalOnly")];
+ const POLAR_MODE: [(&[u8; 4], &str); 2] = [(b"RctP", "rectangularToPolar"), (b"PlrR", "polarToRectangular")];
+ const ZIGZAG_STYLE: [(&[u8; 4], &str); 3] = [(b"PndR", "pondRipples"), (b"OtFr", "outFromCenter"), (b"ArnC", "aroundCenter")];
+ const WAVE_TYPE: [(&[u8; 4], &str); 3] = [(b"WvSn", "sine"), (b"WvTr", "triangle"), (b"WvSq", "square")];
+ const UNDEFINED_AREAS: [(&[u8; 4], &str); 2] = [(b"WrpA", "wrap"), (b"RptE", "repeat")];
+
-/// The PhotoCraft value of the enum `key` in `f` (`None`: absent or a code we don't know).
-fn enum_param(f: &Descriptor, key: &str, table: &[(&[u8; 4], &'static str)]) -> Option<&'static str> {
- let code = enum_of(f, key)?;
- table.iter().find(|(c, _)| c.as_slice() == code).map(|(_, v)| *v)
-}
-
-/// The enum value Photoshop stores for PhotoCraft's `p[key]` (its `default` when unset).
-fn enum_value(p: &J, key: &str, default: &str, type_id: &str, table: &[(&[u8; 4], &str)]) -> Result<Value, String> {
- let v = p.get(key).and_then(J::as_str).unwrap_or(default);
- let (code, _) = table.iter().find(|(_, name)| *name == v).ok_or_else(|| format!("{key} `{v}` has no PSD equivalent"))?;
- Ok(Value::Enumerated { type_id: Id::new(type_id), value: Id::Code(**code) })
-}
-
+ /// The PSD filter record that PhotoCraft's `command` is written as, if it has one.
fn known_by_command(command: &str) -> Option<&'static Known> {
KNOWN.iter().find(|k| k.command == command)
}
@@@ -261,28 -204,7 +282,29 @@@
/// composite: top-level keys).
const CHANNELS: [(&[u8; 4], &str); 4] = [(b"Cmps", ""), (b"Rd ", "red"), (b"Grn ", "green"), (b"Bl ", "blue")];
+/// Mezzotint's `MztT` enum codes and our `type` values (measured in Photoshop by rendering each).
+const MEZZOTINT_TYPES: [(&[u8; 4], &str); 10] = [
+ (b"FnDt", "fineDots"),
+ (b"MdmD", "mediumDots"),
+ (b"GrnD", "grainyDots"),
+ (b"CrsD", "coarseDots"),
+ (b"ShrL", "shortLines"),
+ (b"MdmL", "mediumLines"),
+ (b"LngL", "longLines"),
+ (b"ShSt", "shortStrokes"),
+ (b"MdmS", "mediumStrokes"),
+ (b"LngS", "longStrokes"),
+];
+
+/// Color Halftone's `Rds ` (max radius) and `Ang1`..`Ang4` (screen angles) longs, read within
+/// the dialog's ranges; anything else is kept verbatim.
+fn color_halftone_params(f: &Descriptor) -> Option<J> {
+ let radius = int(f, "Rds ").filter(|r| (4..=127).contains(r))?;
+ let angle = |k: &str| int(f, k).filter(|a| (-360..=360).contains(a));
+ Some(json!({"maxRadius": radius, "channel1": angle("Ang1")?, "channel2": angle("Ang2")?, "channel3": angle("Ang3")?, "channel4": angle("Ang4")?}))
+}
+
+ /// A numeric descriptor item as a finite number; `None` when it is absent, not a number, or not finite.
fn px(d: &Descriptor, key: &str) -> Option<f64> {
num(d.get(key)).filter(|v| v.is_finite())
}
@@@ -410,100 -294,40 +433,127 @@@ fn curves_params(f: &Descriptor) -> Opt
Some(J::Object(out))
}
+/// Diffuse's `Md ` (`DfsM` enum, measured in Photoshop) ↔ our `mode`.
+const DIFFUSE_MODES: [(&str, &str); 4] = [("Nrml", "normal"), ("DrkO", "darkenOnly"), ("LghO", "lightenOnly"), ("anisotropic", "anisotropic")];
+
+/// Trace Contour's `Edg ` (`CntE` enum, measured in Photoshop) ↔ our `edge`.
+const TRACE_EDGES: [(&str, &str); 2] = [("Upr ", "upper"), ("Lwr ", "lower")];
+
+/// Our name for the enum value of `key` (of type `type_id`) through `table` (Photoshop's value, ours).
+fn enum_from(d: &Descriptor, key: &str, type_id: &str, table: &[(&str, &'static str)]) -> Option<&'static str> {
+ let Some(Value::Enumerated { type_id: t, value }) = d.get(key) else { return None };
+ if t.as_bytes() != type_id.as_bytes() {
+ return None;
+ }
+ table.iter().find(|(psd, _)| value.as_bytes() == psd.as_bytes()).map(|(_, ours)| *ours)
+}
+
+// Wind, Extrude and Tiles, measured in Photoshop (each code changes the rendered result).
+
+/// Wind's `WndM` (enum `WndM`) ↔ our `method`.
+const WIND_METHODS: [(&str, &str); 3] = [("Wnd ", "wind"), ("Blst", "blast"), ("Stgr", "stagger")];
+/// Wind's `Drct` (enum `Drct`) ↔ our `direction`. Photoshop's `Left` streaks extend to the left
+/// of an edge, which is our wind from the right.
+const WIND_DIRECTIONS: [(&str, &str); 2] = [("Left", "fromRight"), ("Rght", "fromLeft")];
+/// Extrude's `ExtT` (enum `ExtT`) ↔ our `type`.
+const EXTRUDE_TYPES: [(&str, &str); 2] = [("Blks", "blocks"), ("Pyrm", "pyramids")];
+/// Extrude's `ExtR` (enum `ExtR`) ↔ our `depthMode`.
+const EXTRUDE_DEPTHS: [(&str, &str); 2] = [("Rndm", "random"), ("LvlB", "levelBased")];
+/// Tiles' `FlCl` (enum `FlCl`) ↔ our `fill`.
+const TILE_FILLS: [(&str, &str); 4] = [("FlBc", "background"), ("FlFr", "foreground"), ("FlIn", "inverse"), ("FlSm", "unaltered")];
+/// Extrude's size and depth (`ExtS`, `ExtD`) and Tiles' count and offset (`TlNm`, `TlOf`), all
+/// `long`s, in the engine's (and Photoshop's dialog) ranges.
+const EXTRUDE_SIZE: (i32, i32) = (2, 255);
+const EXTRUDE_DEPTH: (i32, i32) = (1, 255);
+const TILE_COUNT: (i32, i32) = (1, 99);
+const TILE_OFFSET: (i32, i32) = (1, 99);
+
+/// The `bool` at `key`.
+fn bool_at(d: &Descriptor, key: &str) -> Option<bool> {
+ match d.get(key)? {
+ Value::Boolean(b) => Some(*b),
+ _ => None,
+ }
+}
+
+/// Tiles' params; background and foreground fills use the colours the entry carries (`FrgC`,
+/// `BckC`). `None` when a setting or a colour that is there can't be read.
+fn tiles_params(f: &Descriptor, item: &Descriptor) -> Option<J> {
+ let mut out = Map::new();
+ out.insert("count".into(), json!(int_in(f, "TlNm", TILE_COUNT.0, TILE_COUNT.1)?));
+ out.insert("maxOffset".into(), json!(int_in(f, "TlOf", TILE_OFFSET.0, TILE_OFFSET.1)?));
+ out.insert("fill".into(), json!(enum_from(f, "FlCl", "FlCl", &TILE_FILLS)?));
+ for (psd, ours) in [("FrgC", "foreground"), ("BckC", "background")] {
+ if item.get(psd).is_some() {
+ out.insert(ours.into(), get_desc(item, psd).and_then(rgbc_colour)?);
+ }
+ }
+ Some(J::Object(out))
+}
+
+/// Offset › Undefined Areas: the `FlMd` enum (`Fl `) and our `undefinedAreas`. On a layer
+/// Photoshop labels `Bckg` "Set to Transparent"; a smart object is always a layer.
+const OFFSET_FILL: [(&str, &str); 3] = [("Wrp ", "wrap"), ("Rpt ", "repeat"), ("Bckg", "transparent")];
+
+/// Custom's ranges in Photoshop's dialog: matrix cells, Scale, Offset.
+const CUSTOM_CELL: (i32, i32) = (-999, 999);
+const CUSTOM_SCALE: (i32, i32) = (1, 9999);
+const CUSTOM_OFFSET: (i32, i32) = (-9999, 9999);
+
+/// `v` when it lies in `lo..=hi`.
+fn long_in_range(v: Option<i32>, (lo, hi): (i32, i32)) -> Option<i32> {
+ v.filter(|v| (lo..=hi).contains(v))
+}
+
+/// `filter.other.custom` params for a `Cstm` filter: `Mtrx` is 25 longs, row-major 5 × 5. Values
+/// outside Photoshop's ranges are not modelled (the filter stays verbatim).
+fn custom_params(f: &Descriptor) -> Option<J> {
+ let Some(Value::List(m)) = f.get("Mtrx") else { return None };
+ if m.len() != 25 {
+ return None;
+ }
+ let kernel: Option<Vec<J>> = m.iter().map(|v| long_in_range(int_value(v), CUSTOM_CELL).map(|v| json!(v))).collect();
+ let scale = long_in_range(int(f, "Scl "), CUSTOM_SCALE)?;
+ let offset = long_in_range(int(f, "Ofst"), CUSTOM_OFFSET)?;
+ Some(json!({"kernel": kernel?, "scale": scale, "offset": offset}))
+}
+
/// Our command and parameters for a known Photoshop filter; `None` when the filter (or one of its
-/// settings) is not modelled.
-fn known_params(class: &str, f: Option<&Descriptor>) -> Option<(&'static str, J)> {
+/// settings) is not modelled. `item` is the whole `filterFX` entry (Pointillize reads its `BckC`,
+/// Tiles its colours).
+fn known_params(class: &str, f: Option<&Descriptor>, item: &Descriptor) -> Option<(&'static str, J)> {
let k = KNOWN.iter().find(|k| k.class == class)?;
let params = match (class, f) {
- ("adaptCorrect", None) => json!({}),
+ ("adaptCorrect" | "Invr", None) => json!({}),
+ (c, None) if NO_OPTIONS.contains(&c) => json!({}),
(_, None) => return None,
+ ("Pnch", Some(f)) => json!({"amount": int(f, "Amnt")?}),
+ ("Twrl", Some(f)) => json!({"angle": int(f, "Angl")?}),
- ("Rple", Some(f)) => json!({"amount": int(f, "Amnt")?, "size": enum_param(f, "RplS", &RIPPLE_SIZE)?}),
- ("Sphr", Some(f)) => json!({"amount": int(f, "Amnt")?, "mode": enum_param(f, "SphM", &SPHERIZE_MODE)?}),
- ("Plr ", Some(f)) => json!({"mode": enum_param(f, "Cnvr", &POLAR_MODE)?}),
- ("ZgZg", Some(f)) => json!({"amount": int(f, "Amnt")?, "ridges": int(f, "NmbR")?, "style": enum_param(f, "ZZTy", &ZIGZAG_STYLE)?}),
++ ("Rple", Some(f)) => json!({"amount": int(f, "Amnt")?, "size": enum_name(f, "RplS", &RIPPLE_SIZE)?}),
++ ("Sphr", Some(f)) => json!({"amount": int(f, "Amnt")?, "mode": enum_name(f, "SphM", &SPHERIZE_MODE)?}),
++ ("Plr ", Some(f)) => json!({"mode": enum_name(f, "Cnvr", &POLAR_MODE)?}),
++ ("ZgZg", Some(f)) => json!({"amount": int(f, "Amnt")?, "ridges": int(f, "NmbR")?, "style": enum_name(f, "ZZTy", &ZIGZAG_STYLE)?}),
+ ("Wave", Some(f)) => {
+ // PhotoCraft's Wave has no Scale: a scaled wave stays verbatim rather than lose it. The
+ // same for more generators than the renderer models, which would draw fewer than
+ // Photoshop did (and than the file asks for, once its cached pixels are re-rendered).
+ let generators = int(f, "NmbG")?;
+ let modelled = u32::try_from(generators).is_ok_and(|g| (1..=photocraft_algo::MAX_WAVE_GENERATORS).contains(&g));
+ if int(f, "SclH")? != 100 || int(f, "SclV")? != 100 || !modelled {
+ return None;
+ }
+ json!({
- "type": enum_param(f, "Wvtp", &WAVE_TYPE)?,
++ "type": enum_name(f, "Wvtp", &WAVE_TYPE)?,
+ "generators": generators,
+ "wavelengthMin": int(f, "WLMn")?,
+ "wavelengthMax": int(f, "WLMx")?,
+ "amplitudeMin": int(f, "AmMn")?,
+ "amplitudeMax": int(f, "AmMx")?,
- "undefinedAreas": enum_param(f, "UndA", &UNDEFINED_AREAS)?,
++ "undefinedAreas": enum_name(f, "UndA", &UNDEFINED_AREAS)?,
+ // `RndS` is a signed long; the seed is its bit pattern.
+ "seed": (int(f, "RndS")? as u32),
+ })
+ }
("GsnB" | "boxblur" | "Mdn " | "HghP" | "Mxm " | "Mnm ", Some(f)) => json!({"radius": px(f, "Rds ")?}),
("MtnB", Some(f)) => json!({"angle": int(f, "Angl")?, "distance": px(f, "Dstn")?}),
("UnsM", Some(f)) => json!({"amount": px(f, "Amnt")?, "radius": px(f, "Rds ")?, "threshold": int(f, "Thsh")?}),
@@@ -1013,9 -666,37 +1063,40 @@@ fn fltr_for(k: &Known, p: &J) -> Result
}
return Ok(None);
}
+ // No settings to write; any parameter keys an old record carries have no effect on the
+ // filter either, so nothing is lost.
+ c if NO_OPTIONS.contains(&c) => return Ok(None),
+ // Keys and order as Photoshop writes them.
+ "Pnch" => d.with("Amnt", pi(p, "amount", 50.0)),
+ "Twrl" => d.with("Angl", pi(p, "angle", 50.0)),
- "Rple" => d.with("Amnt", pi(p, "amount", 100.0)).with("RplS", enum_value(p, "size", "medium", "RplS", &RIPPLE_SIZE)?),
- "Sphr" => d.with("Amnt", pi(p, "amount", 100.0)).with("SphM", enum_value(p, "mode", "normal", "SphM", &SPHERIZE_MODE)?),
- "Plr " => d.with("Cnvr", enum_value(p, "mode", "rectangularToPolar", "Cnvr", &POLAR_MODE)?),
++ "Rple" => d.with("Amnt", pi(p, "amount", 100.0)).with("RplS", enum_param(p, "size", "medium", "RplS", &RIPPLE_SIZE)?),
++ "Sphr" => d.with("Amnt", pi(p, "amount", 100.0)).with("SphM", enum_param(p, "mode", "normal", "SphM", &SPHERIZE_MODE)?),
++ "Plr " => d.with("Cnvr", enum_param(p, "mode", "rectangularToPolar", "Cnvr", &POLAR_MODE)?),
+ "ZgZg" => {
- d.with("Amnt", pi(p, "amount", 10.0)).with("NmbR", pi(p, "ridges", 5.0)).with("ZZTy", enum_value(p, "style", "pondRipples", "ZZTy", &ZIGZAG_STYLE)?)
++ d.with("Amnt", pi(p, "amount", 10.0)).with("NmbR", pi(p, "ridges", 5.0)).with("ZZTy", enum_param(p, "style", "pondRipples", "ZZTy", &ZIGZAG_STYLE)?)
+ }
+ "Wave" => {
+ // The seed the renderer draws with (engine `filters::seed`): a u32, else a legacy signed
+ // or fractional seed, rounded and saturated, as its bit pattern.
+ let seed = match p.get("seed").and_then(J::as_u64).and_then(|s| u32::try_from(s).ok()) {
+ Some(s) => Value::Integer(s as i32),
+ None => pi(p, "seed", 0.0),
+ };
+ // The renderer draws at most MAX_WAVE_GENERATORS: write what PhotoCraft rendered, so
+ // Photoshop doesn't draw more generators than the user saw.
+ let generators = pf(p, "generators", 5.0).round().clamp(1.0, f64::from(photocraft_algo::MAX_WAVE_GENERATORS)) as i32;
- d.with("Wvtp", enum_value(p, "type", "sine", "Wvtp", &WAVE_TYPE)?)
++ d.with("Wvtp", enum_param(p, "type", "sine", "Wvtp", &WAVE_TYPE)?)
+ .with("NmbG", Value::Integer(generators))
+ .with("WLMn", pi(p, "wavelengthMin", 10.0))
+ .with("WLMx", pi(p, "wavelengthMax", 120.0))
+ .with("AmMn", pi(p, "amplitudeMin", 5.0))
+ .with("AmMx", pi(p, "amplitudeMax", 35.0))
+ .with("SclH", Value::Integer(100))
+ .with("SclV", Value::Integer(100))
- .with("UndA", enum_value(p, "undefinedAreas", "wrap", "UndA", &UNDEFINED_AREAS)?)
++ .with("UndA", enum_param(p, "undefinedAreas", "wrap", "UndA", &UNDEFINED_AREAS)?)
+ .with("RndS", seed)
+ }
+ "Invr" => return Ok(None),
_ => return Err("not a recognized filter".into()),
}))
}
@@@ -1613,8 -1255,20 +1694,20 @@@ mod tests
sf("image.adjustments.shadowsHighlights", json!({})),
// A pencil-drawn curve: 256 output levels (`Mpng`).
sf("image.adjustments.curves", json!({"pencil": true, "points": (0..256).rev().collect::<Vec<i32>>()})),
+ sf("filter.distort.pinch", json!({"amount": -28})),
+ sf("filter.distort.polarCoordinates", json!({"mode": "rectangularToPolar"})),
+ sf("filter.distort.ripple", json!({"amount": 250, "size": "small"})),
+ sf("filter.distort.spherize", json!({"amount": 60, "mode": "verticalOnly"})),
+ sf("filter.distort.twirl", json!({"angle": -355})),
+ sf(
+ "filter.distort.wave",
+ json!({"type": "square", "generators": 3, "wavelengthMin": 20, "wavelengthMax": 90, "amplitudeMin": 4, "amplitudeMax": 30,
+ "undefinedAreas": "repeat", "seed": 4_000_000_000u32}),
+ ),
+ sf("filter.distort.zigZag", json!({"amount": 30, "ridges": 7, "style": "aroundCenter"})),
+ sf("image.adjustments.invert", json!({})),
];
- for mut f in filters {
+ for mut f in filters.into_iter().chain(wind_extrude_tiles_settings()) {
f.blend = BlendMode::Overlay;
f.opacity = 0.75;
f.visible = false;
@@@ -1625,835 -1279,188 +1718,1006 @@@
}
}
+ /// The filters without options, their measured `filterID`s (as Photoshop wrote them).
+ const MEASURED_NO_OPTIONS: [(&str, i32); 11] = [
+ ("filter.blur.blur", 1114403360),
+ ("filter.blur.blurMore", 1114403405),
+ ("filter.blur.average", 1098281575),
+ ("filter.noise.despeckle", 1148416099),
+ ("filter.stylize.findEdges", 1181639749),
+ ("filter.pixelate.facet", 1180922912),
+ ("filter.pixelate.fragment", 1181902701),
+ ("filter.sharpen.sharpen", 1399353968),
+ ("filter.sharpen.sharpenMore", 1399353933),
+ ("filter.sharpen.sharpenEdges", 1399353925),
+ ("filter.stylize.solarize", 1399616122),
+ ];
+
+ /// A filter without options as Photoshop saves it: `hasoptions` false, no `Fltr`, a localized
+ /// name and the current colours.
+ fn photoshop_no_options_item(name: &str, filter_id: Value) -> Descriptor {
+ let rgb = |r: f64, g: f64, b: f64| {
+ Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(r)).with("Grn ", Value::Double(g)).with("Bl ", Value::Double(b)))
+ };
+ Descriptor::new("filterFX")
+ .with("Nm ", Value::Text(UnicodeString::new_nul(name)))
+ .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 60.0)).with("Md ", enumv("BlnM", "Mltp"))))
+ .with("enab", Value::Boolean(false))
+ .with("hasoptions", Value::Boolean(false))
+ .with("FrgC", rgb(167.0, 157.0, 147.0))
+ .with("BckC", rgb(255.0, 255.0, 255.0))
+ .with("filterID", filter_id)
+ }
+
+ #[test]
+ fn filters_without_options_round_trip_in_the_measured_shape() {
+ let keys = ["Nm ", "blendOptions", "enab", "hasoptions", "FrgC", "BckC", "filterID"];
+ for (command, id) in MEASURED_NO_OPTIONS {
+ let mut f = sf(command, json!({}));
+ f.blend = BlendMode::Overlay;
+ f.opacity = 0.75;
+ f.visible = false;
+ let d = item_for_filter(&f).unwrap();
+ let got: Vec<String> = d.items.iter().map(|(k, _)| String::from_utf8_lossy(k.as_bytes()).into_owned()).collect();
+ assert_eq!(got, keys, "{command}");
+ assert_eq!(d.get("hasoptions"), Some(&Value::Boolean(false)), "{command}");
+ assert_eq!(d.get("filterID"), Some(&Value::Integer(id)), "{command}");
+ let back = filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap());
+ assert_eq!(back, f, "{command}");
+ // Keys an old record may carry have no effect on these filters: still written.
+ let extra = item_for_filter(&sf(command, json!({"radius": 3.0, "layer": "L"}))).unwrap();
+ assert_eq!(extra.get("filterID"), Some(&Value::Integer(id)), "{command}");
+ for p in [json!(null), json!("x"), json!([1, 2])] {
+ assert!(item_for_filter(&sf(command, p)).is_ok(), "{command}");
+ }
+ }
+ }
+
+ #[test]
+ fn photoshop_filters_without_options_open_editable() {
+ for (command, id) in MEASURED_NO_OPTIONS {
+ let item = photoshop_no_options_item("Weichzeichnen", Value::Integer(id));
+ let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap());
+ assert_eq!(f.command, command);
+ assert_eq!(f.params, json!({}));
+ assert_eq!((f.visible, f.blend), (false, BlendMode::Multiply));
+ assert!((f.opacity - 0.6).abs() < 1e-6);
+ }
+ }
+
+ #[test]
+ fn malformed_filters_without_options_are_kept_verbatim() {
+ let blur = code(b"Blr ");
+ let cases = [
+ // An id no filter has, a missing id, ids of the wrong type.
+ photoshop_no_options_item("X", Value::Integer(code(b"Zzzz"))),
+ Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)),
+ photoshop_no_options_item("X", Value::Double(f64::from(blur))),
+ photoshop_no_options_item("X", Value::Double(f64::NAN)),
+ photoshop_no_options_item("X", Value::Text(UnicodeString::new_nul("Blr "))),
+ photoshop_no_options_item("X", Value::Integer(-1)),
+ // Settings we don't know of on a filter that has none.
+ photoshop_no_options_item("X", Value::Integer(blur)).with("Fltr", Value::Descriptor(Descriptor::new("Blr ").with("Amnt", Value::Integer(5)))),
+ ];
+ for item in cases {
+ let f = filter_from_item(&item);
+ assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}");
+ // Written back (a bare item gains blending and visibility) and still not editable.
+ let back = filter_from_item(&item_for_filter(&f).unwrap());
+ assert_eq!((back.command.as_str(), &back.params["filterID"]), (UNSUPPORTED_FILTER, &f.params["filterID"]));
+ }
+ }
+
+ /// Smart Sharpen's `Fltr` in the measured shape (no `presetKind`, no `Angl`).
+ fn smart_sharpen(amount: f64, radius: f64, noise: f64, blur: &str) -> Descriptor {
+ Descriptor::new("smartSharpen")
+ .with("useLegacy", Value::Boolean(false))
+ .with("Amnt", unit(b"#Prc", amount))
+ .with("Rds ", unit(b"#Pxl", radius))
+ .with("noiseReduction", unit(b"#Prc", noise))
+ .with("blur", enumv("blurType", blur))
+ }
+
+ fn dust(radius: i32, threshold: i32) -> Descriptor {
+ Descriptor::new("DstS").with("Rds ", Value::Integer(radius)).with("Thsh", Value::Integer(threshold))
+ }
+
+ /// The `Fltr` descriptor PhotoCraft writes for `f`, after a byte round trip.
+ fn written_fltr(f: &SmartFilter) -> Descriptor {
+ let d = Descriptor::from_bytes(&item_for_filter(f).unwrap().to_bytes()).unwrap();
+ get_desc(&d, "Fltr").unwrap().clone()
+ }
+
+ /// Measured in Photoshop: Smart Sharpen 120 %, 2.5 px, noise 5 %, Gaussian Blur
+ /// (filterID 1131); the default entry adds `presetKind` first, which is not kept.
+ #[test]
+ fn smart_sharpen_photoshop_entry_opens_and_writes_back() {
+ let fltr = smart_sharpen(120.0, 2.5, 5.0, "GsnB");
+ let item = ps_item("Smart Sharpen...", fltr.clone(), 1131);
+ let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap());
+ assert_eq!(f.command, "filter.sharpen.smartSharpen");
+ assert_eq!(f.params, json!({"amount": 120.0, "radius": 2.5, "reduceNoise": 5.0}));
+ assert_eq!(written_fltr(&f), fltr);
+ let d = item_for_filter(&f).unwrap();
+ assert_eq!(int(&d, "filterID"), Some(1131));
+ assert_eq!(get_desc(&d, "Fltr").unwrap().class_id, Id::Str(b"smartSharpen".to_vec()));
+ // The four-character keys and enum values are codes, as Photoshop writes them.
+ let bytes = d.to_bytes();
+ assert_eq!(count(&bytes, b"\0\0\0\0blurenum\0\0\0\x08blurType\0\0\0\0GsnB"), 1);
+ assert_eq!(count(&bytes, b"\0\0\0\0Rds UntF#Pxl"), 1);
+
+ // With `presetKind` (any value): opens, but the params hold only the engine's own keys
+ // (it rejects unknown ones), and a re-save leaves it out as Photoshop does for explicit
+ // values.
+ for kind in ["presetKindDefault", "presetKindCustom", "Xxxx"] {
+ let mut with_preset = Descriptor::new("smartSharpen").with("presetKind", enumv("presetKindType", kind));
+ with_preset.items.extend(smart_sharpen(200.0, 1.0, 10.0, "GsnB").items);
+ let f = filter_from_item(&Descriptor::from_bytes(&ps_item("Smart Sharpen...", with_preset, 1131).to_bytes()).unwrap());
+ assert_eq!(f.command, "filter.sharpen.smartSharpen");
+ let keys: Vec<&str> = f.params.as_object().unwrap().keys().map(String::as_str).collect();
+ assert_eq!(keys.len(), 3, "{keys:?}");
+ assert!(keys.iter().all(|k| ["amount", "radius", "reduceNoise"].contains(k)), "{keys:?}");
+ assert_eq!(f.params, json!({"amount": 200.0, "radius": 1.0, "reduceNoise": 10.0}));
+ assert_eq!(written_fltr(&f), smart_sharpen(200.0, 1.0, 10.0, "GsnB"));
+ }
+
+ // Without options PhotoCraft writes the engine's defaults, Gaussian Blur.
+ assert_eq!(written_fltr(&sf("filter.sharpen.smartSharpen", json!({}))), smart_sharpen(100.0, 1.0, 10.0, "GsnB"));
+ }
+
+ /// Lens Blur (Photoshop's default), Motion Blur and legacy mode render differently from
+ /// PhotoCraft's Smart Sharpen, so those entries stay verbatim.
+ #[test]
+ fn smart_sharpen_settings_we_dont_render_stay_verbatim() {
+ let mut default_entry = Descriptor::new("smartSharpen").with("presetKind", enumv("presetKindType", "presetKindDefault"));
+ default_entry.items.extend(smart_sharpen(200.0, 1.0, 10.0, "lensBlur").items);
+ let motion = smart_sharpen(80.0, 1.5, 0.0, "MtnB").with("Angl", Value::Integer(30));
+ let mut legacy = smart_sharpen(100.0, 1.0, 10.0, "GsnB");
+ set(&mut legacy, "useLegacy", Value::Boolean(true));
+ for fltr in [default_entry, motion, legacy] {
+ let item = ps_item("Smart Sharpen...", fltr, 1131);
+ let f = filter_from_item(&item);
+ assert_eq!(f.command, UNSUPPORTED_FILTER);
+ assert_eq!(f.params["filterID"], 1131);
+ assert_eq!(item_for_filter(&f).unwrap(), item);
+ }
+ }
+
+ #[test]
+ fn malformed_smart_sharpen_is_kept_verbatim() {
+ let g = || smart_sharpen(100.0, 1.0, 10.0, "GsnB");
+ let without = |key: &str| {
+ let mut d = g();
+ d.items.retain(|(k, _)| !k.is(key));
+ d
+ };
+ let with = |key: &str, v: Value| {
+ let mut d = g();
+ set(&mut d, key, v);
+ d
+ };
+ let cases = vec![
+ without("useLegacy"),
+ without("Amnt"),
+ without("Rds "),
+ without("noiseReduction"),
+ without("blur"),
+ with("Amnt", Value::Double(100.0)),
+ with("Amnt", unit(b"#Pxl", 100.0)),
+ with("Rds ", Value::Integer(1)),
+ with("useLegacy", Value::Integer(0)),
+ with("Amnt", unit(b"#Prc", 0.0)),
+ with("Amnt", unit(b"#Prc", 501.0)),
+ with("Rds ", unit(b"#Pxl", 0.05)),
+ with("Rds ", unit(b"#Pxl", 65.0)),
+ with("Rds ", unit(b"#Pxl", f64::NAN)),
+ with("noiseReduction", unit(b"#Prc", -1.0)),
+ with("noiseReduction", unit(b"#Prc", f64::INFINITY)),
+ with("blur", enumv("blurType", "Xxxx")),
+ with("blur", enumv("BlrM", "GsnB")),
+ with("blur", Value::Integer(0)),
+ with("presetKind", Value::Integer(1)),
+ g().with("Angl", Value::Integer(30)),
+ g().with("shadowMode", Value::Descriptor(Descriptor::new("adaptCorrectTones"))),
+ ];
+ for fltr in cases {
+ let item = ps_item("Smart Sharpen...", fltr, 1131);
+ let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap());
+ assert_eq!(f.command, UNSUPPORTED_FILTER, "{:?}", get_desc(&item, "Fltr"));
+ assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes());
+ }
+ // No `Fltr` at all (hasoptions false).
+ let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(1131));
+ assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER);
+ }
+
+ /// Measured in Photoshop: Dust & Scratches at its defaults (1, 0) and at 4, 20 (filterID
+ /// `DstS`, 1148417107; both settings `long`).
+ #[test]
+ fn dust_and_scratches_photoshop_entry_opens_and_writes_back() {
+ for (radius, threshold) in [(1, 0), (4, 20), (500, 255)] {
+ let fltr = dust(radius, threshold);
+ let item = ps_item("Dust & Scratches...", fltr.clone(), 1_148_417_107);
+ let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap());
+ assert_eq!(f.command, "filter.noise.dustAndScratches");
+ assert_eq!(f.params, json!({"radius": radius, "threshold": threshold}));
+ assert_eq!(written_fltr(&f), fltr);
+ assert_eq!(int(&item_for_filter(&f).unwrap(), "filterID"), Some(1_148_417_107));
+ }
+ // No `Fltr` (hasoptions false): kept verbatim.
+ let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"DstS")));
+ assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER);
+ }
+
+ #[test]
+ fn malformed_dust_and_scratches_is_kept_verbatim() {
+ let cases = vec![
+ Descriptor::new("DstS").with("Thsh", Value::Integer(0)),
+ Descriptor::new("DstS").with("Rds ", Value::Integer(1)),
+ Descriptor::new("DstS").with("Rds ", Value::Double(1.0)).with("Thsh", Value::Integer(0)),
+ Descriptor::new("DstS").with("Rds ", unit(b"#Pxl", 1.0)).with("Thsh", Value::Integer(0)),
+ Descriptor::new("DstS").with("Rds ", Value::Integer(1)).with("Thsh", Value::Boolean(false)),
+ dust(0, 0),
+ dust(501, 0),
+ dust(1, -1),
+ dust(1, 256),
+ dust(i32::MIN, i32::MAX),
+ dust(1, 0).with("Xtra", Value::Integer(1)),
+ ];
+ for fltr in cases {
+ let item = ps_item("Dust & Scratches...", fltr, code(b"DstS"));
+ let f = filter_from_item(&item);
+ assert_eq!(f.command, UNSUPPORTED_FILTER, "{:?}", get_desc(&item, "Fltr"));
+ assert_eq!(item_for_filter(&f).unwrap(), item);
+ }
+ }
+
+ /// Every option's range ends round trip; hostile params are written in range (the engine
+ /// clamps the same way), never a panic.
+ #[test]
+ fn smart_sharpen_and_dust_option_values_round_trip() {
+ let mut cases = Vec::new();
+ for amount in [1.0, 100.0, 500.0] {
+ for radius in [0.1, 1.0, 64.0] {
+ for noise in [0.0, 10.0, 100.0] {
+ cases.push(sf("filter.sharpen.smartSharpen", json!({"amount": amount, "radius": radius, "reduceNoise": noise})));
+ }
+ }
+ }
+ for radius in [1, 2, 100, 500] {
+ for threshold in [0, 1, 128, 255] {
+ cases.push(sf("filter.noise.dustAndScratches", json!({"radius": radius, "threshold": threshold})));
+ }
+ }
+ for f in cases {
+ let back = filter_from_item(&Descriptor::from_bytes(&item_for_filter(&f).unwrap().to_bytes()).unwrap());
+ assert_eq!(back, f);
+ }
+ let defaults = json!({"amount": 100.0, "radius": 1.0, "reduceNoise": 10.0});
+ for (command, p, want) in [
+ (
+ "filter.sharpen.smartSharpen",
+ json!({"amount": 1e9, "radius": -5.0, "reduceNoise": "x"}),
+ json!({"amount": 500.0, "radius": 0.1, "reduceNoise": 10.0}),
+ ),
+ ("filter.sharpen.smartSharpen", json!({"presetKind": "presetKindDefault", "amount": null}), defaults.clone()),
+ ("filter.sharpen.smartSharpen", json!(null), defaults.clone()),
+ ("filter.noise.dustAndScratches", json!({"radius": 2.4, "threshold": 1e12}), json!({"radius": 2, "threshold": 255})),
+ ("filter.noise.dustAndScratches", json!({"radius": -3, "threshold": -3}), json!({"radius": 1, "threshold": 0})),
+ ("filter.noise.dustAndScratches", json!([]), json!({"radius": 1, "threshold": 0})),
+ ] {
+ let back = filter_from_item(&item_for_filter(&sf(command, p.clone())).unwrap());
+ assert_eq!((back.command.as_str(), &back.params), (command, &want), "{p}");
+ }
+ }
+
+ /// Every option value of Wind, Extrude and Tiles (and the ends of their ranges).
+ fn wind_extrude_tiles_settings() -> Vec<SmartFilter> {
+ let mut v = Vec::new();
+ for method in ["wind", "blast", "stagger"] {
+ for direction in ["fromRight", "fromLeft"] {
+ v.push(sf("filter.stylize.wind", json!({"method": method, "direction": direction})));
+ }
+ }
+ for t in ["blocks", "pyramids"] {
+ for mode in ["random", "levelBased"] {
+ for (solid, mask) in [(false, false), (true, false), (false, true), (true, true)] {
+ v.push(sf(
+ "filter.stylize.extrude",
+ json!({"type": t, "size": 7, "depth": 9, "depthMode": mode, "solidFrontFaces": solid, "maskIncompleteBlocks": mask}),
+ ));
+ }
+ }
+ }
+ v.push(sf(
+ "filter.stylize.extrude",
+ json!({"type": "blocks", "size": 2, "depth": 1, "depthMode": "random", "solidFrontFaces": false, "maskIncompleteBlocks": false}),
+ ));
+ v.push(sf(
+ "filter.stylize.extrude",
+ json!({"type": "pyramids", "size": 255, "depth": 255, "depthMode": "levelBased", "solidFrontFaces": true, "maskIncompleteBlocks": true}),
+ ));
+ for fill in ["background", "foreground", "inverse", "unaltered"] {
+ v.push(sf(
+ "filter.stylize.tiles",
+ json!({"count": 6, "maxOffset": 20, "fill": fill, "foreground": [1.0, 0.0, 0.5, 1.0], "background": [0.0, 0.5, 1.0, 1.0]}),
+ ));
+ }
+ for (count, offset) in [(1, 1), (99, 99)] {
+ v.push(sf(
+ "filter.stylize.tiles",
+ json!({"count": count, "maxOffset": offset, "fill": "background", "foreground": [0.0, 0.0, 0.0, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}),
+ ));
+ }
+ v
+ }
+
+ /// A `filterFX` entry shaped as Photoshop saves Wind, Extrude and Tiles (measured in Photoshop:
+ /// applied through Action Manager to a smart object, saved, `filterFX` read back): the item's
+ /// `FrgC`/`BckC` are the document colours, `Fltr` holds the settings, `filterID` the class code.
+ fn measured_item(fltr: Descriptor, fg: f64, bg: f64) -> Descriptor {
+ let id = code(fltr.class_id.as_bytes().try_into().unwrap());
+ Descriptor::new("filterFX")
+ .with("Nm ", Value::Text(UnicodeString::new_nul("Filter...")))
+ .with("blendOptions", blend_options(&sf("", J::Null)))
+ .with("enab", Value::Boolean(true))
+ .with("hasoptions", Value::Boolean(true))
+ .with("FrgC", rgbc(fg))
+ .with("BckC", rgbc(bg))
+ .with("Fltr", Value::Descriptor(fltr))
+ .with("filterID", Value::Integer(id))
+ }
+
+ /// The `Fltr` descriptors Photoshop 27 wrote for these filters (one smart object each, saved as
+ /// PSD and read back), with the settings PhotoCraft reads from them.
+ const PHOTOSHOP_FLTR: [(&str, &str, &str); 6] = [
+ ("filter.distort.pinch", r#"{"amount":-28}"#, "0000000600500069006e00630068000000000000506e63680000000100000000416d6e746c6f6e67ffffffe4"),
+ ("filter.distort.twirl", r#"{"angle":-355}"#, "000000060054007700690072006c0000000000005477726c0000000100000000416e676c6c6f6e67fffffe9d"),
+ (
+ "filter.distort.ripple",
+ r#"{"amount":-273,"size":"large"}"#,
+ "000000070052006900700070006c006500000000000052706c650000000200000000416d6e746c6f6e67fffffeef0000000052706c53656e756d0000000052706c53000000004c726720",
+ ),
+ (
+ "filter.distort.spherize",
+ r#"{"amount":-1,"mode":"horizontalOnly"}"#,
+ "00000009005300700068006500720069007a0065000000000000537068720000000200000000416d6e746c6f6e67ffffffff000000005370684d656e756d000000005370684d0000000048727a4f",
+ ),
+ (
+ "filter.distort.polarCoordinates",
+ r#"{"mode":"polarToRectangular"}"#,
+ "000000120050006f006c0061007200200043006f006f007200640069006e0061007400650073000000000000506c72200000000100000000436e7672656e756d00000000436e767200000000506c7252",
+ ),
+ (
+ "filter.distort.zigZag",
+ r#"{"amount":-42,"ridges":11,"style":"pondRipples"}"#,
+ "00000007005a00690067005a006100670000000000005a675a670000000300000000416d6e746c6f6e67ffffffd6000000004e6d62526c6f6e670000000b000000005a5a5479656e756d000000005a5a547900000000506e6452",
+ ),
+ ];
+
+ /// Photoshop's Wave with Scale 100% / 28%: PhotoCraft's Wave has no Scale.
+ const PHOTOSHOP_WAVE: &str = "000000050057006100760065000000000000576176650000000a0000000057767470656e756d00000000577674700000000057765472000000004e6d62476c6f6e670000014c00000000574c4d6e6c6f6e67000000d500000000574c4d786c6f6e67000000d600000000416d4d6e6c6f6e67000000f000000000416d4d786c6f6e67000000f10000000053636c486c6f6e67000000640000000053636c566c6f6e670000001c00000000556e6441656e756d00000000556e6441000000005772704100000000526e64536c6f6e670013624a";
+
+ /// A `filterFX` list item as Photoshop writes it (enabled, Normal at 100%, with options), wrapping the `Fltr` descriptor `fltr`.
- fn photoshop_item(fltr: Descriptor) -> Descriptor {
++ fn photoshop_fltr_item(fltr: Descriptor) -> Descriptor {
+ let id = code(fltr.class_id.as_bytes().try_into().unwrap());
+ Descriptor::new("filterFX")
+ .with("Nm ", Value::Text(UnicodeString::new_nul("from Photoshop")))
+ .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal"))))
+ .with("enab", Value::Boolean(true))
+ .with("hasoptions", Value::Boolean(true))
+ .with("Fltr", Value::Descriptor(fltr))
+ .with("filterID", Value::Integer(id))
+ }
+
+ fn wind(method: &str, direction: &str) -> Descriptor {
+ Descriptor::new("Wnd ").with("WndM", enumv("WndM", method)).with("Drct", enumv("Drct", direction))
+ }
+
+ fn extrude(t: &str, size: Value, depth: Value, mode: &str, solid: Value, mask: Value) -> Descriptor {
+ Descriptor::new("Extr")
+ .with("ExtT", enumv("ExtT", t))
+ .with("ExtS", size)
+ .with("ExtD", depth)
+ .with("ExtR", enumv("ExtR", mode))
+ .with("ExtF", solid)
+ .with("ExtM", mask)
+ }
+
+ fn tiles(count: Value, offset: Value, fill: &str) -> Descriptor {
+ Descriptor::new("Tls ").with("TlNm", count).with("TlOf", offset).with("FlCl", enumv("FlCl", fill))
+ }
+
+ #[test]
+ fn wind_extrude_tiles_open_from_photoshop_shapes() {
+ let (long, yes, no) = (Value::Integer, Value::Boolean(true), Value::Boolean(false));
+ let cases = [
+ // The measured files.
+ (wind("Blst", "Left"), "filter.stylize.wind", json!({"method": "blast", "direction": "fromRight"})),
+ (wind("Stgr", "Rght"), "filter.stylize.wind", json!({"method": "stagger", "direction": "fromLeft"})),
+ (wind("Wnd ", "Rght"), "filter.stylize.wind", json!({"method": "wind", "direction": "fromLeft"})),
+ (
+ extrude("Blks", long(7), long(9), "Rndm", yes.clone(), no.clone()),
+ "filter.stylize.extrude",
+ json!({"type": "blocks", "size": 7, "depth": 9, "depthMode": "random", "solidFrontFaces": true, "maskIncompleteBlocks": false}),
+ ),
+ (
+ extrude("Pyrm", long(12), long(20), "LvlB", no, yes),
+ "filter.stylize.extrude",
+ json!({"type": "pyramids", "size": 12, "depth": 20, "depthMode": "levelBased", "solidFrontFaces": false, "maskIncompleteBlocks": true}),
+ ),
+ (
+ tiles(long(6), long(20), "FlFr"),
+ "filter.stylize.tiles",
+ json!({"count": 6, "maxOffset": 20, "fill": "foreground", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}),
+ ),
+ (
+ tiles(long(4), long(5), "FlIn"),
+ "filter.stylize.tiles",
+ json!({"count": 4, "maxOffset": 5, "fill": "inverse", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}),
+ ),
+ (
+ tiles(long(10), long(10), "FlBc"),
+ "filter.stylize.tiles",
+ json!({"count": 10, "maxOffset": 10, "fill": "background", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}),
+ ),
+ (
+ tiles(long(99), long(1), "FlSm"),
+ "filter.stylize.tiles",
+ json!({"count": 99, "maxOffset": 1, "fill": "unaltered", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}),
+ ),
+ ];
+ for (fltr, command, params) in cases {
+ let item = measured_item(fltr, 51.0, 255.0);
+ // Through bytes, as read from a file.
+ let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap());
+ assert_eq!((f.command.as_str(), &f.params), (command, &params));
+ // Written back in the measured shape: same class, keys and their order, value types
+ // (long, bool, enum with its type), filterID; Tiles also its colours.
+ let back = item_for_filter(&f).unwrap();
+ assert_eq!(get_desc(&back, "Fltr").map(Descriptor::to_bytes), get_desc(&item, "Fltr").map(Descriptor::to_bytes), "{command}");
+ assert_eq!(back.get("filterID"), item.get("filterID"), "{command}");
+ if command == "filter.stylize.tiles" {
+ assert_eq!((back.get("FrgC"), back.get("BckC")), (item.get("FrgC"), item.get("BckC")));
+ }
+ }
+ // The class codes: numeric filterIDs of the four-char classes.
+ for (c, id) in [("filter.stylize.wind", 1466852384), ("filter.stylize.extrude", 1165522034), ("filter.stylize.tiles", 1416393504)] {
+ assert_eq!(item_for_filter(&sf(c, json!({}))).unwrap().get("filterID"), Some(&Value::Integer(id)));
+ }
+ // A filter found by its filterID alone (no `Fltr` class to go by) still needs its settings.
+ let bare = Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)).with("filterID", Value::Integer(1466852384));
+ assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER);
+ // Only Tiles reads the entry's colours; Wind and Extrude write the defaults.
+ let f = filter_from_item(&measured_item(wind("Wnd ", "Left"), 51.0, 0.0));
+ assert_eq!(f.params, json!({"method": "wind", "direction": "fromRight"}));
+ let back = item_for_filter(&f).unwrap();
+ assert_eq!((back.get("FrgC"), back.get("BckC")), (Some(&rgbc(0.0)), Some(&rgbc(255.0))));
+ // Tiles without colours in its params (or the entry) writes the engine's black and white.
+ let f = filter_from_item(&Descriptor::new("filterFX").with("Fltr", Value::Descriptor(tiles(long(4), long(5), "FlBc"))));
+ assert_eq!(f.params, json!({"count": 4, "maxOffset": 5, "fill": "background"}));
+ let back = item_for_filter(&f).unwrap();
+ assert_eq!((back.get("FrgC"), back.get("BckC")), (Some(&rgbc(0.0)), Some(&rgbc(255.0))));
+ }
+
+ #[test]
+ fn wind_extrude_tiles_write_defaults_and_photoshop_ranges() {
+ let fltr = |c: &str, p: J| match item_for_filter(&sf(c, p)).unwrap().get("Fltr") {
+ Some(Value::Descriptor(d)) => d.clone(),
+ other => panic!("no Fltr: {other:?}"),
+ };
+ let long = Value::Integer;
+ let (yes, no) = (Value::Boolean(true), Value::Boolean(false));
+ // Defaults are the engine's; our random seed has no PSD key and is not written.
+ assert_eq!(fltr("filter.stylize.wind", json!({"seed": 9})), wind("Wnd ", "Left"));
+ assert_eq!(fltr("filter.stylize.extrude", json!({"seed": 9})), extrude("Blks", long(30), long(30), "Rndm", no.clone(), no.clone()));
+ assert_eq!(fltr("filter.stylize.tiles", json!({"seed": 9})), tiles(long(10), long(10), "FlBc"));
+ // Out of range, fractional, non-numeric and non-bool values as the engine reads them.
+ assert_eq!(
+ fltr("filter.stylize.extrude", json!({"size": 1e12, "depth": -5, "solidFrontFaces": "yes", "maskIncompleteBlocks": true})),
+ extrude("Blks", long(255), long(1), "Rndm", no.clone(), yes)
+ );
+ assert_eq!(fltr("filter.stylize.tiles", json!({"count": 0, "maxOffset": 12.6})), tiles(long(1), long(13), "FlBc"));
+ assert_eq!(fltr("filter.stylize.tiles", json!({"count": "many", "maxOffset": 1000})), tiles(long(10), long(99), "FlBc"));
+ assert_eq!(fltr("filter.stylize.extrude", json!({"size": f64::NAN})), extrude("Blks", long(30), long(30), "Rndm", no.clone(), no));
+ }
+
+ #[test]
+ fn malformed_wind_extrude_tiles_are_kept_verbatim() {
+ let long = Value::Integer;
+ let (yes, no) = (Value::Boolean(true), Value::Boolean(false));
+ let cases = [
+ // Missing keys.
+ Descriptor::new("Wnd "),
+ Descriptor::new("Wnd ").with("WndM", enumv("WndM", "Blst")),
+ Descriptor::new("Wnd ").with("Drct", enumv("Drct", "Left")),
+ Descriptor::new("Extr").with("ExtT", enumv("ExtT", "Blks")).with("ExtS", long(7)).with("ExtD", long(9)).with("ExtR", enumv("ExtR", "Rndm")),
+ Descriptor::new("Tls ").with("TlNm", long(6)).with("TlOf", long(20)),
+ Descriptor::new("Tls ").with("TlNm", long(6)).with("FlCl", enumv("FlCl", "FlFr")),
+ // Unknown enum values and enum types (Photoshop falls back to a default for these;
+ // we keep them as they are rather than guess).
+ wind("Wild", "Left"),
+ wind("Blst", "Up "),
+ Descriptor::new("Wnd ").with("WndM", enumv("Drct", "Blst")).with("Drct", enumv("Drct", "Left")),
+ extrude("Cube", long(7), long(9), "Rndm", yes.clone(), no.clone()),
+ extrude("Blks", long(7), long(9), "Sine", yes.clone(), no.clone()),
+ tiles(long(6), long(20), "FlXx"),
+ Descriptor::new("Tls ").with("TlNm", long(6)).with("TlOf", long(20)).with("FlCl", enumv("BlnM", "FlFr")),
+ // Wrong types (also NaN).
+ Descriptor::new("Wnd ").with("WndM", long(1)).with("Drct", enumv("Drct", "Left")),
+ extrude("Blks", Value::Double(7.0), long(9), "Rndm", yes.clone(), no.clone()),
+ extrude("Blks", long(7), unit(b"#Pxl", 9.0), "Rndm", yes.clone(), no.clone()),
+ extrude("Blks", long(7), long(9), "Rndm", long(1), no.clone()),
+ extrude("Blks", long(7), long(9), "Rndm", yes.clone(), Value::Double(f64::NAN)),
+ tiles(Value::Double(f64::NAN), long(20), "FlFr"),
+ tiles(long(6), Value::Text(UnicodeString::new_nul("20")), "FlFr"),
+ // Out of range.
+ extrude("Blks", long(1), long(9), "Rndm", yes.clone(), no.clone()),
+ extrude("Blks", long(256), long(9), "Rndm", yes.clone(), no.clone()),
+ extrude("Blks", long(7), long(0), "Rndm", yes.clone(), no.clone()),
+ extrude("Blks", long(7), long(i32::MAX), "Rndm", yes, no),
+ tiles(long(0), long(20), "FlFr"),
+ tiles(long(100), long(20), "FlFr"),
+ tiles(long(6), long(0), "FlFr"),
+ tiles(long(6), long(i32::MIN), "FlFr"),
+ ];
+ for fltr in cases {
+ let item = measured_item(fltr, 0.0, 255.0);
+ let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap());
+ assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}");
+ assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes());
+ }
+ // A Tiles entry whose colour is unreadable is kept verbatim too.
+ for (key, bad) in [
+ ("FrgC", Value::Integer(3)),
+ ("BckC", Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)))),
+ (
+ "BckC",
+ Value::Descriptor(
+ Descriptor::new("RGBC").with("Rd ", Value::Double(f64::NAN)).with("Grn ", Value::Double(0.0)).with("Bl ", Value::Double(0.0)),
+ ),
+ ),
+ ] {
+ let mut item = measured_item(tiles(long(6), long(20), "FlFr"), 0.0, 255.0);
+ set(&mut item, key, bad);
+ assert_eq!(filter_from_item(&item).command, UNSUPPORTED_FILTER);
+ }
+ // Values with no PSD equivalent are reported, not guessed.
+ for (c, p) in [
+ ("filter.stylize.wind", json!({"method": "gale"})),
+ ("filter.stylize.wind", json!({"direction": "fromTop"})),
+ ("filter.stylize.wind", json!({"direction": 1})),
+ ("filter.stylize.extrude", json!({"type": "cubes"})),
+ ("filter.stylize.extrude", json!({"depthMode": null})),
+ ("filter.stylize.tiles", json!({"fill": "transparent"})),
+ ("filter.stylize.tiles", json!({"foreground": "teal"})),
+ ("filter.stylize.tiles", json!({"background": [1.0]})),
+ ("filter.stylize.tiles", json!({"background": [f64::NAN, 0.0, 0.0]})),
+ ] {
+ assert!(item_for_filter(&sf(c, p.clone())).is_err(), "{c} {p}");
+ }
+ }
+
+ /// Photoshop's default Custom kernel: a 3 × 3 sharpen centred in the 5 × 5.
+ const SHARPEN: [i32; 25] = [0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, -1, 5, -1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0];
+
+ /// A `filterFXList` item as measured in Photoshop (applied through Action Manager to a smart
+ /// object, saved, `filterFX` read back).
+ fn measured_named_item(id: &[u8; 4], name: &str, fltr: Descriptor) -> Descriptor {
+ Descriptor::new("filterFX")
+ .with("Nm ", Value::Text(UnicodeString::new_nul(name)))
+ .with("blendOptions", blend_options(&sf("", J::Null)))
+ .with("enab", Value::Boolean(true))
+ .with("hasoptions", Value::Boolean(true))
+ .with("FrgC", rgbc(0.0))
+ .with("BckC", rgbc(255.0))
+ .with("Fltr", Value::Descriptor(fltr))
+ .with("filterID", Value::Integer(code(id)))
+ }
+
+ fn offset_fltr(h: Value, v: Value, fill: Value) -> Descriptor {
+ Descriptor::new("Ofst").with("Hrzn", h).with("Vrtc", v).with("Fl ", fill)
+ }
+
+ fn custom_fltr(scale: Value, offset: Value, m: Vec<Value>) -> Descriptor {
+ Descriptor::new("Cstm").with("Scl ", scale).with("Ofst", offset).with("Mtrx", Value::List(m))
+ }
+
+ fn longs(m: &[i32]) -> Vec<Value> {
+ m.iter().map(|v| Value::Integer(*v)).collect()
+ }
+
+ #[test]
+ fn offset_round_trips_every_fill_mode() {
+ for (fill, ours) in [("Wrp ", "wrap"), ("Rpt ", "repeat"), ("Bckg", "transparent")] {
+ for (h, v) in [(0, 0), (12, -7), (5, 3), (i32::MIN, i32::MAX)] {
+ let f = sf("filter.other.offset", json!({"horizontal": h, "vertical": v, "undefinedAreas": ours}));
+ let d = item_for_filter(&f).unwrap();
+ let fltr = get_desc(&d, "Fltr").unwrap();
+ assert_eq!(*fltr, offset_fltr(Value::Integer(h), Value::Integer(v), enumv("FlMd", fill)));
+ assert_eq!(int(&d, "filterID"), Some(1_332_114_292));
+ assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f);
+ }
+ }
+ }
+
+ /// The measured descriptors (Wrap 0/0, Set to Background 12/−7, Repeat 5/3) open as Offset.
+ #[test]
+ fn offset_measured_descriptors_open_as_offset() {
+ for (h, v, fill, ours) in [(0, 0, "Wrp ", "wrap"), (12, -7, "Bckg", "transparent"), (5, 3, "Rpt ", "repeat")] {
+ let item = measured_named_item(b"Ofst", "Offset...", offset_fltr(Value::Integer(h), Value::Integer(v), enumv("FlMd", fill)));
+ let f = filter_from_item(&item);
+ assert_eq!(f.command, "filter.other.offset");
+ assert_eq!(f.params, json!({"horizontal": h, "vertical": v, "undefinedAreas": ours}));
+ // Written back exactly as measured.
+ assert_eq!(item_for_filter(&f).unwrap(), item);
+ }
+ }
+
+ #[test]
+ fn offset_written_with_engine_defaults() {
+ // No params: 0, 0, Wrap Around (the engine's defaults); fractional pixels round.
+ let d = item_for_filter(&sf("filter.other.offset", json!({}))).unwrap();
+ assert_eq!(*get_desc(&d, "Fltr").unwrap(), offset_fltr(Value::Integer(0), Value::Integer(0), enumv("FlMd", "Wrp ")));
+ let d = item_for_filter(&sf("filter.other.offset", json!({"horizontal": 2.6, "vertical": 3e12, "undefinedAreas": "bogus"}))).unwrap();
+ assert_eq!(*get_desc(&d, "Fltr").unwrap(), offset_fltr(Value::Integer(3), Value::Integer(i32::MAX), enumv("FlMd", "Wrp ")));
+ }
+
+ #[test]
+ fn malformed_offset_is_kept_verbatim() {
+ let i = Value::Integer;
+ for fltr in [
+ offset_fltr(i(1), i(2), enumv("FlMd", "Xxxx")),
+ offset_fltr(i(1), i(2), Value::Integer(1)),
+ offset_fltr(Value::Double(1.5), i(2), enumv("FlMd", "Wrp ")),
+ offset_fltr(i(1), unit(b"#Pxl", f64::NAN), enumv("FlMd", "Wrp ")),
+ Descriptor::new("Ofst").with("Hrzn", i(1)).with("Fl ", enumv("FlMd", "Wrp ")),
+ Descriptor::new("Ofst"),
+ ] {
+ let item = measured_named_item(b"Ofst", "Offset...", fltr);
+ let f = filter_from_item(&item);
+ assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}");
+ assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "kept byte for byte");
+ }
+ let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"Ofst")));
+ assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER);
+ }
+
+ #[test]
+ fn custom_round_trips() {
+ let edge: Vec<i32> = (0..25)
+ .map(|i| {
+ if i == 12 {
+ 8
+ } else if (6..=18).contains(&i) && i % 5 != 0 && i % 5 != 4 {
+ -1
+ } else {
+ 0
+ }
+ })
+ .collect();
+ let full: Vec<i32> = (0..25).map(|i| i * 83 - 999).collect();
+ for (kernel, scale, offset) in [(SHARPEN.to_vec(), 1, 0), (edge, 2, 10), (full, 9999, -9999), (vec![999; 25], 1, 9999)] {
+ let f = sf("filter.other.custom", json!({"kernel": kernel, "scale": scale, "offset": offset}));
+ let d = item_for_filter(&f).unwrap();
+ assert_eq!(*get_desc(&d, "Fltr").unwrap(), custom_fltr(Value::Integer(scale), Value::Integer(offset), longs(&kernel)));
+ assert_eq!(int(&d, "filterID"), Some(1_131_639_917));
+ assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f);
+ }
+ }
+
+ /// The measured descriptors (the default sharpen; a blur at Scale 2, Offset 10) open as Custom.
+ #[test]
+ fn custom_measured_descriptors_open_as_custom() {
+ let blur = [0, 0, 0, 0, 0, 0, 1, 2, 1, 0, 0, 2, 4, 2, 0, 0, 1, 2, 1, 0, 0, 0, 0, 0, 0];
+ for (kernel, scale, offset) in [(SHARPEN, 1, 0), (blur, 2, 10)] {
+ let item = measured_named_item(b"Cstm", "Custom...", custom_fltr(Value::Integer(scale), Value::Integer(offset), longs(&kernel)));
+ let f = filter_from_item(&item);
+ assert_eq!(f.command, "filter.other.custom");
+ assert_eq!(f.params, json!({"kernel": kernel, "scale": scale, "offset": offset}));
+ assert_eq!(item_for_filter(&f).unwrap(), item);
+ }
+ }
+
+ #[test]
+ fn custom_written_like_the_engine_reads_it() {
+ let fltr = |p: J| get_desc(&item_for_filter(&sf("filter.other.custom", p)).unwrap(), "Fltr").cloned().unwrap();
+ // No kernel: the engine's identity; short kernels pad with 0; out-of-range values clamp.
+ let mut id = [0; 25];
+ id[12] = 1;
+ assert_eq!(fltr(json!({})), custom_fltr(Value::Integer(1), Value::Integer(0), longs(&id)));
+ let mut short = [0; 25];
+ short[0] = 3;
+ short[1] = -999;
+ assert_eq!(fltr(json!({"kernel": [3, -5000], "scale": 0, "offset": 20000})), custom_fltr(Value::Integer(1), Value::Integer(9999), longs(&short)));
+ // Fractions have no PSD equivalent.
+ for p in [json!({"kernel": [0.5]}), json!({"scale": 1.5}), json!({"offset": -0.25})] {
+ assert!(item_for_filter(&sf("filter.other.custom", p.clone())).is_err(), "{p}");
+ }
+ }
+
+ #[test]
+ fn malformed_custom_is_kept_verbatim() {
+ let i = Value::Integer;
+ let mut wrong_type = longs(&SHARPEN);
+ wrong_type[3] = Value::Double(1.0);
+ for fltr in [
+ custom_fltr(i(1), i(0), longs(&SHARPEN[..24])),
+ custom_fltr(i(1), i(0), longs(&[0; 26])),
+ custom_fltr(i(1), i(0), wrong_type),
+ custom_fltr(i(1), i(0), longs(&[1000; 25])),
+ custom_fltr(i(0), i(0), longs(&SHARPEN)),
+ custom_fltr(i(10_000), i(0), longs(&SHARPEN)),
+ custom_fltr(i(1), i(-10_000), longs(&SHARPEN)),
+ custom_fltr(Value::Double(f64::NAN), i(0), longs(&SHARPEN)),
+ custom_fltr(i(1), unit(b"#Pxl", 1.0), longs(&SHARPEN)),
+ Descriptor::new("Cstm").with("Scl ", i(1)).with("Ofst", i(0)).with("Mtrx", i(5)),
+ Descriptor::new("Cstm").with("Scl ", i(1)).with("Mtrx", Value::List(longs(&SHARPEN))),
+ Descriptor::new("Cstm"),
+ ] {
+ let item = measured_named_item(b"Cstm", "Custom...", fltr);
+ let f = filter_from_item(&item);
+ assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}");
+ assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "kept byte for byte");
+ }
+ }
+
+ /// A `filterFX` item holding `fltr`, as Photoshop writes a filter with options.
+ fn pixelate_item(name: &str, fltr: Descriptor, filter_id: i32) -> Descriptor {
+ Descriptor::new("filterFX")
+ .with("Nm ", Value::Text(UnicodeString::new_nul(name)))
+ .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "Nrml"))))
+ .with("enab", Value::Boolean(true))
+ .with("hasoptions", Value::Boolean(true))
+ .with("FrgC", rgbc(0.0))
+ .with("BckC", rgbc(255.0))
+ .with("Fltr", Value::Descriptor(fltr))
+ .with("filterID", Value::Integer(filter_id))
+ }
+
+ #[test]
+ fn mezzotint_round_trips_every_type_and_reads_photoshops_shape() {
+ for (code, ty) in MEZZOTINT_TYPES {
+ let f = sf("filter.pixelate.mezzotint", json!({"type": ty}));
+ let d = item_for_filter(&f).unwrap();
+ assert_eq!(int(&d, "filterID"), Some(1_299_870_830));
+ let fltr = get_desc(&d, "Fltr").unwrap();
+ assert!(fltr.class_id.is("Mztn"));
+ assert_eq!(enum_of(fltr, "MztT"), Some(&code[..]));
+ assert!(matches!(fltr.get("MztT"), Some(Value::Enumerated { type_id, .. }) if type_id.is("MztT")));
+ assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f, "{ty}");
+ }
+ // Measured in Photoshop: `{'_class': 'Mztn', 'MztT': 'MztT.CrsD'}` and `LngS`, filterID 1299870830.
+ for (code, ty) in [("CrsD", "coarseDots"), ("LngS", "longStrokes")] {
+ let item = pixelate_item("Mezzotint...", Descriptor::new("Mztn").with("MztT", enumv("MztT", code)), 1_299_870_830);
+ let f = filter_from_item(&item);
+ assert_eq!((f.command.as_str(), &f.params), ("filter.pixelate.mezzotint", &json!({"type": ty})));
+ }
+ // No type or an unknown type is Fine Dots, like the engine; the seed
+ // (PhotoCraft only) is not saved.
+ for p in [json!({}), json!({"type": "sparkles"}), json!({"type": "fineDots", "seed": 77})] {
+ let d = item_for_filter(&sf("filter.pixelate.mezzotint", p)).unwrap();
+ let fltr = get_desc(&d, "Fltr").unwrap();
+ assert_eq!(enum_of(fltr, "MztT"), Some(&b"FnDt"[..]));
+ assert_eq!(fltr.items.len(), 1);
+ }
+ }
+
+ #[test]
+ fn color_halftone_round_trips_and_reads_photoshops_shape() {
+ for p in [
+ json!({"maxRadius": 8, "channel1": 108, "channel2": 162, "channel3": 90, "channel4": 45}),
+ json!({"maxRadius": 4, "channel1": -360, "channel2": 0, "channel3": 360, "channel4": -45}),
+ json!({"maxRadius": 127, "channel1": 1, "channel2": 2, "channel3": 3, "channel4": 4}),
+ ] {
+ let f = sf("filter.pixelate.colorHalftone", p);
+ let d = item_for_filter(&f).unwrap();
+ assert_eq!(int(&d, "filterID"), Some(1_131_180_616));
+ let fltr = get_desc(&d, "Fltr").unwrap();
+ assert!(fltr.class_id.is("ClrH"));
+ for k in ["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"] {
+ assert!(matches!(fltr.get(k), Some(Value::Integer(_))), "{k} is a long");
+ }
+ assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f);
+ }
+ // Measured in Photoshop: `{'_class': 'ClrH', 'Rds ': 6, 'Ang1': 10, 'Ang2': 20, 'Ang3': 30, 'Ang4': 40}`.
+ let measured = Descriptor::new("ClrH")
+ .with("Rds ", Value::Integer(6))
+ .with("Ang1", Value::Integer(10))
+ .with("Ang2", Value::Integer(20))
+ .with("Ang3", Value::Integer(30))
+ .with("Ang4", Value::Integer(40));
+ let item = pixelate_item("Color Halftone...", measured.clone(), 1_131_180_616);
+ let f = filter_from_item(&item);
+ assert_eq!(f.command, "filter.pixelate.colorHalftone");
+ assert_eq!(f.params, json!({"maxRadius": 6, "channel1": 10, "channel2": 20, "channel3": 30, "channel4": 40}));
+ assert_eq!(get_desc(&item_for_filter(&f).unwrap(), "Fltr"), Some(&measured));
+ // Defaults and hostile values write longs within the dialog's ranges.
+ let d = item_for_filter(&sf("filter.pixelate.colorHalftone", json!({"maxRadius": f64::NAN, "channel1": 1e12, "channel2": -1e12, "channel3": "x"})))
+ .unwrap();
+ let fltr = get_desc(&d, "Fltr").unwrap();
+ let got: Vec<_> = ["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"].iter().map(|k| int(fltr, k)).collect();
+ assert_eq!(got, [Some(8), Some(360), Some(-360), Some(90), Some(45)]);
+ }
+
+ #[test]
+ fn malformed_pixelate_filters_stay_verbatim() {
+ let mz = |v: Value| Descriptor::new("Mztn").with("MztT", v);
+ let ch = |rds: Value, ang1: Value| {
+ Descriptor::new("ClrH")
+ .with("Rds ", rds)
+ .with("Ang1", ang1)
+ .with("Ang2", Value::Integer(20))
+ .with("Ang3", Value::Integer(30))
+ .with("Ang4", Value::Integer(40))
+ };
+ let cases = [
+ pixelate_item("Mezzotint...", Descriptor::new("Mztn"), code(b"Mztn")),
+ pixelate_item("Mezzotint...", mz(enumv("MztT", "Sprk")), code(b"Mztn")),
+ pixelate_item("Mezzotint...", mz(Value::Integer(1)), code(b"Mztn")),
+ pixelate_item("Color Halftone...", Descriptor::new("ClrH"), code(b"ClrH")),
+ pixelate_item("Color Halftone...", ch(Value::Double(6.0), Value::Integer(10)), code(b"ClrH")),
+ pixelate_item("Color Halftone...", ch(unit(b"#Pxl", 6.0), Value::Integer(10)), code(b"ClrH")),
+ pixelate_item("Color Halftone...", ch(Value::Integer(3), Value::Integer(10)), code(b"ClrH")),
+ pixelate_item("Color Halftone...", ch(Value::Integer(128), Value::Integer(10)), code(b"ClrH")),
+ pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(361)), code(b"ClrH")),
+ pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(i32::MIN)), code(b"ClrH")),
+ pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Double(f64::NAN)), code(b"ClrH")),
+ ];
+ for item in cases {
+ let f = filter_from_item(&item);
+ assert_eq!(f.command, UNSUPPORTED_FILTER, "{:?}", get_desc(&item, "Fltr"));
+ // Written back with its own settings (blending is rewritten from the model).
+ let back = item_for_filter(&f).unwrap();
+ // Compared as bytes: a NaN setting is not equal to itself.
+ let fltr = |d: &Descriptor| get_desc(d, "Fltr").map(Descriptor::to_bytes);
+ assert_eq!((fltr(&back), int(&back, "filterID")), (fltr(&item), int(&item, "filterID")));
+ }
+ // Without a `Fltr` the filter has no settings to read: kept verbatim too.
+ let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"ClrH")));
+ assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER);
+ }
+
+ /// Distort smart filters from a Photoshop file open as their PhotoCraft filters, and the ones
+ /// PhotoCraft writes carry the same settings, keys and order as Photoshop's.
+ #[test]
+ fn photoshop_distort_filters_read_and_write_like_photoshop() {
+ for (command, params, hex) in PHOTOSHOP_FLTR {
+ let ps = Descriptor::from_bytes(&from_hex(hex).unwrap()).unwrap();
- let f = filter_from_item(&photoshop_item(ps.clone()));
++ let f = filter_from_item(&photoshop_fltr_item(ps.clone()));
+ let want: J = serde_json::from_str(params).unwrap();
+ assert_eq!((f.command.as_str(), &f.params), (command, &want), "{command}");
+ let ours = match item_for_filter(&f).unwrap().get("Fltr") {
+ Some(Value::Descriptor(d)) => d.clone(),
+ other => panic!("{command}: no Fltr ({other:?})"),
+ };
+ assert_eq!((&ours.class_id, &ours.items), (&ps.class_id, &ps.items), "{command}: same keys, values and order");
+ }
+ // A scaled wave can't be modelled, so it stays Photoshop's, unchanged.
+ let wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap();
- let item = photoshop_item(wave);
++ let item = photoshop_fltr_item(wave);
+ let f = filter_from_item(&item);
+ assert_eq!(f.command, UNSUPPORTED_FILTER);
+ assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr"));
+ // Unscaled, but with 332 generators (the renderer draws 64 at most), it stays Photoshop's too.
+ let mut unscaled = match item.get("Fltr") {
+ Some(Value::Descriptor(d)) => d.clone(),
+ other => panic!("wave: no Fltr ({other:?})"),
+ };
+ set(&mut unscaled, "SclV", Value::Integer(100));
- let item = photoshop_item(unscaled);
++ let item = photoshop_fltr_item(unscaled);
+ let f = filter_from_item(&item);
+ assert_eq!(f.command, UNSUPPORTED_FILTER);
+ assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr"));
+ }
+
+ /// An unscaled Wave opens as PhotoCraft's Wave (Triangle, the other settings as stored) up to
+ /// the generators the renderer models; one more and it stays Photoshop's, unchanged.
+ #[test]
+ fn wave_maps_up_to_the_generators_the_renderer_models() {
+ let max = i32::try_from(photocraft_algo::MAX_WAVE_GENERATORS).unwrap();
+ assert_eq!(max, 64);
+ let mut wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap();
+ set(&mut wave, "SclV", Value::Integer(100));
+ for (generators, mapped) in [(1, true), (max, true), (max + 1, false), (999, false), (0, false), (-1, false)] {
+ set(&mut wave, "NmbG", Value::Integer(generators));
- let item = photoshop_item(wave.clone());
++ let item = photoshop_fltr_item(wave.clone());
+ let f = filter_from_item(&item);
+ if mapped {
+ assert_eq!(
+ (f.command.as_str(), &f.params),
+ (
+ "filter.distort.wave",
+ &json!({"type": "triangle", "generators": generators, "wavelengthMin": 213, "wavelengthMax": 214, "amplitudeMin": 240,
+ "amplitudeMax": 241, "undefinedAreas": "wrap", "seed": 1270346})
+ ),
+ "{generators} generators"
+ );
+ match item_for_filter(&f).unwrap().get("Fltr") {
+ Some(Value::Descriptor(ours)) => assert_eq!((&ours.class_id, &ours.items), (&wave.class_id, &wave.items), "{generators} generators"),
+ other => panic!("wave: no Fltr ({other:?})"),
+ }
+ } else {
+ assert_eq!(f.command, UNSUPPORTED_FILTER, "{generators} generators");
+ assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr"), "{generators} generators");
+ }
+ }
+ }
+
+ /// PhotoCraft draws at most `MAX_WAVE_GENERATORS` generators, so a Wave edited past that exports
+ /// the 64 it rendered, and a count below 1 exports 1, instead of Photoshop drawing more.
+ #[test]
+ fn wave_export_writes_only_the_generators_the_renderer_draws() {
+ let max = i32::try_from(photocraft_algo::MAX_WAVE_GENERATORS).unwrap();
+ for (stored, written) in [(100, max), (999, max), (max + 1, max), (max, max), (5, 5), (1, 1), (0, 1), (-3, 1)] {
+ let wave = sf(
+ "filter.distort.wave",
+ json!({"type": "sine", "generators": stored, "wavelengthMin": 20, "wavelengthMax": 90, "amplitudeMin": 4, "amplitudeMax": 30}),
+ );
+ let fltr = match item_for_filter(&wave).unwrap().get("Fltr") {
+ Some(Value::Descriptor(d)) => d.clone(),
+ other => panic!("wave: no Fltr ({other:?})"),
+ };
+ assert_eq!(int(&fltr, "NmbG"), Some(written), "{stored} generators");
+ }
+ }
+
+ /// `RndS` is the seed the renderer draws with, also for a legacy signed or fractional seed
+ /// (stored as is by `layer.smartFilter.setParams`), not 0.
+ #[test]
+ fn wave_export_writes_the_seed_the_renderer_draws() {
+ for (stored, written) in [
+ (json!(77), 77),
+ (json!(4_000_000_000u32), -294_967_296),
+ (json!(-1), -1),
+ (json!(7.4), 7),
+ (json!(-2.6), -3),
+ (json!(1e12), i32::MAX),
+ (json!("x"), 0),
+ ] {
+ let wave = sf("filter.distort.wave", json!({"generators": 3, "seed": stored}));
+ let fltr = match item_for_filter(&wave).unwrap().get("Fltr") {
+ Some(Value::Descriptor(d)) => d.clone(),
+ other => panic!("wave: no Fltr ({other:?})"),
+ };
+ assert_eq!(int(&fltr, "RndS"), Some(written), "seed {stored}");
+ // And it reads back as that bit pattern.
- assert_eq!(known_params("Wave", Some(&fltr)).unwrap().1["seed"], json!(written as u32), "seed {stored}");
++ assert_eq!(known_params("Wave", Some(&fltr), &Descriptor::new("filterFX")).unwrap().1["seed"], json!(written as u32), "seed {stored}");
+ }
+ }
+
+ /// Invert on a smart object: Photoshop stores no `Fltr`, `hasoptions` false and its filter id.
+ #[test]
+ fn invert_smart_filter_reads_and_writes_like_photoshop() {
+ let item = Descriptor::new("filterFX")
+ .with("Nm ", Value::Text(UnicodeString::new_nul("Invert")))
+ .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal"))))
+ .with("enab", Value::Boolean(true))
+ .with("hasoptions", Value::Boolean(false))
+ .with("FrgC", rgbc(255.0))
+ .with("BckC", rgbc(0.0))
+ .with("filterID", Value::Integer(code(b"Invr")));
+ let f = filter_from_item(&item);
+ assert_eq!((f.command.as_str(), &f.params), ("image.adjustments.invert", &json!({})));
+ let back = item_for_filter(&f).unwrap();
+ assert_eq!(back.get("Fltr"), None);
+ assert_eq!(back.get("hasoptions"), Some(&Value::Boolean(false)));
+ assert_eq!(back.get("filterID"), Some(&Value::Integer(code(b"Invr"))));
+ assert_eq!(back.get("Nm "), Some(&Value::Text(UnicodeString::new_nul("Invert"))));
+ }
+
+ /// A filter PhotoCraft doesn't model, or a known one with settings it doesn't, is kept verbatim; only its visibility and blend change.
#[test]
fn unknown_filters_keep_their_descriptor() {
let item = Descriptor::new("filterFX")
- .with("Nm ", Value::Text(UnicodeString::new_nul("Twirl...")))
- .with("Nm ", Value::Text(UnicodeString::new_nul("Crystallize...")))
++ .with("Nm ", Value::Text(UnicodeString::new_nul("Shear...")))
.with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal"))))
.with("enab", Value::Boolean(true))
- .with("Fltr", Value::Descriptor(Descriptor::new("Twrl").with("Angl", Value::Integer(50))))
- .with("filterID", Value::Integer(code(b"Twrl")));
- .with("Fltr", Value::Descriptor(Descriptor::new("Crst").with("ClSz", Value::Integer(10))))
- .with("filterID", Value::Integer(code(b"Crst")));
++ .with("Fltr", Value::Descriptor(Descriptor::new("Shr ").with("UndA", enumv("UndA", "WrpA"))))
++ .with("filterID", Value::Integer(code(b"Shr ")));
let f = filter_from_item(&item);
assert_eq!(f.command, UNSUPPORTED_FILTER);
- assert_eq!(f.params["name"], "Twirl...");
- assert_eq!(f.params["name"], "Crystallize...");
++ assert_eq!(f.params["name"], "Shear...");
assert_eq!(item_for_filter(&f).unwrap(), item);
// Hidden and re-blended: only those keys change.
let mut g = f.clone();
diff --cc docs/file-format-parity.md
index d5d2e545e,420ea68bb..c05bba49e
--- a/docs/file-format-parity.md
+++ b/docs/file-format-parity.md
@@@ -1,6 -1,6 +1,6 @@@
# File-format parity
- > **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-15 · **Change:** minor (DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 41 filters (27 more: Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026
-> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-15 · **Change:** minor (DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); earlier: PSD smart filters: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave and ZigZag, and Invert, read and written like Photoshop; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026
++> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-15 · **Change:** minor (DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 49 filters (35 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026
Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity and
tests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write
@@@ -21,8 -21,8 +21,8 @@@ XL are missing (gap G10). Remaining: 30
| Format | Photoshop | PhotoCraft read | PhotoCraft write | Fidelity and tests |
|---|---|---|---|---|
- | PSD | R/W | yes | yes | 1/8/16/32-bit; Bitmap, Gray, Indexed, RGB, CMYK, Multichannel, Lab, Duotone; layers, groups, masks, vector masks, adjustment and fill layers, effects, text, shapes, smart objects (SoLd/lnk2 with their warp: the bend presets, a custom mesh and, since #4112, Cylinder; CS2 PlLd/lnkD read with their warp, kept as is or re-saved as SoLd once edited), smart filters (41 mapped plus Hue/Saturation, Perspective Warp, Filter Gallery with Chrome and a Camera Raw subset, rest verbatim), slices, comps, Advanced Blending. Oracle floors: Photoshop-authored 188/258, io 148/170, psd-tools 249/309; round trip ≥ 169/170, 308/309, 258/256. Known failures: #1281, #2469 (#2374, text layers, closed 2026-10-10; #2465, CS2 `PlLd`-only smart objects, fixed 2026-10-12) |
-| PSD | R/W | yes | yes | 1/8/16/32-bit; Bitmap, Gray, Indexed, RGB, CMYK, Multichannel, Lab, Duotone; layers, groups, masks, vector masks, adjustment and fill layers, effects, text, shapes, smart objects (SoLd/lnk2; CS2 PlLd/lnkD read with their warp, kept as is or re-saved as SoLd once edited), smart filters (22 mapped: blurs, Unsharp Mask, noise, Other, Mosaic, Emboss, Levels, Curves, Shadows/Highlights, Invert and the Distort filters but Shear; plus Filter Gallery with Chrome; rest verbatim), slices, comps, Advanced Blending. Oracle floors: Photoshop-authored 188/258, io 148/170, psd-tools 249/309; round trip ≥ 169/170, 308/309, 258/256. Known failures: #1281, #2469 (#2374, text layers, closed 2026-10-10; #2465, CS2 `PlLd`-only smart objects, fixed 2026-10-12) |
-| PSB | R/W | yes | yes | Auto-switches above 2 GB (REL-212-2); 4–5 GB fixtures generated (FILE-216-2); > 4 GB fails on Windows (#375) |
++| PSD | R/W | yes | yes | 1/8/16/32-bit; Bitmap, Gray, Indexed, RGB, CMYK, Multichannel, Lab, Duotone; layers, groups, masks, vector masks, adjustment and fill layers, effects, text, shapes, smart objects (SoLd/lnk2 with their warp: the bend presets, a custom mesh and, since #4112, Cylinder; CS2 PlLd/lnkD read with their warp, kept as is or re-saved as SoLd once edited), smart filters (49 mapped, among them Invert and the Distort filters but Shear, plus Hue/Saturation, Perspective Warp, Filter Gallery with Chrome and a Camera Raw subset, rest verbatim), slices, comps, Advanced Blending. Oracle floors: Photoshop-authored 188/258, io 148/170, psd-tools 249/309; round trip ≥ 169/170, 308/309, 258/256. Known failures: #1281, #2469 (#2374, text layers, closed 2026-10-10; #2465, CS2 `PlLd`-only smart objects, fixed 2026-10-12) |
+| PSB | R/W | yes | yes | Auto-switches above 2 GB (REL-212-2); generated 20 MP, 150-layer, 2 GB PSD and 4.4 GB PSB fixtures opened, saved and re-opened by io tests/large_files.rs (FILE-216-2, 2026-10-13; the 4.4 GB PSB opens on Windows); > 4 GB from the app's File › Open on Windows: #375 |
| Cloud PSD (.psdc) | R/W | no | no | Out of scope (Adobe cloud) |
| TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, BigTIFF, every IFD, banded parallel decode; layered TIFF both byte orders (FILE-215-7: extra alpha channels not written) |
| JPEG | R/W | yes | yes | 8-bit Gray/RGB/CMYK, ICC/EXIF/XMP; Save keeps the opened file's quality (estimated from its quantisation tables, #2399); no JPEG Options dialog (quality 0–12, baseline/progressive) (FILE-215-19) |
@@@ -158,7 -148,7 +158,8 @@@ remaining gaps in #1606 stay tracked wi
| 2026-10-14 | minor | PSD smart filter masks: Photoshop stores a smart object's filtered pixels without its filter mask and mixes the unfiltered ones (`FEid`) back in; import now mixes them and export writes them that way, so sf-filter-mask-hard, -gradient and sf-stack-blend-and-mask pass; Photoshop-oracle floor 185 → 188 of 258 |
| 2026-10-13 | minor | Lossy DNG (compression 34892) decodes: 8-bit baseline JPEG tiles and strips, CFA and LinearRaw, partial edge tiles; the stored values take the normal levels and LinearizationTable (FILE-215-11, lossy DNG part) |
| 2026-10-14 | minor | Corpus floors raised to the measured results of the CMYK, Lab, 32-bit, Levels, Threshold, Posterize, feather and pass-through fixes landed together: Photoshop-authored 165 → 185 of 258, io 146 → 148 of 170, psd-tools 242 → 249 of 309 |
+| 2026-10-13 | minor | Large-file fixtures generated at test time (20 MP layered, 150-layer layout, 2.02 GB PSD, 4.38 GB PSB), opened, saved and re-opened by io tests/large_files.rs; FILE-216-2 done; P20/P63 open times measurable (#5107) |
+ | 2026-10-13 | minor | PSD smart filters: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag and Invert open as editable filters and are saved instead of dropped (checked against a Photoshop 27 file); a scaled Wave, a Wave with more than 64 generators and Shear stay verbatim |
| 2026-10-13 | minor | CMYK Hue/Saturation (not Colorize) and Color Balance work on C, M and Y as inverted RGB with black kept, on the inks for display, export and destructive edits; cmyk8/16 hue-saturation 100% → 0.4–0.7% bad pixels, color-balance 74% → 25% |
| 2026-10-13 | minor | CMYK Posterize works on the stored values (1 − ink), as Photoshop does: psd-tools posterize_cmyk passes (13.8 % → 0 of pixels off on the ink path); psd-tools floor → 242 of 309 |
| 2026-10-13 | minor | CMYK documents whose layers are plain raster layers plus Invert, Posterize, Threshold, Brightness/Contrast, Levels or Curves layers composite on their own inks for display, export and flattening: the cmyk8/16 oracles for those seven adjustments pass; Photoshop-oracle floor 151 → 165 of 258 |