PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Merge PR #6305: PSD: Offset and Custom smart filters open and save like Photoshop (#6304)
aiongg2c87bd630b49
diff --cc crates/io/src/smart_map.rsindex 6a6a74c11,6040d3d0b..ba3eb3525--- a/crates/io/src/smart_map.rs+++ b/crates/io/src/smart_map.rs@@@ -165,15 -154,10 +165,17 @@@ const KNOWN: [Known; 37] =Known { class: "HghP", filter_id: code(b"HghP"), name: "High Pass...", command: "filter.other.highPass" },Known { class: "Mxm ", filter_id: code(b"Mxm "), name: "Maximum...", command: "filter.other.maximum" },Known { class: "Mnm ", filter_id: code(b"Mnm "), name: "Minimum...", command: "filter.other.minimum" },+ Known { class: "Ofst", filter_id: code(b"Ofst"), name: "Offset...", command: "filter.other.offset" },+ Known { class: "Cstm", filter_id: code(b"Cstm"), name: "Custom...", command: "filter.other.custom" },Known { class: "Msc ", filter_id: code(b"Msc "), name: "Mosaic...", command: "filter.pixelate.mosaic" },Known { class: "Embs", filter_id: code(b"Embs"), name: "Emboss...", command: "filter.stylize.emboss" },+ Known { class: "Dfs ", filter_id: code(b"Dfs "), name: "Diffuse...", command: "filter.stylize.diffuse" },+ Known { class: "TrcC", filter_id: code(b"TrcC"), name: "Trace Contour...", command: "filter.stylize.traceContour" },+ Known { class: "Crst", filter_id: code(b"Crst"), name: "Crystallize...", command: "filter.pixelate.crystallize" },+ Known { class: "Pntl", filter_id: code(b"Pntl"), name: "Pointillize...", command: "filter.pixelate.pointillize" },+ Known { class: "Wnd ", filter_id: code(b"Wnd "), name: "Wind...", command: "filter.stylize.wind" },+ Known { class: "Extr", filter_id: code(b"Extr"), name: "Extrude...", command: "filter.stylize.extrude" },+ Known { class: "Tls ", filter_id: code(b"Tls "), name: "Tiles...", command: "filter.stylize.tiles" },Known { class: "Lvls", filter_id: code(b"Lvls"), name: "Levels...", command: "image.adjustments.levels" },Known { class: "Crvs", filter_id: code(b"Crvs"), name: "Curves...", command: "image.adjustments.curves" },// Shadows/Highlights at its defaults stores no `Fltr` (`hasoptions` false).@@@ -384,68 -260,35 +386,94 @@@ fn curves_params(f: &Descriptor) -> OptSome(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);++ fn int_in(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| int_in(int_value(v), CUSTOM_CELL).map(|v| json!(v))).collect();+ let scale = int_in(int(f, "Scl "), CUSTOM_SCALE)?;+ let offset = int_in(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!({}),@@@ -466,54 -308,13 +494,59 @@@};json!({"amount": px(f, "Nose")?, "distribution": dist, "monochromatic": mono, "seed": int(f, "FlRs").unwrap_or(0)})}+ ("surfaceBlur", Some(f)) if only_keys(f, &["Rds ", "Thsh"]) => json!({+ "radius": in_range(px(f, "Rds ")?, 1.0, 100.0)?,+ "threshold": int_in(f, "Thsh", 2, 255)?,+ }),+ ("SmrB", Some(f)) if only_keys(f, &["Rds ", "Thsh", "SmBQ", "SmBM"]) => json!({+ "radius": in_range(px(f, "Rds ")?, 0.1, 100.0)?,+ "threshold": in_range(px(f, "Thsh")?, 0.1, 100.0)?,+ "quality": enum_name(f, "SmBQ", &SMART_BLUR_QUALITY)?,+ "mode": enum_name(f, "SmBM", &SMART_BLUR_MODE)?,+ }),+ ("RdlB", Some(f)) if only_keys(f, &["Amnt", "BlrM", "BlrQ"]) => json!({+ "amount": int_in(f, "Amnt", 1, 100)?,+ "method": enum_name(f, "BlrM", &RADIAL_METHOD)?,+ "quality": enum_name(f, "BlrQ", &RADIAL_QUALITY)?,+ }),("Msc ", Some(f)) => json!({"cellSize": px(f, "ClSz")?}),("Embs", Some(f)) => json!({"angle": int(f, "Angl")?, "height": int(f, "Hght")?, "amount": int(f, "Amnt")?}),+ (SMART_SHARPEN, Some(f)) => smart_sharpen_params(f)?,+ ("DstS", Some(f)) => {+ if f.items.iter().any(|(k, _)| !k.is("Rds ") && !k.is("Thsh")) {+ return None;+ }+ json!({"radius": int_in(f, "Rds ", 1, 500)?, "threshold": int_in(f, "Thsh", 0, 255)?})+ }+ ("Dfs ", Some(f)) => json!({"mode": enum_from(f, "Md ", "DfsM", &DIFFUSE_MODES)?}),+ ("TrcC", Some(f)) => json!({"level": int_in(f, "Lvl ", 0, 255)?, "edge": enum_from(f, "Edg ", "CntE", &TRACE_EDGES)?}),+ ("Crst", Some(f)) => json!({"cellSize": int_in(f, "ClSz", CELL_SIZE.0, CELL_SIZE.1)?}),+ ("Pntl", Some(f)) => {+ let mut p = json!({"cellSize": int_in(f, "ClSz", CELL_SIZE.0, CELL_SIZE.1)?});+ // Pointillize paints the gaps in the background colour the entry carries.+ if item.get("BckC").is_some() {+ p["background"] = get_desc(item, "BckC").and_then(rgbc_colour)?;+ }+ p+ }+ ("Wnd ", Some(f)) => json!({+ "method": enum_from(f, "WndM", "WndM", &WIND_METHODS)?,+ "direction": enum_from(f, "Drct", "Drct", &WIND_DIRECTIONS)?,+ }),+ ("Extr", Some(f)) => json!({+ "type": enum_from(f, "ExtT", "ExtT", &EXTRUDE_TYPES)?,+ "size": int_in(f, "ExtS", EXTRUDE_SIZE.0, EXTRUDE_SIZE.1)?,+ "depth": int_in(f, "ExtD", EXTRUDE_DEPTH.0, EXTRUDE_DEPTH.1)?,+ "depthMode": enum_from(f, "ExtR", "ExtR", &EXTRUDE_DEPTHS)?,+ "solidFrontFaces": bool_at(f, "ExtF")?,+ "maskIncompleteBlocks": bool_at(f, "ExtM")?,+ }),+ ("Tls ", Some(f)) => tiles_params(f, item)?,+ ("Ofst", Some(f)) => {+ let fill = OFFSET_FILL.iter().find(|(psd, _)| enum_of(f, "Fl ") == Some(psd.as_bytes()))?.1;+ json!({"horizontal": int(f, "Hrzn")?, "vertical": int(f, "Vrtc")?, "undefinedAreas": fill})+ }+ ("Cstm", Some(f)) => custom_params(f)?,("Lvls", Some(f)) => levels_params(f)?,("Crvs", Some(f)) => curves_params(f)?,_ => return None,@@@ -850,56 -635,26 +892,74 @@@ fn fltr_for(k: &Known, p: &J) -> Result.with("Mnch", Value::Boolean(p.get("monochromatic").and_then(J::as_bool).unwrap_or(false))).with("FlRs", pi(p, "seed", 0.0))}+ "surfaceBlur" => d.with("Rds ", unit(b"#Pxl", pf(p, "radius", 5.0))).with("Thsh", pi(p, "threshold", 15.0)),+ "SmrB" => d+ .with("Rds ", Value::Double(pf(p, "radius", 3.0)))+ .with("Thsh", Value::Double(pf(p, "threshold", 25.0)))+ .with("SmBQ", enum_param(p, "quality", "high", "SmBQ", &SMART_BLUR_QUALITY)?)+ .with("SmBM", enum_param(p, "mode", "normal", "SmBM", &SMART_BLUR_MODE)?),+ "RdlB" => {+ // Photoshop wrote no centre key for a centred blur; an off-centre one is unmeasured.+ if ["centerX", "centerY"].iter().any(|k| (pf(p, k, 0.5) - 0.5).abs() > 1e-9) {+ return Err("an off-centre Radial Blur centre is not written to PSD".into());+ }+ d.with("Amnt", pi(p, "amount", 10.0))+ .with("BlrM", enum_param(p, "method", "spin", "BlrM", &RADIAL_METHOD)?)+ .with("BlrQ", enum_param(p, "quality", "good", "BlrQ", &RADIAL_QUALITY)?)+ }"Msc " => d.with("ClSz", unit(b"#Pxl", pf(p, "cellSize", 10.0))),"Embs" => d.with("Angl", pi(p, "angle", 135.0)).with("Hght", pi(p, "height", 3.0)).with("Amnt", pi(p, "amount", 100.0)),+ SMART_SHARPEN => {+ // The engine's defaults and ranges (it clamps the same way when rendering).+ d.with("useLegacy", Value::Boolean(false))+ .with("Amnt", unit(b"#Prc", pf(p, "amount", 100.0).clamp(1.0, 500.0)))+ .with("Rds ", unit(b"#Pxl", pf(p, "radius", 1.0).clamp(0.1, 64.0)))+ .with("noiseReduction", unit(b"#Prc", pf(p, "reduceNoise", 10.0).clamp(0.0, 100.0)))+ .with("blur", enumv("blurType", "GsnB"))+ }+ // Photoshop stores whole pixels and levels.+ "DstS" => {+ let whole = |key: &str, default: f64, lo: f64, hi: f64| Value::Integer(pf(p, key, default).round().clamp(lo, hi) as i32);+ d.with("Rds ", whole("radius", 1.0, 1.0, 500.0)).with("Thsh", whole("threshold", 0.0, 0.0, 255.0))+ }+ // Photoshop stores no random seed for these: `seed` is ours only and is not written.+ "Dfs " => d.with("Md ", enum_out(p, "mode", "normal", "DfsM", &DIFFUSE_MODES)?),+ "TrcC" => d.with("Lvl ", pi_in(p, "level", 128.0, 0, 255)).with("Edg ", enum_out(p, "edge", "lower", "CntE", &TRACE_EDGES)?),+ "Crst" => d.with("ClSz", pi_in(p, "cellSize", 10.0, CELL_SIZE.0, CELL_SIZE.1)),+ "Pntl" => d.with("ClSz", pi_in(p, "cellSize", 5.0, CELL_SIZE.0, CELL_SIZE.1)),+ // Photoshop stores no random seed for these: our `seed` is not written.+ "Wnd " => {+ d.with("WndM", enum_out(p, "method", "wind", "WndM", &WIND_METHODS)?).with("Drct", enum_out(p, "direction", "fromRight", "Drct", &WIND_DIRECTIONS)?)+ }+ "Extr" => d+ .with("ExtT", enum_out(p, "type", "blocks", "ExtT", &EXTRUDE_TYPES)?)+ .with("ExtS", pi_in(p, "size", 30.0, EXTRUDE_SIZE.0, EXTRUDE_SIZE.1))+ .with("ExtD", pi_in(p, "depth", 30.0, EXTRUDE_DEPTH.0, EXTRUDE_DEPTH.1))+ .with("ExtR", enum_out(p, "depthMode", "random", "ExtR", &EXTRUDE_DEPTHS)?)+ .with("ExtF", bool_param(p, "solidFrontFaces"))+ .with("ExtM", bool_param(p, "maskIncompleteBlocks")),+ "Tls " => d+ .with("TlNm", pi_in(p, "count", 10.0, TILE_COUNT.0, TILE_COUNT.1))+ .with("TlOf", pi_in(p, "maxOffset", 10.0, TILE_OFFSET.0, TILE_OFFSET.1))+ .with("FlCl", enum_out(p, "fill", "background", "FlCl", &TILE_FILLS)?),+ "Ofst" => {+ // As the engine reads it: anything but repeat / transparent wraps.+ let ours = p.get("undefinedAreas").and_then(J::as_str).unwrap_or("wrap");+ let fill = OFFSET_FILL.iter().find(|(_, o)| *o == ours).map_or("Wrp ", |(psd, _)| *psd);+ d.with("Hrzn", pi(p, "horizontal", 0.0)).with("Vrtc", pi(p, "vertical", 0.0)).with("Fl ", enumv("FlMd", fill))+ }+ "Cstm" => {+ // The engine's identity kernel when none is given; missing cells are 0.+ let kernel = p.get("kernel").and_then(J::as_array);+ let cell = |i: usize| match kernel {+ Some(a) => a.get(i).and_then(J::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0),+ None => f64::from(u8::from(i == 12)),+ };+ let m = (0..25).map(|i| whole(cell(i), CUSTOM_CELL, "a kernel value")).collect::<Result<Vec<_>, _>>()?;+ d.with("Scl ", whole(pf(p, "scale", 1.0), CUSTOM_SCALE, "Scale")?)+ .with("Ofst", whole(pf(p, "offset", 0.0), CUSTOM_OFFSET, "Offset")?)+ .with("Mtrx", Value::List(m))+ }"Lvls" => d.with("Adjs", adjustments(p, false)?),"Crvs" => d.with("Adjs", adjustments(p, true)?),"adaptCorrect" => {@@@ -1483,21 -1123,8 +1543,23 @@@ mod testssf("filter.other.minimum", json!({"radius": 2.0})),sf("filter.pixelate.mosaic", json!({"cellSize": 8.0})),sf("filter.stylize.emboss", json!({"angle": 135, "height": 3, "amount": 100})),+ sf("filter.sharpen.smartSharpen", json!({"amount": 120.0, "radius": 2.5, "reduceNoise": 5.0})),+ sf("filter.noise.dustAndScratches", json!({"radius": 4, "threshold": 20})),+ sf("filter.stylize.diffuse", json!({"mode": "normal"})),+ sf("filter.stylize.diffuse", json!({"mode": "darkenOnly"})),+ sf("filter.stylize.diffuse", json!({"mode": "lightenOnly"})),+ sf("filter.stylize.diffuse", json!({"mode": "anisotropic"})),+ sf("filter.stylize.traceContour", json!({"level": 60, "edge": "lower"})),+ sf("filter.stylize.traceContour", json!({"level": 128, "edge": "upper"})),+ sf("filter.stylize.traceContour", json!({"level": 0, "edge": "upper"})),+ sf("filter.stylize.traceContour", json!({"level": 255, "edge": "lower"})),+ sf("filter.pixelate.crystallize", json!({"cellSize": 10})),+ sf("filter.pixelate.crystallize", json!({"cellSize": 3})),+ sf("filter.pixelate.crystallize", json!({"cellSize": 300})),+ sf("filter.pixelate.pointillize", json!({"cellSize": 7, "background": [1.0, 1.0, 1.0, 1.0]})),+ sf("filter.pixelate.pointillize", json!({"cellSize": 300, "background": [0.0, 0.5, 1.0, 1.0]})),+ sf("filter.other.offset", json!({"horizontal": 12, "vertical": -7, "undefinedAreas": "transparent"})),+ sf("filter.other.custom", json!({"kernel": SHARPEN, "scale": 1, "offset": 0})),sf("image.adjustments.levels", json!({"inBlack": 20, "inWhite": 220, "gamma": 1.4, "red": {"inBlack": 0, "inWhite": 255, "gamma": 0.8}})),sf("image.adjustments.curves", json!({"points": [[0.0, 0.0], [64.0, 40.0], [255.0, 255.0]], "blue": [[0.0, 20.0], [255.0, 235.0]]})),sf("image.adjustments.shadowsHighlights", json!({})),@@@ -1515,544 -1142,170 +1577,708 @@@}}+ /// 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))+ }++ 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, ¶ms));+ // 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_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_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_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_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_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");+ }+ }+#[test]fn unknown_filters_keep_their_descriptor() {let item = Descriptor::new("filterFX")diff --cc docs/file-format-parity.mdindex 287626747,b662b3ecb..5998c1f4b--- a/docs/file-format-parity.md+++ b/docs/file-format-parity.md@@@ -143,13 -143,7 +143,14 @@@ remaining gaps in #1606 stay tracked wi| Date | Change | Summary ||---|---|---|| 2026-10-15 | minor | DDS textures save (#1327): uncompressed or BC1/BC2/BC3 (DXT1/3/5) from a clean-room block encoder, optional box-filtered mip chain, legacy header; DDS Options in Save As and Save a Copy, `ddsCompression`/`ddsMipmaps` for scripts, the CLI and MCP |+| 2026-10-16 | minor | PSD smart filters: Perspective Warp (`perspectiveWarpTransform`: `vertices`, `warpedVertices`, `quads` of vertex indices, document pixels) opens as `layer.smartObjects.perspectiveWarp`, one plane per quad, and re-renders warped; save writes the original item with only the geometry rewritten, or a new one in Photoshop's layout; inconsistent descriptors stay verbatim (FILE-215-2, #6268) |+| 2026-10-16 | minor | PSD smart filters: Hue/Saturation (`HStr`: `Clrz`, `Adjs` = master `Hst2` plus one per edited range with `LclR` and its four range sliders, all longs, measured on a Photoshop-saved file) opens as `image.adjustments.hueSaturation`, re-renders with the smart object and saves in Photoshop's layout; layouts outside it stay verbatim (FILE-215-2, #6267) |+| 2026-10-15 | minor | PSD smart filters without options (Blur, Blur More, Average, Despeckle, Find Edges, Facet, Fragment, Sharpen, Sharpen More, Sharpen Edges, Solarize) map both ways as Photoshop stores them: `hasoptions` false, no `Fltr`, the four-char `filterID` (FILE-215-2) |+| 2026-10-15 | minor | PSD smart filters: Surface Blur (filterID 1135, `surfaceBlur`), Smart Blur (`SmrB`) and Radial Blur (`RdlB`) open as editable filters and save with the keys, types and enums measured in Photoshop; out-of-range, unknown-enum or extra-key entries (an off-centre Radial Blur) stay verbatim (#6298, FILE-215-2) |+| 2026-10-15 | minor | PSD smart filters: Smart Sharpen (filterID 1131, Gaussian removal; Lens/Motion Blur and legacy entries stay verbatim) and Dust & Scratches (`DstS`) open as editable filters and save in Photoshop's measured shape (#6300) |+| 2026-10-15 | minor | PSD smart filters: Diffuse (`Dfs `, `DfsM` mode), Trace Contour (`TrcC`, level and `CntE` edge), Crystallize (`Crst`) and Pointillize (`Pntl`, background from `BckC`) open as editable smart filters and save in the shape measured in Photoshop (#6302, FILE-215-2) |+| 2026-10-15 | minor | PSD smart filters: Wind (`Wnd `, `WndM` method, `Drct` direction), Extrude (`Extr`, `ExtT` type, size, depth, `ExtR` depth mode, solid front faces, mask incomplete blocks) and Tiles (`Tls `, count, offset, `FlCl` fill with the entry's `FrgC`/`BckC`) open as editable smart filters and save in the shape measured in Photoshop (#6314, FILE-215-2) |+ | 2026-10-15 | minor | PSD smart filters: Offset (`Ofst`: `Hrzn`/`Vrtc` long, `Fl ` `FlMd` Wrap/Background/Repeat) and Custom (`Cstm`: `Scl `, `Ofst` long, 25-long `Mtrx`) map both ways in `filterFX`, matching descriptors measured in Photoshop (FILE-215-2, #6304) || 2026-10-15 | minor | PNG: a stereo PNG's `sTER` pairing (PNG Extensions 1.4.0 §3.6) is read on open and written back on save, so the file still says it is a stereo pair (#6063) || 2026-10-15 | minor | PSD guides: image resource 1092 (guides v2) gives guides their own colours on import; 1092 and 1097 (guide GUIDs) are written back only while they still describe the document's guides, so an edit no longer leaves Photoshop a stale second guide list (#5966) || 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 |