Skip to content

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

Merge PR #6301: PSD: Smart Sharpen and Dust & Scratches smart filters open and save like Photoshop (#6300)

aiongg9fbb648f8aae
diff --cc crates/io/src/smart_map.rs
index b1a4d98fc,30ea2b7a8..b1fc94486
--- a/crates/io/src/smart_map.rs
+++ b/crates/io/src/smart_map.rs
@@@ -171,24 -160,66 +171,82 @@@ const KNOWN: [Known; 28] =
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" },
];
+/// 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,
+ }
+ }
+
+ /// A `long` value within `lo..=hi`.
+ fn int_in(d: &Descriptor, key: &str, lo: i32, hi: i32) -> Option<i32> {
+ int(d, key).filter(|v| (lo..=hi).contains(v))
+ }
+
+ /// `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))
+ }
+
fn known_by_command(command: &str) -> Option<&'static Known> {
KNOWN.iter().find(|k| k.command == command)
}
@@@ -347,23 -338,15 +405,30 @@@ fn known_params(class: &str, f: Option<
};
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)?})
+ }
("Lvls", Some(f)) => levels_params(f)?,
("Crvs", Some(f)) => curves_params(f)?,
_ => return None,
@@@ -677,23 -658,21 +742,36 @@@ 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))
+ }
"Lvls" => d.with("Adjs", adjustments(p, false)?),
"Crvs" => d.with("Adjs", adjustments(p, true)?),
"adaptCorrect" => {
@@@ -1288,96 -1160,222 +1368,312 @@@ mod tests
}
}
+ /// 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"]));
+ }
+ }
+
+ /// A `filterFXList` item as Photoshop writes it, around filter `fltr`.
+ fn ps_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", "normal"))))
+ .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))
+ }
+
+ /// 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}");
+ }
+ }
+
#[test]
fn unknown_filters_keep_their_descriptor() {
let item = Descriptor::new("filterFX")
diff --cc docs/file-format-parity.md
index ca53b0382,c7e6b0856..4f7df2383
--- a/docs/file-format-parity.md
+++ b/docs/file-format-parity.md
@@@ -143,10 -143,7 +143,11 @@@ 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 | 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 |