Skip to content

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

Actions: map Select Subject, Select and Mask, Color Range, clipping masks, layer masks and colours from .atn (part of #6745)

Higgs325840769fa22ff1a
diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs
index ebeda4868..6c837ac00 100644
--- a/crates/engine/src/atn_cmds.rs
+++ b/crates/engine/src/atn_cmds.rs
@@ -697,9 +697,11 @@ fn channel_mixer_to(p: &Value) -> Option<Descriptor> {
Some(d.with("Mnch", D::Boolean(jbool(p, "monochrome").unwrap_or(false))))
}
+/// Photoshop's `Clrs` colour-range enumeration. Yellows is `Ylws` (`Yllw` is the yellow ink
+/// key); earlier PhotoCraft builds wrote `Yllw`, which import still reads (#6745).
const SELECTIVE_RANGES: &[(&str, &str)] = &[
("Rds", "reds"),
- ("Yllw", "yellows"),
+ ("Ylws", "yellows"),
("Grns", "greens"),
("Cyns", "cyans"),
("Bls", "blues"),
@@ -716,7 +718,8 @@ fn selective_from(d: &Descriptor) -> Option<Value> {
}
for e in get_list(d, "ClrC").unwrap_or(&[]) {
let D::Descriptor(e) = e else { return None };
- let name = lookup(SELECTIVE_RANGES, &get_enum(e, "Clrs")?)?;
+ let range = get_enum(e, "Clrs")?;
+ let name = lookup(SELECTIVE_RANGES, if range == "Yllw" { "Ylws" } else { &range })?;
let v = |k: &str| get_num(e, k).unwrap_or(0.0);
out.insert(name.into(), json!([v("Cyn "), v("Mgnt"), v("Yllw"), v("Blck")]));
}
@@ -982,6 +985,14 @@ fn pattern_desc(p: &Value) -> Option<Descriptor> {
Some(t)
}
+/// Layer › Layer Mask: the `UsrM` value of an Add Layer Mask `Mk` ↔ its command.
+const MASK_USING: &[(&str, &str)] = &[
+ ("RvlA", "layer.layerMask.revealAll"),
+ ("HdAl", "layer.layerMask.hideAll"),
+ ("RvlS", "layer.layerMask.revealSelection"),
+ ("HdSl", "layer.layerMask.hideSelection"),
+];
+
fn make_from(d: &Descriptor) -> Mapped {
// Duplicate layer/group into a new document: `Mk` with a document class, a layer
// `Usng`, an optional `Nm` (the new document's name) and an optional `LyrN`
@@ -1003,6 +1014,16 @@ fn make_from(d: &Descriptor) -> Mapped {
}
return step("layer.duplicate", Value::Object(p));
}
+ // Add Layer Mask: a `Chnl` class made at the mask channel, `Usng` what it reveals.
+ if let Some(D::Class(c)) = d.get("Nw ")
+ && trimmed(&c.class_id) == "Chnl"
+ {
+ let at_mask = get_ref(d, "At ").is_some_and(|r| ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Ordinal(o) if o == "Msk"));
+ return match get_enum(d, "Usng").and_then(|u| lookup(MASK_USING, &u)) {
+ Some(id) if at_mask => none(id),
+ _ => Mapped::Unsupported { harmless: false },
+ };
+ }
if let Some(nw) = get_obj(d, "Nw ") {
// Layer via Copy / Cut (`Usng` = the selection), or a new document.
if get_enum(d, "Usng").as_deref() == Some("Slct") {
@@ -1152,6 +1173,14 @@ fn make_to(id: &str, p: &Value) -> Option<Descriptor> {
}
d
}
+ "layer.layerMask.revealAll" | "layer.layerMask.hideAll" | "layer.layerMask.revealSelection" | "layer.layerMask.hideSelection" => {
+ // Photoshop adds the mask to the target layer only.
+ if p.get("layer").is_some() {
+ return None;
+ }
+ let at = D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: code("Msk ") }]);
+ desc("null").with("Nw ", D::Class(class("Chnl"))).with("At ", at).with("Usng", enm("UsrM", lookup_back(MASK_USING, id)?))
+ }
"file.newFromClipboard" => desc("null").with("Nw ", D::Descriptor(desc("Dcmn").with("preset", text("Clipboard")))),
"file.new" => {
let mut n = desc("Dcmn");
@@ -1229,6 +1258,15 @@ fn set_from(d: &Descriptor) -> Mapped {
}
_ => unsupported,
},
+ // The foreground or background colour (Color Picker, Swatches). Colours in other models
+ // (Lab, CMYK, a colour book) stay unsupported.
+ (Some("Clr"), Target::Property(p)) if p == "FrgC" || p == "BckC" => match get_obj(d, "T ").and_then(color_hex) {
+ Some(c) => {
+ let which = if p == "FrgC" { "foreground" } else { "background" };
+ step("tools.setColors", json!({ which: c }))
+ }
+ None => unsupported,
+ },
// Quick Mask mode on (`set` of the document's quick-mask property); `clearEvent` turns it off.
(Some("Prpr"), Target::Property(p)) if p == "QucM" => step("select.editInQuickMaskMode", json!({"on": true})),
// Layer › New › Layer From Background (Photoshop records the New Layer dialog's values
@@ -1373,6 +1411,18 @@ fn set_to(id: &str, p: &Value) -> Option<Descriptor> {
}
desc("null").with("null", layer_ref(p)).with("T ", D::Descriptor(t))
}
+ "tools.setColors" => {
+ let (key, hex) = match (jstr(p, "foreground"), jstr(p, "background")) {
+ (Some(f), None) => ("FrgC", f),
+ (None, Some(b)) => ("BckC", b),
+ _ => return None,
+ };
+ if p.as_object()?.len() != 1 {
+ return None;
+ }
+ let r = D::Reference(vec![ReferenceItem::Property { class: class("Clr "), key: Id::new(key) }]);
+ desc("null").with("null", r).with("T ", D::Descriptor(color_desc(hex)?))
+ }
"layer.new.layerFromBackground" => {
let bckg = D::Reference(vec![ReferenceItem::Property { class: class("Lyr "), key: Id::new("Bckg") }]);
desc("null").with("null", bckg).with("T ", D::Descriptor(desc("Lyr ").with("Opct", pct(100.0)).with("Md ", enm("BlnM", "Nrml"))))
@@ -2543,6 +2593,141 @@ fn gallery_to(id: &str, p: &Value) -> Option<Descriptor> {
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)))
+}
+
/// Every Photoshop event PhotoCraft maps. The order matters only for the panel label.
const EVENTS: &[Event] = &[
// Filters.
@@ -2760,6 +2945,10 @@ const EVENTS: &[Event] = &[
"layer.newAdjustmentLayer.channelMixer",
"layer.newAdjustmentLayer.selectiveColor",
"layer.newAdjustmentLayer.gradientMap",
+ "layer.layerMask.revealAll",
+ "layer.layerMask.hideAll",
+ "layer.layerMask.revealSelection",
+ "layer.layerMask.hideSelection",
"file.new",
"file.newFromClipboard",
],
@@ -2784,6 +2973,7 @@ const EVENTS: &[Event] = &[
"layer.setAdjustment",
"layer.fill.pattern.set",
"layer.new.layerFromBackground",
+ "tools.setColors",
],
from: set_from,
to: set_to,
@@ -2841,6 +3031,22 @@ const EVENTS: &[Event] = &[
to: merge_visible_to,
},
ev!("Mrg2", "mergeLayersNew", "Merge Layers", "layer.mergeLayers", &[]),
+ Event {
+ code: "GrpL",
+ name: "groupEvent",
+ label: "Create Clipping Mask",
+ ids: &["layer.createClippingMask"],
+ from: |d| clipping_from(d, "layer.createClippingMask"),
+ to: clipping_to,
+ },
+ Event {
+ code: "Ungr",
+ name: "ungroup",
+ label: "Release Clipping Mask",
+ ids: &["layer.releaseClippingMask"],
+ from: |d| clipping_from(d, "layer.releaseClippingMask"),
+ to: clipping_to,
+ },
ev!("CpTL", "copyToLayer", "Layer Via Copy", "layer.new.layerViaCopy", &[]),
ev!("CtTL", "cutToLayer", "Layer Via Cut", "layer.new.layerViaCut", &[]),
ev!("", "rasterizeLayer", "Rasterize", "layer.rasterize.layer", &[]),
@@ -2872,6 +3078,9 @@ const EVENTS: &[Event] = &[
ev!("Grow", "grow", "Grow", "select.grow", &[F("Tlrn", "tolerance", Kind::Long)]),
ev!("Smlr", "similar", "Similar", "select.similar", &[F("Tlrn", "tolerance", Kind::Long)]),
ev!("", "refineSelectionEdge", "Select and Mask", "select.refineEdge", REFINE_EDGE),
+ ev!("", "smartBrushWorkspace", "Select and Mask", "select.refineEdge", SMART_BRUSH),
+ ev!("", "autoCutout", "Select Subject", "select.subject", &[F("sampleAllLayers", "sampleAllLayers", Kind::Bool)]),
+ Event { code: "ClrR", name: "colorRange", label: "Color Range", ids: &["select.colorRange"], from: color_range_from, to: color_range_to },
// Edit.
Event { code: "Fl ", name: "fill", label: "Fill", ids: &["edit.fill", "paint.bucket"], from: fill_from, to: fill_to },
ev!("Strk", "stroke", "Stroke", "edit.stroke", STROKE),
diff --git a/crates/engine/src/atn_cmds/tests.rs b/crates/engine/src/atn_cmds/tests.rs
index 871300372..fa8f9032b 100644
--- a/crates/engine/src/atn_cmds/tests.rs
+++ b/crates/engine/src/atn_cmds/tests.rs
@@ -198,7 +198,20 @@ fn every_mapped_command_exports_and_imports_back() {
json!({"reds": 40, "yellows": 60, "greens": 40, "cyans": 60, "blues": 20, "magentas": 80, "tint": true, "tintColor": "#e4d5b0"}),
),
("image.adjustments.channelMixer", json!({"red": [100, 0, 0, 0], "green": [0, 90, 10, 0], "blue": [0, 0, 100, 5], "monochrome": false})),
- ("image.adjustments.selectiveColor", json!({"method": "absolute", "reds": [10, 0, -5, 0], "neutrals": [0, 0, 0, 3]})),
+ ("image.adjustments.selectiveColor", json!({"method": "absolute", "reds": [10, 0, -5, 0], "yellows": [0, 5, 0, 0], "neutrals": [0, 0, 0, 3]})),
+ ("select.subject", json!({"sampleAllLayers": false})),
+ ("select.colorRange", json!({"select": "midtones", "fuzziness": 30, "tonalRange": [90, 160], "invert": true})),
+ ("select.colorRange", json!({"select": "skinTones", "fuzziness": 40})),
+ ("select.colorRange", json!({"select": "highlights", "tonalRange": 200})),
+ ("select.colorRange", json!({"select": "reds"})),
+ ("layer.createClippingMask", json!({})),
+ ("layer.releaseClippingMask", json!({"layer": "Shadow"})),
+ ("layer.layerMask.revealAll", json!({})),
+ ("layer.layerMask.hideAll", json!({})),
+ ("layer.layerMask.revealSelection", json!({})),
+ ("layer.layerMask.hideSelection", json!({})),
+ ("tools.setColors", json!({"foreground": "#336699"})),
+ ("tools.setColors", json!({"background": "#ffffff"})),
("image.adjustments.desaturate", json!({})),
("image.autoTone", json!({})),
("image.imageSize", json!({"width": 800, "height": 600, "resolution": 72, "resample": "bicubicSharper"})),
@@ -479,6 +492,95 @@ fn unsupported_shapes_become_photoshop_steps_not_errors() {
assert!(imp.actions[0].disabled.is_empty(), "steps with a document effect stay on so playback reports them");
}
+/// #6745: the events of a Photoshop 2026 retouching set (ID-photo background swap, whitening,
+/// highlight cleanup, high-pass sharpening), in the stringID form Photoshop wrote them.
+#[test]
+fn retouching_set_events_map_to_their_commands() {
+ let smart_brush = desc("null")
+ .with("smartBrushRadius", px(3.0))
+ .with("smartBrushSmooth", long(2.0))
+ .with("smartBrushFeather", px(0.5))
+ .with("smartBrushContrast", pct(10.0))
+ .with("smartBrushShiftEdge", pct(-20.0))
+ .with("sampleAllLayers", D::Boolean(false))
+ .with("smartBrushUseSmartRadius", D::Boolean(true))
+ .with("smartBrushDecontaminate", D::Boolean(false))
+ .with("smartBrushDeconAmount", pct(100.0))
+ .with("refineEdgeOutput", enm("refineEdgeOutput", "refineEdgeOutputUserMask"));
+ let selective = desc("null").with("Mthd", enm("CrcM", "Rltv")).with(
+ "ClrC",
+ D::List(vec![
+ D::Descriptor(
+ desc("ClrC").with("Clrs", enm("Clrs", "Ylws")).with("Cyn ", pct(-30.0)).with("Mgnt", pct(0.0)).with("Yllw", pct(-40.0)).with("Blck", pct(0.0)),
+ ),
+ D::Descriptor(
+ desc("ClrC").with("Clrs", enm("Clrs", "Whts")).with("Cyn ", pct(0.0)).with("Mgnt", pct(0.0)).with("Yllw", pct(0.0)).with("Blck", pct(-10.0)),
+ ),
+ ]),
+ );
+ let lab = |l: f64| D::Descriptor(desc("LbCl").with("Lmnc", D::Double(l)).with("A ", D::Double(0.0)).with("B ", D::Double(0.0)));
+ let sampled = desc("null").with("Fzns", long(40.0)).with("Mnm ", lab(80.0)).with("Mxm ", lab(95.0)).with("colorModel", long(0.0));
+ let mask = desc("null")
+ .with("Nw ", D::Class(class("Chnl")))
+ .with("At ", D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: code("Msk ") }]))
+ .with("Usng", enm("UsrM", "RvlS"));
+ let fg = desc("null")
+ .with("null", D::Reference(vec![ReferenceItem::Property { class: class("Clr "), key: Id::new("FrgC") }]))
+ .with("T ", D::Descriptor(desc("RGBC").with("Rd ", D::Double(0.0)).with("Grn ", D::Double(0.0)).with("Bl ", D::Double(255.0))));
+ let lab_fg = desc("null").with("null", D::Reference(vec![ReferenceItem::Property { class: class("Clr "), key: Id::new("BckC") }])).with("T ", lab(50.0));
+ let items = vec![
+ item("autoCutout", "Select Subject", Some(desc("null").with("sampleAllLayers", D::Boolean(false)))),
+ item("smartBrushWorkspace", "Select and Mask", Some(smart_brush)),
+ item("selectiveColor", "Selective Color", Some(selective)),
+ item("colorRange", "Color Range", Some(desc("null").with("Clrs", enm("Clrs", "skinTone")).with("Fzns", long(40.0)))),
+ item("colorRange", "Color Range", Some(sampled)),
+ item("colorRange", "Color Range", Some(desc("null").with("Clrs", enm("Clrs", "Rds ")).with("UsFc", D::Boolean(true)))),
+ item("make", "Make", Some(mask)),
+ item("set", "Set", Some(fg)),
+ item("set", "Set", Some(lab_fg)),
+ item("groupEvent", "Create Clipping Mask", Some(desc("null").with("null", target_ref("Lyr ")))),
+ item("someFutureEvent", "Something New", Some(desc("null").with("Amnt", long(5.0)))),
+ ];
+ let file = AtnFile {
+ name: UnicodeString::new_nul("Retouch"),
+ expanded: false,
+ actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }],
+ warnings: vec![],
+ };
+ let imp = import(&atn::write(&file).unwrap()).unwrap();
+ let steps = &imp.actions[0].steps;
+ let expected = [
+ ("select.subject", json!({"sampleAllLayers": false})),
+ (
+ "select.refineEdge",
+ json!({"radius": 3, "smartRadius": true, "smooth": 2, "feather": 0.5, "contrast": 10, "shiftEdge": -20, "decontaminate": false, "amount": 100, "output": "layerMask", "sampleAllLayers": false}),
+ ),
+ ("image.adjustments.selectiveColor", json!({"method": "relative", "yellows": [-30, 0, -40, 0], "whites": [0, 0, 0, -10]})),
+ ("select.colorRange", json!({"select": "skinTones", "fuzziness": 40})),
+ (PHOTOSHOP_STEP, Value::Null),
+ (PHOTOSHOP_STEP, Value::Null),
+ ("layer.layerMask.revealSelection", json!({})),
+ ("tools.setColors", json!({"foreground": "#0000ff"})),
+ (PHOTOSHOP_STEP, Value::Null),
+ ("layer.createClippingMask", json!({})),
+ (PHOTOSHOP_STEP, Value::Null),
+ ];
+ assert_eq!(steps.len(), expected.len(), "{steps:?}");
+ for ((id, params), (want_id, want)) in steps.iter().zip(&expected) {
+ assert_eq!(id, want_id, "{steps:?}");
+ if *want_id != PHOTOSHOP_STEP {
+ assert_eq!(params, want, "{id}");
+ }
+ }
+ // Sampled Colors (Lab range), an unknown Color Range key, a Lab colour and an unknown
+ // event stay unsupported rather than play with other values.
+ let unsupported: Vec<(&str, usize)> = imp.unsupported.iter().map(|u| (u.event.as_str(), u.step)).collect();
+ assert_eq!(unsupported, [("colorRange", 4), ("colorRange", 5), ("set", 8), ("someFutureEvent", 10)]);
+ // A legacy PhotoCraft export's `Yllw` yellows still read.
+ let legacy = desc("null").with("ClrC", D::List(vec![D::Descriptor(desc("ClrC").with("Clrs", enm("Clrs", "Yllw")).with("Cyn ", pct(5.0)))]));
+ assert_eq!(selective_from(&legacy), Some(json!({"yellows": [5.0, 0.0, 0.0, 0.0]})));
+}
+
#[test]
fn step_commands_and_bad_params_fail_gracefully() {
let mut s = Session::new();