Skip to content

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

Merge PR #7258: fix(atn): reject off-center radial blur in .atn export (#7234)

aiongge41060429d48
diff --cc crates/engine/src/atn_cmds.rs
index c68151e2b,01ea95052..16059f61a
--- a/crates/engine/src/atn_cmds.rs
+++ b/crates/engine/src/atn_cmds.rs
@@@ -2957,148 -2664,32 +2957,174 @@@ fn gallery_to(id: &str, p: &Value) -> O
fields_to(p, fields, desc("null").with("GEfk", enm("GEft", code)))
}
+/// Select and Mask as Photoshop CC 2015.5 and later record it (`smartBrushWorkspace`); the
+/// older Refine Edge event is [`REFINE_EDGE`], which is also what Select and Mask exports as.
+const SMART_BRUSH: &[F] = &[
+ F("smartBrushRadius", "radius", Kind::Px),
+ F("smartBrushUseSmartRadius", "smartRadius", Kind::Bool),
+ F("smartBrushSmooth", "smooth", Kind::Long),
+ F("smartBrushFeather", "feather", Kind::Px),
+ F("smartBrushContrast", "contrast", Kind::Pct),
+ F("smartBrushShiftEdge", "shiftEdge", Kind::Pct),
+ F("smartBrushDecontaminate", "decontaminate", Kind::Bool),
+ F("smartBrushDeconAmount", "amount", Kind::Pct),
+ F("refineEdgeOutput", "output", Kind::Enum("refineEdgeOutput", REFINE_OUTPUT)),
+ F("sampleAllLayers", "sampleAllLayers", Kind::Bool),
+];
+
+/// Select › Color Range's `Clrs` presets ↔ `select.colorRange`'s `select`.
+const COLOR_RANGE: &[(&str, &str)] = &[
+ ("Rds", "reds"),
+ ("Ylws", "yellows"),
+ ("Grns", "greens"),
+ ("Cyns", "cyans"),
+ ("Bls", "blues"),
+ ("Mgnt", "magentas"),
+ ("Hghl", "highlights"),
+ ("Mdtn", "midtones"),
+ ("Shdw", "shadows"),
+ ("OtOf", "outOfGamut"),
+ ("skinTone", "skinTones"),
+];
+
+/// The Color Range keys the converter reads (or that don't change a preset's result:
+/// `colorModel` is the model of sampled colours).
+const COLOR_RANGE_KEYS: &[&str] = &[
+ "Clrs",
+ "Fzns",
+ "Invr",
+ "colorModel",
+ "shadowsFuzziness",
+ "shadowsUpperLimit",
+ "midtonesFuzziness",
+ "midtonesLowerLimit",
+ "midtonesUpperLimit",
+ "highlightsFuzziness",
+ "highlightsLowerLimit",
+];
+
+/// Color Range (`ClrR`) with a preset. Sampled Colors records Lab minimum and maximum colours,
+/// which `select.colorRange` (eyedropper points on the image) can't reproduce, and an unknown
+/// key (Detect Faces, Localized Color Clusters…) could change the result: both stay
+/// unsupported.
+fn color_range_from(d: &Descriptor) -> Mapped {
+ let unsupported = Mapped::Unsupported { harmless: false };
+ if d.items.iter().any(|(k, _)| !COLOR_RANGE_KEYS.contains(&trimmed(k).as_str())) {
+ return unsupported;
+ }
+ let Some(preset) = get_enum(d, "Clrs").and_then(|c| lookup(COLOR_RANGE, &c)) else { return unsupported };
+ let mut p = Map::new();
+ p.insert("select".into(), preset.into());
+ let key = |suffix: &str| get_num(d, &format!("{preset}{suffix}"));
+ match preset {
+ "skinTones" => {
+ if let Some(f) = get_num(d, "Fzns") {
+ p.insert("fuzziness".into(), f.into());
+ }
+ }
+ "shadows" | "midtones" | "highlights" => {
+ if let Some(f) = key("Fuzziness") {
+ p.insert("fuzziness".into(), f.into());
+ }
+ let range = match (preset, key("LowerLimit"), key("UpperLimit")) {
+ ("shadows", _, hi) => hi.map(Value::from),
+ ("highlights", lo, _) => lo.map(Value::from),
+ (_, Some(lo), Some(hi)) => Some(json!([lo, hi])),
+ (_, None, None) => None,
+ _ => return unsupported,
+ };
+ if let Some(r) = range {
+ p.insert("tonalRange".into(), r);
+ }
+ }
+ _ => {}
+ }
+ if get_bool(d, "Invr") == Some(true) {
+ p.insert("invert".into(), true.into());
+ }
+ step("select.colorRange", Value::Object(p))
+}
+
+fn color_range_to(_: &str, p: &Value) -> Option<Descriptor> {
+ let preset = jstr(p, "select")?;
+ if p.as_object()?.keys().any(|k| !matches!(k.as_str(), "select" | "fuzziness" | "tonalRange" | "invert")) {
+ return None;
+ }
+ let mut d = desc("null").with("Clrs", enm("Clrs", lookup_back(COLOR_RANGE, preset)?));
+ let tonal = matches!(preset, "shadows" | "midtones" | "highlights");
+ if let Some(f) = jnum(p, "fuzziness") {
+ match preset {
+ "skinTones" => d = d.with("Fzns", long(f)),
+ _ if tonal => d = d.with(&format!("{preset}Fuzziness"), long(f)),
+ _ => {}
+ }
+ }
+ if let Some(r) = p.get("tonalRange") {
+ match preset {
+ "shadows" => d = d.with("shadowsUpperLimit", long(r.as_f64()?)),
+ "highlights" => d = d.with("highlightsLowerLimit", long(r.as_f64()?)),
+ "midtones" => {
+ let a = r.as_array()?;
+ d = d.with("midtonesLowerLimit", long(a.first()?.as_f64()?)).with("midtonesUpperLimit", long(a.get(1)?.as_f64()?));
+ }
+ _ => return None,
+ }
+ }
+ if jbool(p, "invert") == Some(true) {
+ d = d.with("Invr", D::Boolean(true));
+ }
+ Some(d)
+}
+
+/// Create / Release Clipping Mask (`groupEvent` / `ungroup`) on the target or a named layer.
+fn clipping_from(d: &Descriptor, id: &str) -> Mapped {
+ match get_ref(d, "null") {
+ None => none(id),
+ Some(r) if ref_class(r).as_deref() == Some("Lyr") => match layer_target(r) {
+ Some(p) => step(id, Value::Object(p)),
+ None => Mapped::Unsupported { harmless: false },
+ },
+ Some(_) => Mapped::Unsupported { harmless: false },
+ }
+}
+
+fn clipping_to(_: &str, p: &Value) -> Option<Descriptor> {
+ Some(desc("null").with("null", layer_ref(p)))
+}
+
+/// A clipping mask event: `clipping_from` / `clipping_to` with one command id.
+macro_rules! clipping_event {
+ ($code:literal, $name:literal, $label:literal, $id:literal) => {
+ Event { code: $code, name: $name, label: $label, ids: &[$id], from: |d| clipping_from(d, $id), to: clipping_to }
+ };
+}
+
+ const RADIAL_BLUR_FIELDS: &[F] =
+ &[F("Amnt", "amount", Kind::Long), F("BlrM", "method", Kind::Enum("BlrM", RADIAL_METHOD)), F("BlrQ", "quality", Kind::Enum("BlrQ", RADIAL_QUALITY))];
+
+ fn radial_blur_from(d: &Descriptor) -> Mapped {
+ match fields_from(d, RADIAL_BLUR_FIELDS) {
+ Some(m) => step("filter.blur.radialBlur", Value::Object(m)),
+ None => Mapped::Unsupported { harmless: false },
+ }
+ }
+
+ fn radial_blur_to(_: &str, p: &Value) -> Option<Descriptor> {
+ if !pixel_target(p) {
+ return None;
+ }
+ // Photoshop's Radial Blur has no center parameter and always blurs from the center (0.5, 0.5).
+ // An explicit center must match 0.5 exactly; any non-default center cannot be faithfully exported.
+ let is_default_center = |k: &str| match p.get(k) {
+ None | Some(Value::Null) => true,
+ Some(v) => v.as_f64() == Some(0.5),
+ };
+ if !is_default_center("centerX") || !is_default_center("centerY") {
+ return None;
+ }
+ fields_to(p, RADIAL_BLUR_FIELDS, desc("null"))
+ }
+
/// Every Photoshop event PhotoCraft maps. The order matters only for the panel label.
const EVENTS: &[Event] = &[
// Filters.
diff --cc crates/engine/src/atn_cmds/tests.rs
index be52645d7,0e5e63a00..7b49a6b9b
--- a/crates/engine/src/atn_cmds/tests.rs
+++ b/crates/engine/src/atn_cmds/tests.rs
@@@ -1841,73 -1388,57 +1841,128 @@@ fn function_keys_keep_shift_and_command
assert_eq!(super::function_key_name(7, false, false), "F7");
}
+/// A param a PhotoCraft step leaves out exports as PhotoCraft's default wherever Photoshop plays
+/// the missing key differently (checked against Photoshop): Canvas Size anchors top left,
+/// Apply Image blends Normal, Color Balance turns preserve luminosity off, and a Paint Bucket
+/// step without a tolerance doesn't play at all.
+#[test]
+fn defaults_photoshop_plays_differently_are_written() {
+ let exported = |id: &str, p: Value| export_item(id, &p, "S").and_then(|i| i.descriptor).unwrap_or_else(|| panic!("{id} does not export"));
+ let bucket = exported("paint.bucket", json!({"x": 1, "y": 2}));
+ assert_eq!((get_num(&bucket, "Tlrn"), get_bool(&bucket, "AntA")), (Some(32.0), Some(true)));
+ let canvas = exported("image.canvasSize", json!({"width": 10, "height": 10}));
+ assert_eq!((get_enum(&canvas, "Hrzn").as_deref(), get_enum(&canvas, "Vrtc").as_deref()), (Some("Cntr"), Some("Cntr")));
+ let apply = exported("image.applyImage", json!({}));
+ assert_eq!(get_obj(&apply, "With").and_then(|w| get_enum(w, "Clcl")).as_deref(), Some("Mltp"));
+ let balance = exported("image.adjustments.colorBalance", json!({"midtones": [10, 0, 0]}));
+ assert_eq!(get_bool(&balance, "PrsL"), Some(true));
+ assert_eq!(get_list(&balance, "ShdL").map(<[D]>::len), Some(3));
+}
+
+/// Photoshop sets one colour per step: a step that sets both doesn't export rather than drop one.
+#[test]
+fn set_colors_exports_only_a_single_colour() {
+ assert!(export_item("tools.setColors", &json!({"foreground": "#ff0000", "background": "#0000ff"}), "S").is_none());
+ assert!(export_item("tools.setColors", &json!({"foregroundCmyk": [0, 0, 0, 100], "background": "#0000ff"}), "S").is_none());
+ assert!(export_item("tools.setColors", &json!({"background": "#0000ff"}), "S").is_some());
+}
+
+/// Photoshop's reset of an adjustment layer (`set` with an empty `T`) stays a reset: `kind`
+/// only joins params that edit something, as any key makes `layer.setAdjustment` merge.
+#[test]
+fn adjustment_layer_reset_still_resets() {
+ let set = |t: Descriptor| desc("null").with("null", target_ref("AdjL")).with("T ", D::Descriptor(t));
+ let reset = set(desc("HStr").with("presetKind", enm("presetKindType", "presetKindDefault")));
+ let edit = set(desc("ClrB").with("MdtL", D::List(vec![long(10.0), long(0.0), long(0.0)])));
+ let file = AtnFile {
+ name: UnicodeString::new_nul("Reset"),
+ expanded: false,
+ actions: vec![AtnAction {
+ name: UnicodeString::new_nul("A"),
+ items: vec![item("setd", "Set", Some(reset)), item("setd", "Set", Some(edit))],
+ ..Default::default()
+ }],
+ warnings: vec![],
+ };
+ let steps = import(&atn::write(&file).unwrap()).unwrap().actions.remove(0).steps;
+ assert_eq!(steps[0], ("layer.setAdjustment".to_string(), json!({})));
+ assert_eq!(steps[1].1, json!({"midtones": [10, 0, 0], "kind": "colorBalance"}));
+}
+
+/// Photoshop's Select and Mask descriptor as mapped has no field for the Refine Edge Brush,
+/// so a step with brush strokes must not export as a plain Select and Mask without them.
+#[test]
+fn refine_edge_with_brush_strokes_is_not_exported_without_them() {
+ for mode in ["add", "subtract"] {
+ let brushed = Action {
+ name: "Probe".into(),
+ steps: vec![("select.refineEdge".into(), json!({"radius": 1, "refineStrokes": [{"points": [[5, 4]], "size": 4, "mode": mode}]}))],
+ ..Default::default()
+ };
+ assert!(export("Audit", &[&brushed], &[], false).is_err(), "{mode}");
+ let (_, skipped) = export("Audit", &[&brushed], &[], true).unwrap();
+ assert_eq!(skipped, vec![Skipped { action: "Probe".into(), step: 0, id: "select.refineEdge".into() }]);
+ }
+ for params in [json!({"radius": 1}), json!({"radius": 1, "refineStrokes": []}), json!({"radius": 1, "refineStrokes": null})] {
+ let plain = Action { name: "Plain".into(), steps: vec![("select.refineEdge".into(), params)], ..Default::default() };
+ let (bytes, skipped) = export("Audit", &[&plain], &[], false).unwrap();
+ assert!(skipped.is_empty());
+ let imported = import(&bytes).unwrap();
+ assert_eq!(imported.actions[0].steps, vec![("select.refineEdge".to_string(), json!({"radius": 1}))]);
+ }
+}
++
+ #[test]
+ fn radial_blur_off_center_strict_export_refuses_silent_recentering() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 16, "height": 16})).unwrap();
+
+ // Default center (omitted) exports successfully
+ s.actions.list.push(Action::new("DefaultCenter", vec![("filter.blur.radialBlur".into(), json!({"amount": 50, "method": "spin", "quality": "good"}))]));
+ let saved = s.execute("actions.save", json!({"action": "DefaultCenter"})).unwrap();
+ assert_eq!(saved["steps"], 1);
+
+ // Explicit (0.5, 0.5) center also exports successfully
+ s.actions.list.push(Action::new(
+ "ExplicitDefaultCenter",
+ vec![("filter.blur.radialBlur".into(), json!({"amount": 50, "method": "spin", "quality": "good", "centerX": 0.5, "centerY": 0.5}))],
+ ));
+ let saved_exp = s.execute("actions.save", json!({"action": "ExplicitDefaultCenter"})).unwrap();
+ assert_eq!(saved_exp["steps"], 1);
+
+ // Off-center radial blur cannot be silently recentered in strict export
+ s.actions.list.push(Action::new(
+ "OffCenter",
+ vec![("filter.blur.radialBlur".into(), json!({"amount": 50, "method": "spin", "quality": "good", "centerX": 0.1, "centerY": 0.2}))],
+ ));
+ let before_actions = s.actions.list.clone();
+ let err = s.execute("actions.save", json!({"action": "OffCenter"}));
+ assert!(err.is_err(), "strict export must reject off-center radial blur rather than silently recentering it");
+ assert_eq!(s.actions.list, before_actions, "actions list must remain unchanged after rejected save");
+
+ // With skipUnsupported: true, off-center radial blur is skipped
+ let skipped = s.execute("actions.save", json!({"action": "OffCenter", "skipUnsupported": true})).unwrap();
+ assert_eq!(skipped["steps"], 0);
+ assert_eq!(skipped["skipped"][0]["id"], "filter.blur.radialBlur");
+
+ // Radial blur targeting a mask must not export as a plain filter that edits pixels
+ s.actions
+ .list
+ .push(Action::new("MaskTarget", vec![("filter.blur.radialBlur".into(), json!({"amount": 50, "method": "spin", "quality": "good", "target": "mask"}))]));
+ let before_actions = s.actions.list.clone();
+ let err_mask = s.execute("actions.save", json!({"action": "MaskTarget"}));
+ assert!(err_mask.is_err(), "strict export must reject radial blur with non-pixel target");
+ assert_eq!(s.actions.list, before_actions, "actions list must remain unchanged after rejected save");
+
+ let skipped_mask = s.execute("actions.save", json!({"action": "MaskTarget", "skipUnsupported": true})).unwrap();
+ assert_eq!(skipped_mask["steps"], 0);
+ assert_eq!(skipped_mask["skipped"][0]["id"], "filter.blur.radialBlur");
+
+ // Explicit pixels target exports successfully
+ s.actions.list.push(Action::new(
+ "PixelsTarget",
+ vec![("filter.blur.radialBlur".into(), json!({"amount": 50, "method": "spin", "quality": "good", "target": "pixels"}))],
+ ));
+ let saved_pixels = s.execute("actions.save", json!({"action": "PixelsTarget"})).unwrap();
+ assert_eq!(saved_pixels["steps"], 1);
+ }