Skip to content

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

Play real Photoshop action sets: TrueGrit .atn mappings and fixes (#4356, #219) (#4698)

John Cambra3a307a757ed1
diff --git a/crates/algo/src/artistic_fx.rs b/crates/algo/src/artistic_fx.rs
index 7f75041b1..4d2e85ed1 100644
--- a/crates/algo/src/artistic_fx.rs
+++ b/crates/algo/src/artistic_fx.rs
@@ -427,7 +427,7 @@ pub(crate) fn effect_reach(e: &GalleryEffect) -> i32 {
F::Crosshatch => (g("strokeLength") / 3.0) as i32 + gs(1.0) + 2,
F::DarkStrokes => 9,
F::InkOutlines => (g("strokeLength") / 2.0) as i32 + 3,
- F::Spatter => g("sprayRadius").ceil() as i32 + 2,
+ F::Spatter => (g("sprayRadius") * 1.5).ceil() as i32 + 2,
F::SprayedStrokes => g("sprayRadius").ceil() as i32 + (g("strokeLength") / 2.0) as i32 + 3,
F::SumiE => gs(g("strokeWidth") * 0.2) + (g("strokeWidth") / 2.0) as i32 + 2,
F::Glass => (g("distortion") * 2.0).ceil() as i32 + 2,
@@ -768,9 +768,26 @@ fn apply(e: &GalleryEffect, win: &mut Win, ctx: &Ctx) {
win.c[i] = map(win.c[i], |v| (v + (1.0 - v) * lt) * (1.0 - dk) * (1.0 - clamp01(ink)));
}
}
- F::Spatter | F::SprayedStrokes => {
+ F::Spatter => {
+ // Smoothness smooths the random displacement: a larger feature size and, as with any
+ // averaged noise, a smaller reach. Low smoothness sprays specks out to the full
+ // radius; high smoothness leaves a torn but attached, hard edge (what Photoshop
+ // shows at Smoothness 15).
let rad = g("sprayRadius");
- let sc = if e.filter == F::Spatter { 0.6 + g("smoothness") * 0.25 } else { 1.2 };
+ let feature = 1.0 + g("smoothness") * 0.35;
+ let reach = (rad * 1.2 / feature).min(rad);
+ let src = Win { r: win.r, w, h, c: win.c.clone() };
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let (fx, fy) = (x as f32 / feature, y as f32 / feature);
+ let dx = (fbm(fx, fy, 91) - 0.5) * 3.0 * reach;
+ let dy = (fbm(fx, fy, 92) - 0.5) * 3.0 * reach;
+ win.c[i] = src.sample(x as f32 + 0.5 + dx, y as f32 + 0.5 + dy);
+ }
+ }
+ F::SprayedStrokes => {
+ let rad = g("sprayRadius");
+ let sc = 1.2;
let src = Win { r: win.r, w, h, c: win.c.clone() };
for i in 0..win.c.len() {
let (x, y) = win.xy(i);
@@ -779,9 +796,7 @@ fn apply(e: &GalleryEffect, win: &mut Win, ctx: &Ctx) {
let dy = (vnoise(fx, fy, 92) - 0.5) * 2.0 * rad;
win.c[i] = src.sample(x as f32 + 0.5 + dx, y as f32 + 0.5 + dy);
}
- if e.filter == F::SprayedStrokes {
- line_blur3(&mut win.c, w, h, direction(e.choice("strokeDirection")), (g("strokeLength") / 2.0) as usize);
- }
+ line_blur3(&mut win.c, w, h, direction(e.choice("strokeDirection")), (g("strokeLength") / 2.0) as usize);
}
F::SumiE => {
let sw = g("strokeWidth");
diff --git a/crates/algo/src/pixelate.rs b/crates/algo/src/pixelate.rs
index 1a1325975..df6edb5ff 100644
--- a/crates/algo/src/pixelate.rs
+++ b/crates/algo/src/pixelate.rs
@@ -115,8 +115,11 @@ pub(crate) fn color_halftone(src: &Image, out: Rect, ctx: &Ctx, max_radius: f32,
res
}
-/// Crystallize: Voronoi cells around jittered points, each filled with the
-/// (premultiplied) average colour of its pixels.
+/// Crystallize: Voronoi cells around jittered points, each filled with the colour at its
+/// point, as Photoshop's are: cells stay solid, so a black-and-white image (a layer mask
+/// being distressed) keeps hard edges and its weight instead of greying where cells straddle
+/// an edge. A cell whose point falls outside the image takes the (premultiplied) average
+/// colour of its pixels.
pub(crate) fn crystallize(src: &Image, out: Rect, ctx: &Ctx, cell_size: f32, seed: u32) -> Vec<f32> {
let n = src.ch;
let cell = cell_size.max(2.0);
@@ -177,6 +180,14 @@ pub(crate) fn crystallize(src: &Image, out: Rect, ctx: &Ctx, cell_size: f32, see
continue;
}
let (cx, cy) = if win.contains(x, y) { owners[i] } else { owner(x, y) };
+ let (sx, sy) = cell_point(cx, cy, cell, seed, origin);
+ let (sx, sy) = (sx.floor() as i32, sy.floor() as i32);
+ if src.rect.contains(sx, sy) && b.contains(sx, sy) {
+ for (c, v) in px.iter_mut().enumerate() {
+ *v = src.get(sx, sy, c);
+ }
+ continue;
+ }
if cx < c0.0 || cy < c0.1 || cx > c1.0 || cy > c1.1 {
continue;
}
diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs
index e5c8e7467..391c21abd 100644
--- a/crates/engine/src/atn_cmds.rs
+++ b/crates/engine/src/atn_cmds.rs
@@ -167,6 +167,8 @@ fn class(c: &str) -> Class {
/// The pixel and percent units of a `UntF` value.
const PX: [u8; 4] = *b"#Pxl";
const PCT: [u8; 4] = *b"#Prc";
+/// Points (1/72 in): what Photoshop calls "relative" units.
+const PT: [u8; 4] = *b"#Rlt";
fn px(v: f64) -> D {
D::UnitFloat { unit: PX, value: v }
@@ -937,6 +939,49 @@ fn adjustment_steps(a: &Adjustment, prefix: &str, type_desc: Option<&Descriptor>
step(&format!("{prefix}{}", a.suffix), params)
}
+/// A `patternLayer` descriptor's pattern, scale, angle and link as the params of
+/// `layer.newFillLayer.pattern` / `layer.fill.pattern.set`. The pattern goes by name: ids differ
+/// between Photoshop's library and one rebuilt from the same `.pat` file. None for a pattern
+/// recorded without a name or id.
+fn pattern_params(t: &Descriptor) -> Option<Map<String, Value>> {
+ let mut p = Map::new();
+ if let Some(ptrn) = get_obj(t, "Ptrn") {
+ let key = get_text(ptrn, "Nm ").filter(|n| !n.is_empty()).or_else(|| get_text(ptrn, "Idnt").filter(|i| !i.is_empty()))?;
+ p.insert("pattern".into(), key.into());
+ }
+ if let Some(s) = get_num(t, "Scl ") {
+ p.insert("scale".into(), s.into());
+ }
+ if let Some(a) = get_num(t, "Angl") {
+ p.insert("angle".into(), a.into());
+ }
+ if let Some(l) = get_bool(t, "Algn") {
+ p.insert("link".into(), l.into());
+ }
+ Some(p)
+}
+
+/// The `patternLayer` descriptor for [`pattern_params`]' params.
+fn pattern_desc(p: &Value) -> Option<Descriptor> {
+ let mut t = desc("patternLayer");
+ if let Some(n) = jstr(p, "pattern") {
+ t = t.with("Ptrn", D::Descriptor(desc("Ptrn").with("Nm ", text(n))));
+ }
+ if let Some(s) = jnum(p, "scale") {
+ t = t.with("Scl ", pct(s));
+ }
+ if let Some(a) = jnum(p, "angle") {
+ t = t.with("Angl", ang(a));
+ }
+ if let Some(l) = jbool(p, "link") {
+ t = t.with("Algn", D::Boolean(l));
+ }
+ if p.get("phase").is_some() {
+ return None;
+ }
+ Some(t)
+}
+
fn make_from(d: &Descriptor) -> Mapped {
if let Some(nw) = get_obj(d, "Nw ") {
// Layer via Copy / Cut (`Usng` = the selection), or a new document.
@@ -1010,6 +1055,10 @@ fn make_from(d: &Descriptor) -> Mapped {
Some(c) => step("layer.newFillLayer.solidColor", json!({"color": c})),
None => none("layer.newFillLayer.solidColor"),
},
+ Some(t) if t.class_id.is("patternLayer") => match pattern_params(t) {
+ Some(p) => step("layer.newFillLayer.pattern", Value::Object(p)),
+ None => Mapped::Unsupported { harmless: false },
+ },
_ => Mapped::Unsupported { harmless: false },
},
Some("layerSection") => {
@@ -1061,6 +1110,13 @@ fn make_to(id: &str, p: &Value) -> Option<Descriptor> {
}
desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t))))
}
+ "layer.newFillLayer.pattern" => {
+ if p.get("path").is_some() {
+ return None;
+ }
+ let t = pattern_desc(p)?;
+ desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t))))
+ }
"file.newFromClipboard" => desc("null").with("Nw ", D::Descriptor(desc("Dcmn").with("preset", text("Clipboard")))),
"file.new" => {
let mut n = desc("Dcmn");
@@ -1106,6 +1162,8 @@ fn set_from(d: &Descriptor) -> Mapped {
},
Some(D::Reference(t)) => match (ref_class(t).as_deref(), target(t)) {
(Some("Chnl"), Target::Ordinal(o)) if o == "Trsp" => step("select.loadSelection", json!({"channel": "transparency"})),
+ // ⌘-click on the targeted channel (a layer mask after `select` of `Msk`).
+ (Some("Chnl"), Target::Ordinal(o)) if o == "Trgt" => step("select.loadSelection", json!({"channel": "targeted"})),
(Some("Chnl"), Target::Name(n)) => step("select.loadSelection", json!({"channel": n})),
_ => unsupported,
},
@@ -1138,6 +1196,37 @@ fn set_from(d: &Descriptor) -> Mapped {
},
// 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
+ // as a `set` of the Background); values other than the defaults then apply to the layer.
+ (Some("Lyr"), Target::Property(p)) if p == "Bckg" => {
+ // On an image that opened as a normal layer there is no Background to convert;
+ // Photoshop stops there, but the step's purpose (an editable layer) is met.
+ // Photoshop's `set` of another layer doesn't target it: the selected layer stays.
+ let mut v = vec![("layer.new.layerFromBackground", json!({"ifPresent": true, "select": false}))];
+ let mut props = Map::new();
+ props.insert("layer".into(), "Layer 0".into());
+ if let Some(t) = get_obj(d, "T ") {
+ if let Some(n) = get_text(t, "Nm ") {
+ props.insert("name".into(), n.into());
+ }
+ if let Some(o) = get_num(t, "Opct").filter(|o| (o - 100.0).abs() > 1e-9) {
+ props.insert("opacity".into(), (o / 100.0).into());
+ }
+ match get_enum(t, "Md ").as_deref() {
+ None | Some("Nrml") => {}
+ Some(m) => match blend_label(m) {
+ Some(label) => {
+ props.insert("blend".into(), label.into());
+ }
+ None => return unsupported,
+ },
+ }
+ }
+ if props.len() > 1 {
+ v.push(("layer.setProps", Value::Object(props)));
+ }
+ steps(v)
+ }
(Some("Lyr"), _) => {
let Some(mut p) = layer_target(r) else { return unsupported };
let Some(t) = get_obj(d, "T ") else { return unsupported };
@@ -1168,6 +1257,14 @@ fn set_from(d: &Descriptor) -> Mapped {
}
if v.is_empty() { unsupported } else { steps(v) }
}
+ // A Pattern Fill layer's pattern (double-click its thumbnail).
+ (Some("contentLayer"), Target::Ordinal(o)) if o == "Trgt" => match get_obj(d, "T ") {
+ Some(t) if t.class_id.is("patternLayer") => match pattern_params(t) {
+ Some(p) if !p.is_empty() => step("layer.fill.pattern.set", Value::Object(p)),
+ _ => unsupported,
+ },
+ _ => unsupported,
+ },
(Some("AdjL"), Target::Ordinal(o)) if o == "Trgt" => {
match get_obj(d, "T ").and_then(|t| adjustment_by_class(&trimmed(&t.class_id)).map(|a| (a, t))) {
Some((a, t)) => match (a.from)(t) {
@@ -1190,6 +1287,7 @@ fn set_to(id: &str, p: &Value) -> Option<Descriptor> {
"select.reselect" => sel(enm("Ordn", "Prvs")),
"select.loadSelection" => match jstr(p, "channel")? {
"transparency" => sel(D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: Id::new("Chnl"), value: Id::new("Trsp") }])),
+ "targeted" => sel(D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: Id::new("Ordn"), value: Id::new("Trgt") }])),
name => sel(name_ref("Chnl", name)),
},
"select.lasso" => {
@@ -1240,6 +1338,16 @@ fn set_to(id: &str, p: &Value) -> Option<Descriptor> {
}
desc("null").with("null", layer_ref(p)).with("T ", D::Descriptor(t))
}
+ "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"))))
+ }
+ "layer.fill.pattern.set" => {
+ if p.get("layer").is_some() || p.get("document").is_some() {
+ return None;
+ }
+ desc("null").with("null", target_ref("contentLayer")).with("T ", D::Descriptor(pattern_desc(p)?))
+ }
"layer.setAdjustment" => {
// The adjustment kind isn't in the params: Photoshop needs it, so only steps that
// name one (`kind`) export.
@@ -1260,11 +1368,24 @@ fn select_from(d: &Descriptor) -> Mapped {
match (ref_class(r).as_deref(), target(r)) {
(Some("Lyr"), Target::Name(n)) => {
let mut p = json!({"layer": n});
- if get_enum(d, "selectionModifier").as_deref() == Some("addToSelection") {
- p["mode"] = json!("add");
+ match get_enum(d, "selectionModifier").as_deref() {
+ Some("addToSelection") => p["mode"] = json!("add"),
+ Some("removeFromSelection") => p["mode"] = json!("remove"),
+ _ => {}
}
step("layer.select", p)
}
+ // The Channels panel: the active layer's mask, or back to the composite (`RGB`, `CMYK`…).
+ (Some("Chnl"), Target::Ordinal(o)) => match o.as_str() {
+ "Msk" => step("channel.target", json!({"channel": "mask"})),
+ "RGB" | "CMYK" | "Lab" | "Gry" => step("channel.target", json!({"channel": "composite"})),
+ // Re-selecting the channel that is already targeted changes nothing.
+ "Trgt" => Mapped::Unsupported { harmless: true },
+ _ => Mapped::Unsupported { harmless: false },
+ },
+ // History › Step Backward / Step Forward.
+ (Some("HstS"), Target::Ordinal(o)) if o == "Prvs" => none("edit.undo"),
+ (Some("HstS"), Target::Ordinal(o)) if o == "Nxt" => none("edit.redo"),
(Some("Lyr"), Target::Ordinal(o)) => {
// Shift+Alt+[ / ] add the next layer to the selection instead of replacing it.
let add = get_enum(d, "selectionModifier").as_deref() == Some("addToSelection");
@@ -1285,14 +1406,28 @@ fn select_from(d: &Descriptor) -> Mapped {
fn select_to(id: &str, p: &Value) -> Option<Descriptor> {
let ord = |o: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code(o) }]);
+ let enumerated = |cls: &str, ty: &str, v: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class(cls), type_id: code(ty), value: code(v) }]);
Some(match id {
"layer.select" => {
let mut d = desc("null").with("null", name_ref("Lyr ", jstr(p, "layer")?));
- if jstr(p, "mode") == Some("add") {
- d = d.with("selectionModifier", enm("selectionModifierType", "addToSelection"));
+ match jstr(p, "mode") {
+ None | Some("replace") => {}
+ Some("add") => d = d.with("selectionModifier", enm("selectionModifierType", "addToSelection")),
+ Some("remove") => d = d.with("selectionModifier", enm("selectionModifierType", "removeFromSelection")),
+ Some(_) => return None,
}
d.with("MkVs", D::Boolean(false))
}
+ "channel.target" => {
+ let v = match jstr(p, "channel") {
+ Some("mask") => "Msk ",
+ None | Some("composite") => "RGB ",
+ Some(_) => return None,
+ };
+ desc("null").with("null", enumerated("Chnl", "Chnl", v)).with("MkVs", D::Boolean(false))
+ }
+ "edit.undo" => desc("null").with("null", enumerated("HstS", "Ordn", "Prvs")),
+ "edit.redo" => desc("null").with("null", enumerated("HstS", "Ordn", "Nxt ")),
"layer.selectAbove" => desc("null").with("null", ord("Frwr")),
"layer.selectBelow" => desc("null").with("null", ord("Bckw")),
"layer.addAboveToSelection" => desc("null").with("null", ord("Frwr")).with("selectionModifier", enm("selectionModifierType", "addToSelection")),
@@ -1679,14 +1814,25 @@ fn move_from(d: &Descriptor) -> Mapped {
let Some(mut p) = layer_target(r) else { return Mapped::Unsupported { harmless: false } };
match d.get("T ") {
Some(D::Descriptor(t)) => {
- let in_px = |k: &str| matches!(t.get(k), Some(D::UnitFloat { unit: PX, .. }));
+ let unit = |k: &str| match t.get(k) {
+ Some(D::UnitFloat { unit, .. }) => Some(*unit),
+ _ => None,
+ };
let (Some(dx), Some(dy)) = (get_num(t, "Hrzn"), get_num(t, "Vrtc")) else { return Mapped::Unsupported { harmless: false } };
- if !in_px("Hrzn") || !in_px("Vrtc") {
- // Points at an unknown resolution.
- return Mapped::Unsupported { harmless: false };
+ match (unit("Hrzn"), unit("Vrtc")) {
+ (Some(PX), Some(PX)) => {
+ p.insert("dx".into(), dx.round().into());
+ p.insert("dy".into(), dy.round().into());
+ }
+ // A nudge recorded with the rulers in other units: points, converted to pixels
+ // at the resolution of the document the action plays on.
+ (Some(PT), Some(PT)) => {
+ p.insert("dx".into(), dx.into());
+ p.insert("dy".into(), dy.into());
+ p.insert("units".into(), "pt".into());
+ }
+ _ => return Mapped::Unsupported { harmless: false },
}
- p.insert("dx".into(), dx.round().into());
- p.insert("dy".into(), dy.round().into());
step("layer.translate", Value::Object(p))
}
Some(D::Reference(t)) => {
@@ -1708,7 +1854,15 @@ fn move_from(d: &Descriptor) -> Mapped {
fn move_to(id: &str, p: &Value) -> Option<Descriptor> {
let ord = |o: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code(o) }]);
let t = match id {
- "layer.translate" => D::Descriptor(desc("Ofst").with("Hrzn", px(jnum(p, "dx").unwrap_or(0.0))).with("Vrtc", px(jnum(p, "dy").unwrap_or(0.0)))),
+ "layer.translate" => {
+ let unit = match jstr(p, "units") {
+ None | Some("px") => PX,
+ Some("pt") => PT,
+ Some(_) => return None,
+ };
+ let v = |k: &str| D::UnitFloat { unit, value: jnum(p, k).unwrap_or(0.0) };
+ D::Descriptor(desc("Ofst").with("Hrzn", v("dx")).with("Vrtc", v("dy")))
+ }
"layer.arrange.bringToFront" => ord("Frnt"),
"layer.arrange.sendToBack" => ord("Back"),
"layer.arrange.bringForward" => ord("Nxt "),
@@ -1941,17 +2095,59 @@ fn convert_mode_from(d: &Descriptor) -> Mapped {
_ => Mapped::Unsupported { harmless: false },
};
}
- match get_enum(d, "T ").and_then(|t| lookup(MODES, &t)) {
+ // The mode as an enumeration (`ClrS.Grys`), a class (`Grys`), or an object of the mode's
+ // class holding its options (`BtmM {Rslt, Mthd}`, `Grys {Rt}` from Bitmap).
+ let (mode, options) = match d.get("T ") {
+ Some(D::Enumerated { value, .. }) => (trimmed(value), None),
+ Some(D::Class(c)) => (trimmed(&c.class_id), None),
+ Some(D::Descriptor(o)) => (trimmed(&o.class_id), Some(o)),
+ _ => return Mapped::Unsupported { harmless: false },
+ };
+ if mode == "BtmM" {
+ return bitmap_from(options);
+ }
+ // Bitmap to Grayscale records a size ratio; only 1 keeps the pixels as they are.
+ if options.and_then(|o| get_num(o, "Rt ")).is_some_and(|r| (r - 1.0).abs() > 1e-9) {
+ return Mapped::Unsupported { harmless: false };
+ }
+ match lookup(MODES, &mode) {
Some(m) => none(&format!("image.mode.{m}")),
None => Mapped::Unsupported { harmless: false },
}
}
-fn convert_mode_to(id: &str, _: &Value) -> Option<Descriptor> {
+const BITMAP_METHOD: &[(&str, &str)] = &[("Thrh", "threshold"), ("PtnD", "pattern"), ("DfnD", "diffusion")];
+
+/// Image › Mode › Bitmap. Its Output resolution resamples the image, keeping the print size,
+/// before the conversion; at the document's own resolution that is a no-op. Halftone screens
+/// and custom patterns stay unsupported.
+fn bitmap_from(options: Option<&Descriptor>) -> Mapped {
+ let Some(o) = options else { return none("image.mode.bitmap") };
+ let method = match get_enum(o, "Mthd") {
+ None => "diffusion",
+ Some(m) => match lookup(BITMAP_METHOD, &m) {
+ Some(m) => m,
+ None => return Mapped::Unsupported { harmless: false },
+ },
+ };
+ let convert = ("image.mode.bitmap", json!({"method": method}));
+ match get_num(o, "Rslt") {
+ Some(r) => steps(vec![("image.imageSize", json!({"resolution": r, "resample": "bicubic", "keepPrintSize": true})), convert]),
+ None => steps(vec![convert]),
+ }
+}
+
+fn bitmap_to(p: &Value) -> Option<Descriptor> {
+ let method = lookup_back(BITMAP_METHOD, jstr(p, "method").unwrap_or("diffusion"))?;
+ Some(desc("null").with("T ", D::Descriptor(desc("BtmM").with("Mthd", enm("Mthd", method)))))
+}
+
+fn convert_mode_to(id: &str, p: &Value) -> Option<Descriptor> {
Some(match id {
"image.mode.bits8" => desc("null").with("Dpth", long(8.0)),
"image.mode.bits16" => desc("null").with("Dpth", long(16.0)),
"image.mode.bits32" => desc("null").with("Dpth", long(32.0)),
+ "image.mode.bitmap" => bitmap_to(p)?,
_ => desc("null").with("T ", enm("ClrS", lookup_back(MODES, id.strip_prefix("image.mode.")?)?)),
})
}
@@ -2065,6 +2261,10 @@ fn image_size_from(d: &Descriptor) -> Mapped {
match lookup(INTERPOLATION, &i) {
Some(i) => {
p.insert("resample".into(), i.into());
+ // Resample on with only the resolution changed: Photoshop keeps the print size.
+ if p.contains_key("resolution") && !p.contains_key("width") && !p.contains_key("height") && !p.contains_key("percent") {
+ p.insert("keepPrintSize".into(), true.into());
+ }
}
None => return Mapped::Unsupported { harmless: false },
}
@@ -2257,6 +2457,48 @@ macro_rules! adjustment_event {
};
}
+const RIPPLE_SIZE: &[(&str, &str)] = &[("Sml", "small"), ("Mdm", "medium"), ("Lrg", "large")];
+
+/// Select and Mask (`refineSelectionEdge`). Smart Radius, decontamination and the output follow
+/// Photoshop's; the edge itself is PhotoCraft's own matting, so results differ in detail.
+const REFINE_EDGE: &[F] = &[
+ F("refineEdgeBorderRadius", "radius", Kind::Px),
+ F("refineEdgeAutoRadius", "smartRadius", Kind::Bool),
+ F("refineEdgeSmooth", "smooth", Kind::Long),
+ F("refineEdgeFeatherRadius", "feather", Kind::Px),
+ F("refineEdgeBorderContrast", "contrast", Kind::Pct),
+ F("refineEdgeChoke", "shiftEdge", Kind::Pct),
+ F("refineEdgeDecontaminate", "decontaminate", Kind::Bool),
+ F("refineEdgeDeconAmount", "amount", Kind::Pct),
+ F("refineEdgeOutput", "output", Kind::Enum("refineEdgeOutput", REFINE_OUTPUT)),
+];
+const REFINE_OUTPUT: &[(&str, &str)] = &[
+ ("refineEdgeOutputSelection", "selection"),
+ ("refineEdgeOutputUserMask", "layerMask"),
+ ("refineEdgeOutputNewLayer", "newLayer"),
+ ("refineEdgeOutputNewLayerWithMask", "newLayerWithMask"),
+ ("refineEdgeOutputNewDocument", "newDocument"),
+ ("refineEdgeOutputNewDocumentWithMask", "newDocumentWithMask"),
+];
+
+/// Filter Gallery effects (`GEfc` with the effect in `GEfk`): Photoshop's effect code, the
+/// command, and its fields. A stack of several effects stays unsupported.
+const GALLERY: &[(&str, &str, &[F])] = &[("Spt", "filter.gallery.spatter", &[F("SprR", "sprayRadius", Kind::Long), F("Smth", "smoothness", Kind::Long)])];
+const GALLERY_IDS: &[&str] = &["filter.gallery.spatter"];
+
+fn gallery_from(d: &Descriptor) -> Mapped {
+ let Some(effect) = get_enum(d, "GEfk") else { return Mapped::Unsupported { harmless: false } };
+ match GALLERY.iter().find(|(code, _, _)| *code == effect).and_then(|(_, id, fields)| Some((*id, fields_from(d, fields)?))) {
+ Some((id, p)) => step(id, Value::Object(p)),
+ None => Mapped::Unsupported { harmless: false },
+ }
+}
+
+fn gallery_to(id: &str, p: &Value) -> Option<Descriptor> {
+ let (code, _, fields) = GALLERY.iter().find(|(_, cmd, _)| *cmd == id)?;
+ fields_to(p, fields, desc("null").with("GEfk", enm("GEft", code)))
+}
+
/// Every Photoshop event PhotoCraft maps. The order matters only for the panel label.
const EVENTS: &[Event] = &[
// Filters.
@@ -2320,6 +2562,9 @@ const EVENTS: &[Event] = &[
"filter.other.offset",
&[F("Hrzn", "horizontal", Kind::Long), F("Vrtc", "vertical", Kind::Long), F("Fl ", "undefinedAreas", Kind::Enum("FlMd", OFFSET_FILL))]
),
+ ev!("Rple", "ripple", "Ripple", "filter.distort.ripple", &[F("Amnt", "amount", Kind::Long), F("RplS", "size", Kind::Enum("RplS", RIPPLE_SIZE))]),
+ ev!("Crst", "crystallize", "Crystallize", "filter.pixelate.crystallize", &[F("ClSz", "cellSize", Kind::Long)]),
+ Event { code: "GEfc", name: "filterGallery", label: "Filter Gallery", ids: GALLERY_IDS, from: gallery_from, to: gallery_to },
// Adjustments (Image › Adjustments).
Event {
code: "Lvls",
@@ -2436,6 +2681,7 @@ const EVENTS: &[Event] = &[
"image.mode.bits8",
"image.mode.bits16",
"image.mode.bits32",
+ "image.mode.bitmap",
],
from: convert_mode_from,
to: convert_mode_to,
@@ -2453,6 +2699,7 @@ const EVENTS: &[Event] = &[
"layer.new.layerViaCopy",
"layer.new.layerViaCut",
"layer.newFillLayer.solidColor",
+ "layer.newFillLayer.pattern",
"layer.newAdjustmentLayer.levels",
"layer.newAdjustmentLayer.curves",
"layer.newAdjustmentLayer.hueSaturation",
@@ -2490,6 +2737,8 @@ const EVENTS: &[Event] = &[
"layer.renameLayer",
"layer.setLabelColor",
"layer.setAdjustment",
+ "layer.fill.pattern.set",
+ "layer.new.layerFromBackground",
],
from: set_from,
to: set_to,
@@ -2506,6 +2755,9 @@ const EVENTS: &[Event] = &[
"layer.addBelowToSelection",
"layer.selectTop",
"layer.selectBottom",
+ "channel.target",
+ "edit.undo",
+ "edit.redo",
],
from: select_from,
to: select_to,
@@ -2574,6 +2826,7 @@ const EVENTS: &[Event] = &[
ev!("Brdr", "border", "Border", "select.modify.border", &[F("Wdth", "radius", Kind::Px)]),
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),
// 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 fc73a1841..11aa53bd8 100644
--- a/crates/engine/src/atn_cmds/tests.rs
+++ b/crates/engine/src/atn_cmds/tests.rs
@@ -295,6 +295,26 @@ fn every_mapped_command_exports_and_imports_back() {
("actions.conditional", json!({"if": "landscape", "then": "Wide", "else": null, "set": "S"})),
("actions.play", json!({"action": "Other", "set": "S"})),
(STOP_MESSAGE, json!({"message": "Hi", "allowContinue": false})),
+ // The TrueGrit Texture Supply sets (Debaser, Distress Press, Halftone Zine Machine).
+ ("filter.distort.ripple", json!({"amount": 50, "size": "medium"})),
+ ("filter.pixelate.crystallize", json!({"cellSize": 5})),
+ ("filter.gallery.spatter", json!({"sprayRadius": 7, "smoothness": 15})),
+ (
+ "select.refineEdge",
+ json!({"radius": 0, "smartRadius": false, "smooth": 2, "feather": 0.5, "contrast": 15, "shiftEdge": -100, "decontaminate": false, "output": "layerMask"}),
+ ),
+ ("channel.target", json!({"channel": "mask"})),
+ ("channel.target", json!({"channel": "composite"})),
+ ("edit.undo", json!({})),
+ ("edit.redo", json!({})),
+ ("layer.select", json!({"layer": "YELLOW", "mode": "remove"})),
+ ("layer.translate", json!({"dx": 0.36, "dy": -1.08, "units": "pt"})),
+ ("select.loadSelection", json!({"channel": "targeted"})),
+ ("layer.newFillLayer.pattern", json!({"pattern": "Debaser-Distressed-Dark", "scale": 50, "angle": 0, "link": true})),
+ ("layer.fill.pattern.set", json!({"pattern": "1 -R2.jpg"})),
+ ("image.mode.bitmap", json!({"method": "threshold"})),
+ ("image.imageSize", json!({"resolution": 1200, "resample": "preserveDetails", "keepPrintSize": true})),
+ ("layer.new.layerFromBackground", json!({"ifPresent": true, "select": false})),
];
for (id, params) in &cases {
let item = export_item(id, params, "S").unwrap_or_else(|| panic!("{id} does not export"));
@@ -409,7 +429,7 @@ fn every_mapped_command_exports_and_imports_back() {
#[test]
fn unsupported_shapes_become_photoshop_steps_not_errors() {
// Image size in two different percentages, a Paint Bucket click in percent of the canvas, a
- // move in points, an unknown adjustment class.
+ // move in percent, an unknown adjustment class.
let items = vec![
item("ImgS", "Image Size", Some(desc("null").with("Wdth", pct(200.0)).with("Hght", pct(150.0)))),
item(
@@ -420,10 +440,7 @@ fn unsupported_shapes_become_photoshop_steps_not_errors() {
item(
"move",
"Move",
- Some(desc("null").with("null", target_ref("Lyr ")).with(
- "T ",
- D::Descriptor(desc("Ofst").with("Hrzn", D::UnitFloat { unit: *b"#Rlt", value: 3.0 }).with("Vrtc", D::UnitFloat { unit: *b"#Rlt", value: 1.0 })),
- )),
+ Some(desc("null").with("null", target_ref("Lyr ")).with("T ", D::Descriptor(desc("Ofst").with("Hrzn", pct(3.0)).with("Vrtc", pct(1.0))))),
),
item(
"make",
@@ -746,3 +763,177 @@ fn remaining_events_import_in_their_photoshop_shapes() {
let e = s.execute("image.applyImage", json!({"source": {"layer": "Nope"}})).unwrap_err().to_string();
assert!(e.contains("Nope"), "{e}");
}
+
+fn channel_ord(value: &str) -> D {
+ D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: Id::new("Chnl"), value: code(value) }])
+}
+
+fn fsel(t: D) -> Descriptor {
+ desc("null").with("null", D::Reference(vec![ReferenceItem::Property { class: class("Chnl"), key: Id::new("fsel") }])).with("T ", t)
+}
+
+fn set_of(name: &str, actions: Vec<(&str, Vec<AtnItem>)>) -> String {
+ let file = AtnFile {
+ name: UnicodeString::new_nul(name),
+ expanded: false,
+ actions: actions.into_iter().map(|(n, items)| AtnAction { name: UnicodeString::new_nul(n), items, ..Default::default() }).collect(),
+ warnings: vec![],
+ };
+ b64(&atn::write(&file).unwrap())
+}
+
+/// The step shapes of the TrueGrit Texture Supply sets (Distress Press, Debaser, Transparency,
+/// Halftone Zine Machine), rebuilt here as Photoshop records them, import and play: the
+/// distressing filters land on the targeted layer mask, Remove White leaves the white
+/// transparent, nudges in points follow the resolution, and Step Backward undoes a step.
+#[test]
+fn distressing_and_remove_white_shapes_import_and_play() {
+ let ord = |cls: &str, ty: &str, v: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class(cls), type_id: Id::new(ty), value: code(v) }]);
+ let black = D::Descriptor(desc("RGBC").with("Rd ", D::Double(0.0)).with("Grn ", D::Double(0.0)).with("Bl ", D::Double(0.0)));
+ let fill = desc("null")
+ .with("null", class_ref("contentLayer"))
+ .with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(desc("solidColorLayer").with("Clr ", black)))));
+ let refine = desc("null")
+ .with("refineEdgeBorderRadius", px(0.0))
+ .with("refineEdgeBorderContrast", pct(100.0))
+ .with("refineEdgeSmooth", long(2.0))
+ .with("refineEdgeFeatherRadius", px(0.0))
+ .with("refineEdgeChoke", pct(0.0))
+ .with("refineEdgeAutoRadius", D::Boolean(false))
+ .with("refineEdgeDecontaminate", D::Boolean(false))
+ .with("refineEdgeOutput", enm("refineEdgeOutput", "refineEdgeOutputUserMask"));
+ let distress = vec![
+ item("setd", "Set", Some(fsel(channel_ord("Trsp")))),
+ item("Hd ", "Hide", Some(desc("null").with("null", D::List(vec![target_ref("Lyr ")])))),
+ item("Mk ", "Make", Some(fill)),
+ item("slct", "Select", Some(desc("null").with("null", channel_ord("Msk")).with("MkVs", D::Boolean(false)))),
+ item("refineSelectionEdge", "Select and Mask", Some(refine)),
+ item("Rple", "Ripple", Some(desc("null").with("Amnt", long(50.0)).with("RplS", enm("RplS", "Sml")))),
+ item("Crst", "Crystallize", Some(desc("null").with("ClSz", long(3.0)))),
+ item("GEfc", "Filter Gallery", Some(desc("null").with("GEfk", enm("GEft", "Spt")).with("SprR", long(7.0)).with("Smth", long(15.0)))),
+ item("slct", "Select", Some(desc("null").with("null", ord("Chnl", "Ordn", "Trgt")).with("MkVs", D::Boolean(false)))),
+ item("setd", "Set", Some(fsel(ord("Chnl", "Ordn", "Trgt")))),
+ ];
+ let bckg = D::Reference(vec![ReferenceItem::Property { class: class("Lyr "), key: Id::new("Bckg") }]);
+ let remove_white = vec![
+ item("CnvM", "Convert Mode", Some(desc("null").with("T ", D::Class(class("Grys"))))),
+ item(
+ "setd",
+ "Set",
+ Some(desc("null").with("null", bckg).with("T ", D::Descriptor(desc("Lyr ").with("Opct", pct(100.0)).with("Md ", enm("BlnM", "Nrml"))))),
+ ),
+ item("setd", "Set", Some(fsel(ord("Chnl", "Ordn", "Trgt")))),
+ item("Dlt ", "Delete", None),
+ item("setd", "Set", Some(fsel(enm("Ordn", "None")))),
+ ];
+ let pt = |v: f64| D::UnitFloat { unit: PT, value: v };
+ let nudge = vec![item(
+ "move",
+ "Move",
+ Some(desc("null").with("null", target_ref("Lyr ")).with("T ", D::Descriptor(desc("Ofst").with("Hrzn", pt(0.36)).with("Vrtc", pt(-0.36))))),
+ )];
+ let undo = vec![item("Invs", "Inverse", None), item("slct", "Select", Some(desc("null").with("null", ord("HstS", "Ordn", "Prvs"))))];
+ let data = set_of("TrueGrit", vec![("Distress", distress), ("Remove White", remove_white), ("Nudge", nudge), ("Undo", undo)]);
+
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 120, "height": 80, "resolution": 200})).unwrap();
+ s.execute("layer.new.layer", json!({"name": "Ink"})).unwrap();
+ s.execute("select.rect", json!({"x": 20, "y": 20, "width": 80, "height": 40})).unwrap();
+ s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ let r = s.execute("actions.load", json!({"data": data})).unwrap();
+ // Only the re-selection of the targeted channel stays a Photoshop step, switched off.
+ let unsupported: Vec<&str> = r["unsupported"].as_array().unwrap().iter().map(|u| u["action"].as_str().unwrap()).collect();
+ assert_eq!(unsupported, ["Distress"], "{r}");
+
+ let r = s.execute("actions.play", json!({"action": "Distress"})).unwrap();
+ assert!(r.get("failed").is_none(), "{r}");
+ let st = s.active().unwrap();
+ let fill = st.doc.layer(st.active_layer.unwrap()).unwrap();
+ let mask = &fill.mask.as_ref().expect("the fill layer is masked by the ink").surface;
+ // The rectangle's straight top edge is roughened: pixels along it differ.
+ let edge: Vec<f32> = (20..100).map(|x| mask.sample_channel(x, 20, 0)).collect();
+ assert!(edge.iter().any(|v| *v < 0.5) && edge.iter().any(|v| *v > 0.5), "{edge:?}");
+ assert!(mask.sample_channel(60, 40, 0) > 0.9 && mask.sample_channel(5, 5, 0) < 0.1);
+ assert!(st.doc.selection.is_some(), "the targeted mask loads as the selection");
+ assert_eq!(st.channel_view.target, crate::channel_cmds::ChannelTarget::LayerMask);
+
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 40, "height": 30})).unwrap();
+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 10})).unwrap();
+ s.execute("edit.fill", json!({"contents": "color", "color": "#202020"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ s.execute("actions.load", json!({"data": data})).unwrap();
+ let r = s.execute("actions.play", json!({"action": "Remove White"})).unwrap();
+ assert!(r.get("failed").is_none(), "{r}");
+ let d = &s.active().unwrap().doc;
+ assert_eq!(d.mode, photocraft_color::ColorMode::Grayscale);
+ let l = d.layers.last().unwrap();
+ assert!(!d.is_background(l.id), "Layer From Background");
+ let surf = l.surface().unwrap();
+ assert!(surf.sample_channel(2, 2, 1) < 0.01, "white is cleared");
+ assert!((surf.sample_channel(20, 15, 1) - (1.0 - 32.0 / 255.0)).abs() < 0.02, "the ink keeps its darkness as opacity");
+ // An image that opened as a normal layer has no Background: the step leaves it as it is.
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 40, "height": 30, "background": "transparent"})).unwrap();
+ s.execute("edit.fill", json!({"contents": "white"})).unwrap();
+ s.execute("actions.load", json!({"data": data})).unwrap();
+ let r = s.execute("actions.play", json!({"action": "Remove White"})).unwrap();
+ assert!(r.get("failed").is_none(), "{r}");
+ let surf = s.active().unwrap().doc.layers.last().unwrap().surface().unwrap().clone();
+ assert!(surf.sample_channel(2, 2, 1) < 0.01, "white is cleared without a Background");
+
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 40, "height": 30, "resolution": 200})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 5, "height": 5})).unwrap();
+ s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap();
+ s.execute("actions.load", json!({"data": data})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ assert!(s.execute("actions.play", json!({"action": "Nudge"})).unwrap().get("failed").is_none());
+ let st = s.active().unwrap();
+ let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds();
+ assert_eq!((b.x0, b.y0), (11, 9), "0.36 pt is 1 px at 200 ppi");
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap();
+ let before = s.active().unwrap().doc.selection.clone();
+ assert!(s.execute("actions.play", json!({"action": "Undo"})).unwrap().get("failed").is_none());
+ assert_eq!(s.active().unwrap().doc.selection, before, "Step Backward undid the Inverse");
+}
+
+/// Remove White on art in its own layer above a white Background: the Background becomes a
+/// normal layer, but the art layer stays targeted, so the white is cleared from the art.
+#[test]
+fn remove_white_clears_the_targeted_layer_not_the_converted_background() {
+ let ord = |cls: &str, ty: &str, v: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class(cls), type_id: Id::new(ty), value: code(v) }]);
+ let bckg = D::Reference(vec![ReferenceItem::Property { class: class("Lyr "), key: Id::new("Bckg") }]);
+ let steps = vec![
+ item("CnvM", "Convert Mode", Some(desc("null").with("T ", D::Class(class("Grys"))))),
+ item(
+ "setd",
+ "Set",
+ Some(desc("null").with("null", bckg).with("T ", D::Descriptor(desc("Lyr ").with("Opct", pct(100.0)).with("Md ", enm("BlnM", "Nrml"))))),
+ ),
+ item("setd", "Set", Some(fsel(ord("Chnl", "Ordn", "Trgt")))),
+ item("Dlt ", "Delete", None),
+ item("setd", "Set", Some(fsel(enm("Ordn", "None")))),
+ ];
+ let data = set_of("TrueGrit", vec![("Remove White", steps)]);
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 40, "height": 30})).unwrap();
+ let art = s.execute("layer.new.layer", json!({"name": "Art"})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("edit.fill", json!({"contents": "white"})).unwrap();
+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 10})).unwrap();
+ s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ s.execute("actions.load", json!({"data": data})).unwrap();
+ let r = s.execute("actions.play", json!({"action": "Remove White"})).unwrap();
+ assert!(r.get("failed").is_none(), "{r}");
+ let st = s.active().unwrap();
+ assert_eq!(st.active_layer.map(|l| l.0), Some(art), "the art layer stays targeted");
+ let art = st.doc.layer(photocraft_doc::LayerId(art)).unwrap().surface().unwrap();
+ assert!(art.sample_channel(2, 2, 1) < 0.01, "the art's white is cleared");
+ assert!(art.sample_channel(20, 15, 1) > 0.99, "the black stays");
+ let bottom = st.doc.layers.first().unwrap();
+ assert!(!st.doc.is_background(bottom.id), "the Background became a normal layer");
+ assert!(bottom.surface().unwrap().sample_channel(2, 2, 1) > 0.99, "and kept its pixels");
+}
diff --git a/crates/engine/src/channel_clip.rs b/crates/engine/src/channel_clip.rs
index 8b1739d16..fc52cf0a4 100644
--- a/crates/engine/src/channel_clip.rs
+++ b/crates/engine/src/channel_clip.rs
@@ -73,7 +73,7 @@ pub(crate) fn copy(s: &mut Session) -> Result<Option<Value>> {
if bounds.is_empty() {
return Err(EngineError::Other("Could not copy: the selected area is empty".into()));
}
- s.clipboard = Some(Clip { surface, bounds, layers: None });
+ s.clipboard = Some(Clip { surface, bounds, layers: None, resolution: Some(doc.resolution_dpi) });
Ok(Some(json!({"bounds": [bounds.x0, bounds.y0, bounds.width(), bounds.height()], "channel": k})))
}
diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs
index 45391cac3..089db6c85 100644
--- a/crates/engine/src/channel_cmds.rs
+++ b/crates/engine/src/channel_cmds.rs
@@ -897,6 +897,20 @@ fn load_selection(s: &mut Session, p: &Value) -> Result<Value> {
if p.get("channel").is_none() {
return Err(bad(cmd, "missing `channel`"));
}
+ // `"targeted"`: the Channels panel's target, as a Photoshop action's "load the target
+ // channel" step records it.
+ let mut targeted = p.clone();
+ if p.get("channel").and_then(Value::as_str) == Some("targeted") {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ targeted["channel"] = match st.channel_view.target {
+ ChannelTarget::Composite => json!("composite"),
+ ChannelTarget::Color(k) => json!({ "color": k }),
+ ChannelTarget::Alpha(i) => json!(i),
+ ChannelTarget::LayerMask => json!("mask"),
+ ChannelTarget::VectorMask => json!("vectorMask"),
+ };
+ }
+ let p = &targeted;
// Composite and colour channels load their luminosity / values, as ⌘-clicking them does.
let plane = source(s, p, cmd, true)?.into_iter().next().ok_or_else(|| bad(cmd, "the channel has no pixels"))?;
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
@@ -1722,7 +1736,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Load Selection…",
["Select"],
None,
- r##"{"channel":index|name|"composite"|"red|green|blue|…"|"transparency"|"mask"|"vectorMask"|"quickMask"|"selection","layer":id?,"document":index?,"invert":bool=false,"operation":"new|add|subtract|intersect"="new"}"##,
+ r##"{"channel":index|name|"composite"|"red|green|blue|…"|"transparency"|"mask"|"vectorMask"|"quickMask"|"selection"|"targeted" (the Channels panel's target),"layer":id?,"document":index?,"invert":bool=false,"operation":"new|add|subtract|intersect"="new"}"##,
has_doc,
load_selection
),
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 09db339bf..89278165e 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -652,7 +652,7 @@ fn build() -> Vec<CommandSpec> {
"Select Layer",
[],
None,
- r##"{"layer":id,"mode":"replace|toggle|range|add"="replace"} (toggle = ⌘-click, range = ⇧-click)"##,
+ r##"{"layer":id,"mode":"replace|toggle|range|add|remove"="replace"} (toggle = ⌘-click, range = ⇧-click, remove = deselect it, keeping at least one)"##,
has_doc,
crate::layer_multi_cmds::select
),
@@ -922,7 +922,7 @@ fn build() -> Vec<CommandSpec> {
"Move Layer",
[],
None,
- r##"{"layer":id?,"dx":i32,"dy":i32,"target":"pixels"|"mask"="pixels"} (no layer: every selected layer; linked layers follow; target mask: a layer whose mask is unlinked moves that mask alone, a linked mask moves with the layer)"##,
+ r##"{"layer":id?,"dx":i32,"dy":i32,"units":"px"|"pt"="px" (pt: points, whole pixels at the document's resolution),"target":"pixels"|"mask"="pixels"} (no layer: every selected layer; linked layers follow; target mask: a layer whose mask is unlinked moves that mask alone, a linked mask moves with the layer)"##,
has_layer,
crate::layer_multi_cmds::translate
),
diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs
index d4de2d548..0f965c261 100644
--- a/crates/engine/src/edit_cmds.rs
+++ b/crates/engine/src/edit_cmds.rs
@@ -28,6 +28,9 @@ pub struct Clip {
/// than rasterize (see [`whole_layer`]): a scratch document in the source's colour holding it.
/// `surface` still holds its pixels, for Paste Into, masks, channels and other apps.
pub layers: Option<Box<Document>>,
+ /// The source document's resolution (ppi): File › New from the clipboard takes it, as
+ /// Photoshop's Clipboard preset does. None for an image from another app.
+ pub resolution: Option<f32>,
}
/// Photoshop's layer-based copy (CC 2018 on): with no selection, Copy takes the active layer
@@ -148,7 +151,7 @@ fn lift(src: &Surface, sel: Option<&Surface>, canvas: Rect) -> Result<Clip> {
};
let mut out = Surface::new(with_alpha);
if area.is_empty() {
- return Ok(Clip { surface: out, bounds: Rect::EMPTY, layers: None });
+ return Ok(Clip { surface: out, bounds: Rect::EMPTY, layers: None, resolution: None });
}
// Only the selected area is read: converting the whole layer (a 24 MP Background gaining
// alpha) cost about a second per Layer via Copy (#668).
@@ -186,7 +189,7 @@ fn lift(src: &Surface, sel: Option<&Surface>, canvas: Rect) -> Result<Clip> {
out.try_write_region(area, &px).map_err(|e| EngineError::Other(format!("not enough memory while copying pixels ({e}); the document was not changed")))?;
out.prune();
let bounds = out.content_bounds();
- Ok(Clip { surface: out, bounds, layers: None })
+ Ok(Clip { surface: out, bounds, layers: None, resolution: None })
}
/// Merged composite of the visible document as a surface in the document's format.
@@ -221,6 +224,7 @@ fn copy(s: &mut Session, merged: bool) -> Result<Value> {
return Err(EngineError::Other("Could not copy: the selected area is empty".into()));
}
let b = clip.bounds;
+ let clip = Clip { resolution: Some(d.doc.resolution_dpi), ..clip };
s.clipboard = Some(clip);
Ok(json!({"bounds": [b.x0, b.y0, b.width(), b.height()]}))
}
@@ -263,7 +267,8 @@ fn copy_mask(s: &mut Session) -> Result<Value> {
return Err(EngineError::Other("Could not copy: the selected area is empty".into()));
}
let b = bounds;
- s.clipboard = Some(Clip { surface, bounds: b, layers: None });
+ let resolution = Some(d.doc.resolution_dpi);
+ s.clipboard = Some(Clip { surface, bounds: b, layers: None, resolution });
Ok(json!({"bounds": [b.x0, b.y0, b.width(), b.height()], "target": "mask"}))
}
@@ -404,6 +409,9 @@ fn new_from_clipboard(s: &mut Session) -> Result<Value> {
let target = PixelFormat::new(fmt.mode, fmt.sample, true);
let moved = if b.x0 == 0 && b.y0 == 0 { clip.surface } else { photocraft_algo::resample::translate_surface(&clip.surface, -b.x0, -b.y0) };
let mut doc = Document::new("Untitled", photocraft_geom::Size::new(w, h), fmt.mode, fmt.sample);
+ if let Some(r) = clip.resolution.filter(|r| r.is_finite() && *r > 0.0) {
+ doc.resolution_dpi = r;
+ }
let mut l = Layer::raster(doc.next_layer_name("Layer"), target);
*crate::pixels_mut(&mut l)? = if moved.format() == target { moved } else { moved.convert(target) };
doc.layers.push(l);
@@ -1007,6 +1015,18 @@ mod tests {
st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds()
}
+ /// New from Clipboard takes the copied document's resolution (Photoshop's Clipboard preset),
+ /// so a later Image Size by resolution scales from the right size.
+ #[test]
+ fn new_from_clipboard_keeps_the_source_resolution() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 60, "height": 40, "resolution": 300})).unwrap();
+ s.execute("select.all", json!({})).unwrap();
+ s.execute("edit.copy", json!({})).unwrap();
+ s.execute("file.newFromClipboard", json!({})).unwrap();
+ assert_eq!(s.active().unwrap().doc.resolution_dpi, 300.0);
+ }
+
/// #368: the clipboard as a document of its own, from New from Clipboard or a Paste with
/// nothing open, at every depth.
#[test]
diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rs
index c4fdebf21..1f3748d7b 100644
--- a/crates/engine/src/extra_cmds.rs
+++ b/crates/engine/src/extra_cmds.rs
@@ -437,11 +437,20 @@ pub fn reveal_all_bounds(doc: &Document) -> Rect {
// ---------- layers ----------
-fn layer_from_background(s: &mut Session) -> Result<Value> {
+fn layer_from_background(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ if d.doc.background().is_none() && p.get("ifPresent").and_then(Value::as_bool) == Some(true) {
+ return Ok(json!({"layer": null}));
+ }
+ // `select: false`: the targeted layer stays targeted, as when a Photoshop action's `set`
+ // names the Background while another layer is selected.
+ let select = p.get("select").and_then(Value::as_bool).unwrap_or(true);
let id = s.edit("Layer From Background", |doc, active| {
let l = doc.background_mut().ok_or(EngineError::Other("the document has no Background layer".into()))?;
unlock_background(l);
- *active = Some(l.id);
+ if select || active.is_none() {
+ *active = Some(l.id);
+ }
Ok(l.id)
})?;
Ok(json!({"layer": id.0}))
@@ -858,7 +867,15 @@ pub fn specs() -> Vec<CommandSpec> {
s.execute("image.crop", json!({"x": all.x0, "y": all.y0, "width": all.width(), "height": all.height(), "deleteCroppedPixels": false}))?;
Ok(json!({"changed": true}))
}),
- spec!("layer.new.layerFromBackground", "Layer From Background…", &["Layer", "New"], None, "{}", has_background, |s, _| layer_from_background(s)),
+ spec!(
+ "layer.new.layerFromBackground",
+ "Layer From Background…",
+ &["Layer", "New"],
+ None,
+ r##"{"ifPresent":bool=false (true: a document without a Background is left as it is, as a Photoshop action's step needs on an image that opened as a normal layer),"select":bool=true (false: the targeted layer stays targeted)}"##,
+ has_background,
+ layer_from_background
+ ),
spec!("layer.layerStyle.copyLayerStyle", "Copy Layer Style", &["Layer", "Layer Style"], None, r##"{"layer":id?}"##, has_layer, |s, p| {
let id = layer_param(s, p)?;
let l = s.active().and_then(|d| d.doc.layer(id)).ok_or(EngineError::NoLayer(id))?;
diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs
index d26d87e51..c56a91277 100644
--- a/crates/engine/src/image_cmds.rs
+++ b/crates/engine/src/image_cmds.rs
@@ -173,6 +173,18 @@ fn image_size(s: &mut Session, p: &Value) -> Result<Value> {
pw = pw.or(Some(ow as f64 * pc / 100.0));
ph = ph.or(Some(oh as f64 * pc / 100.0));
}
+ // `keepPrintSize`: only the resolution given, the pixels follow it (Photoshop's Image Size
+ // with Resample on, as an action records it).
+ if p.get("keepPrintSize").and_then(Value::as_bool) == Some(true)
+ && pw.is_none()
+ && ph.is_none()
+ && let Some(r) = p.get("resolution").and_then(Value::as_f64)
+ {
+ let r = r.clamp(1.0, 10_000.0);
+ let old = f64::from(d.doc.resolution_dpi).max(1.0);
+ pw = Some(ow as f64 * r / old);
+ ph = Some(oh as f64 * r / old);
+ }
// Missing dimension keeps the aspect ratio.
let (nw, nh) = match (pw, ph) {
(Some(w), Some(h)) => (w, h),
@@ -719,7 +731,7 @@ pub fn specs() -> Vec<CommandSpec> {
"image.imageSize",
"Image Size…",
["Image"],
- r##"{"width":px,"height":px,"percent":%? (both sides; an explicit side wins),"resolution":ppi,"resample":"automatic|preserveDetails|bicubicSmoother|bicubicSharper|bicubicAutomatic|bicubic|nearest|bilinear|lanczos|none"="bicubic"} → {width,height} (the document's size after the command; "none" changes the resolution only)"##,
+ r##"{"width":px,"height":px,"percent":%? (both sides; an explicit side wins),"resolution":ppi,"keepPrintSize":bool=false (with only a resolution: resample the pixels to keep the print size),"resample":"automatic|preserveDetails|bicubicSmoother|bicubicSharper|bicubicAutomatic|bicubic|nearest|bilinear|lanczos|none"="bicubic"} → {width,height} (the document's size after the command; "none" changes the resolution only)"##,
has_doc,
image_size
),
@@ -862,6 +874,21 @@ mod tests {
&s.active().unwrap().doc
}
+ /// Resample on with only a new resolution keeps the print size, as Photoshop's Image Size
+ /// does (an action's `imageSize` with `Rslt` alone); without `keepPrintSize` only the
+ /// resolution changes.
+ #[test]
+ fn image_size_keep_print_size_resamples_to_the_resolution() {
+ let mut s = session();
+ s.execute("image.imageSize", json!({"resolution": 144, "resample": "bicubic"})).unwrap();
+ assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(40, 20), 144.0));
+ s.execute("image.imageSize", json!({"resolution": 288, "resample": "bicubic", "keepPrintSize": true})).unwrap();
+ assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(80, 40), 288.0));
+ // An explicit side still wins.
+ s.execute("image.imageSize", json!({"width": 20, "resolution": 72, "resample": "bicubic", "keepPrintSize": true})).unwrap();
+ assert_eq!(doc(&s).size, Size::new(20, 10));
+ }
+
#[test]
fn image_size_scales_everything() {
for resample in ["bicubic", "bicubicSmoother", "bicubicSharper", "bicubicAutomatic", "automatic", "bilinear", "nearest", "lanczos", "preserveDetails"] {
diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs
index b26e46358..e2f666d10 100644
--- a/crates/engine/src/layer_multi_cmds.rs
+++ b/crates/engine/src/layer_multi_cmds.rs
@@ -113,7 +113,7 @@ fn range_order(layers: &[Layer], include_collapsed: bool, out: &mut Vec<LayerId>
}
}
-/// `layer.select`: `{"layer": id, "mode": "replace|toggle|range|add"}`.
+/// `layer.select`: `{"layer": id, "mode": "replace|toggle|range|add|remove"}`.
pub fn select(s: &mut Session, p: &Value) -> Result<Value> {
let id = crate::commands::explicit_layer(s, p)?.ok_or_else(|| bad("layer.select", "missing `layer`"))?;
let mode = p.get("mode").and_then(Value::as_str).unwrap_or("replace");
@@ -144,6 +144,15 @@ pub fn select(s: &mut Session, p: &Value) -> Result<Value> {
set_selection(s, sel, Some(id), Some(id))?;
}
}
+ // Toggle's removing half: a layer that isn't selected stays unselected (Photoshop's
+ // `removeFromSelection`, recorded by actions).
+ "remove" => {
+ if sel.contains(&id) && sel.len() > 1 {
+ sel.retain(|x| *x != id);
+ let active = if st.active_layer == Some(id) { sel.last().copied() } else { st.active_layer };
+ set_selection(s, sel, active, active)?;
+ }
+ }
"range" => {
let anchor = st.layer_anchor.filter(|a| st.doc.layer(*a).is_some()).or(st.active_layer).unwrap_or(id);
let mut order = Vec::new();
@@ -288,8 +297,27 @@ pub fn moves_mask_alone(l: &Layer) -> bool {
/// `layer.translate`: the explicit layer, or every selected layer, plus their linked layers.
/// With `"target":"mask"` a layer whose mask is unlinked moves that mask alone.
pub fn translate(s: &mut Session, p: &Value) -> Result<Value> {
- let dx = int_i32("layer.translate", p, "dx")?.unwrap_or(0);
- let dy = int_i32("layer.translate", p, "dy")?.unwrap_or(0);
+ let (dx, dy) = match p.get("units").and_then(Value::as_str) {
+ None | Some("px") => (int_i32("layer.translate", p, "dx")?.unwrap_or(0), int_i32("layer.translate", p, "dy")?.unwrap_or(0)),
+ // Points (1/72 in), as a Photoshop action records a nudge: whole pixels at this
+ // document's resolution.
+ Some("pt") => {
+ let dpi = s.active().map_or(72.0, |d| f64::from(d.doc.resolution_dpi));
+ let to_px = |key: &str| -> Result<i32> {
+ let pt = match p.get(key) {
+ None => 0.0,
+ Some(v) => v.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad("layer.translate", format!("`{key}` must be a number")))?,
+ };
+ let px = (pt * dpi / 72.0).round();
+ if px.abs() > f64::from(i32::MAX) {
+ return Err(bad("layer.translate", format!("`{key}` = {pt} pt is outside the 32-bit coordinate range")));
+ }
+ Ok(px as i32)
+ };
+ (to_px("dx")?, to_px("dy")?)
+ }
+ Some(other) => return Err(bad("layer.translate", format!("unknown units `{other}` (px|pt)"))),
+ };
if dx == 0 && dy == 0 {
return Ok(Value::Null);
}
@@ -1482,6 +1510,42 @@ mod tests {
s.active().unwrap().last_damage
}
+ /// A Photoshop action's nudge in points moves whole pixels at the document's resolution:
+ /// 0.36 pt is 1 px at 200 ppi and 1.5 → 2 px at 300 ppi.
+ #[test]
+ fn translate_in_points_follows_the_resolution() {
+ for (res, moved) in [(200, 1), (300, 2), (72, 0)] {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 100, "height": 80, "resolution": res})).unwrap();
+ let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20));
+ s.execute("layer.translate", json!({"dx": 0.36, "dy": -0.36, "units": "pt"})).unwrap();
+ assert_eq!(bounds(&s, a), Rect::new(10 + moved, 10 - moved, 20 + moved, 20 - moved), "{res} ppi");
+ }
+ let mut s = session(8);
+ rect_layer(&mut s, Rect::new(10, 10, 20, 20));
+ for bad in [json!({"dx": 1, "units": "in"}), json!({"dx": "x", "units": "pt"}), json!({"dx": 1e300, "units": "pt"})] {
+ assert!(s.execute("layer.translate", bad.clone()).is_err(), "{bad}");
+ }
+ }
+
+ /// `remove` deselects a selected layer, leaves an unselected one alone and never empties the
+ /// selection.
+ #[test]
+ fn select_remove_takes_a_layer_out_of_the_selection() {
+ let mut s = session(8);
+ let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20));
+ let b = rect_layer(&mut s, Rect::new(30, 10, 40, 20));
+ let c = rect_layer(&mut s, Rect::new(50, 10, 60, 20));
+ s.execute("layer.select", json!({"layer": a.0})).unwrap();
+ s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap();
+ s.execute("layer.select", json!({"layer": c.0, "mode": "remove"})).unwrap();
+ assert_eq!(sel(&s).len(), 2, "an unselected layer stays out");
+ s.execute("layer.select", json!({"layer": b.0, "mode": "remove"})).unwrap();
+ assert_eq!(sel(&s), vec![a]);
+ s.execute("layer.select", json!({"layer": a.0, "mode": "remove"})).unwrap();
+ assert_eq!(sel(&s), vec![a], "the last selected layer stays");
+ }
+
/// A mask with its chain off stays put while the layer moves; a linked one moves along.
#[test]
fn translate_leaves_an_unlinked_mask_in_place() {
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index f1bd9bd16..58a897429 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -614,6 +614,10 @@ impl Session {
if self.names_existing_layer(spec.id, params) {
return Ok(());
}
+ // `ifPresent`: with no Background there is nothing to do, which isn't an error.
+ if spec.id == "layer.new.layerFromBackground" && params.get("ifPresent").and_then(Value::as_bool) == Some(true) {
+ return self.active().map(|_| ()).ok_or_else(|| "no document open".into());
+ }
channel_cmds::mask_target_enabled(self, spec.id, params).unwrap_or_else(|| (spec.enabled)(self))
}
diff --git a/crates/engine/src/pattern_cmds.rs b/crates/engine/src/pattern_cmds.rs
index d58fd9e82..0cb9052ce 100644
--- a/crates/engine/src/pattern_cmds.rs
+++ b/crates/engine/src/pattern_cmds.rs
@@ -268,8 +268,12 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
fn import(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "pattern.import";
- let path = p.get("path").and_then(Value::as_str).ok_or_else(|| bad(cmd, "missing `path` (.pat file)"))?;
- let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
+ // A file on disk, or its bytes (a dropped file, the web build).
+ let bytes = match (p.get("path").and_then(Value::as_str), p.get("data").and_then(Value::as_str)) {
+ (Some(path), _) => std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?,
+ (None, Some(b64)) => photocraft_paint::tile::b64_decode(b64).ok_or_else(|| bad(cmd, "`data` is not base64"))?,
+ (None, None) => return Err(bad(cmd, "missing `path` (.pat file) or `data`")),
+ };
let pats = photocraft_io::pattern_map::read_pat(&bytes).map_err(EngineError::Other)?;
let mut ids = Vec::new();
for pat in pats {
@@ -279,7 +283,7 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
None => s.patterns.items.push(pat),
}
}
- Ok(json!({"imported": ids}))
+ Ok(json!({"imported": ids, "count": ids.len()}))
}
fn export(s: &mut Session, p: &Value) -> Result<Value> {
@@ -409,7 +413,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Import Patterns…",
menu: &[],
shortcut: None,
- params: r##"{"path":".pat file"}"##,
+ params: r##"{"path":".pat file"?,"data":base64 bytes? (instead of a path)} → {imported:[ids],count}"##,
enabled: always,
journal: true,
run: import,
@@ -500,8 +504,17 @@ mod tests {
let v = s.execute("pattern.import", json!({"path": path})).unwrap();
assert!(v["imported"].as_array().unwrap().iter().any(|x| x == id.as_str()));
assert_eq!(resolve(&s, &id).unwrap().surface.read_region(Rect::new(0, 0, 5, 4)), pat.surface.read_region(Rect::new(0, 0, 5, 4)));
+ // The same file as bytes (a dropped file, the web build).
+ let bytes = std::fs::read(path).unwrap();
+ s.execute("pattern.delete", json!({"pattern": "Crimson"})).unwrap();
+ let v = s.execute("pattern.import", json!({"data": photocraft_paint::tile::b64_encode(&bytes)})).unwrap();
+ assert_eq!(v["count"], v["imported"].as_array().unwrap().len());
+ assert_eq!(resolve(&s, "Crimson").unwrap().id, id);
std::fs::remove_dir_all(dir).ok();
assert!(s.execute("pattern.import", json!({"path": "/nonexistent.pat"})).is_err());
+ for bad in [json!({}), json!({"data": "not base64!"}), json!({"data": "aGVsbG8="})] {
+ assert!(s.execute("pattern.import", bad.clone()).is_err(), "{bad}");
+ }
}
#[test]
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index ea65085c3..f5046dea0 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -3659,6 +3659,7 @@ curves Smooth Vyhladit
gradients přechody
@plural Imported {n} brush from {file}|Imported {n} brushes from {file} Importován {n} štětec ze souboru {file}|Importovány {n} štětce ze souboru {file}|Importováno {n} štětců ze souboru {file}
@plural Imported {n} gradient from {file}|Imported {n} gradients from {file} Importován {n} přechod ze souboru {file}|Importovány {n} přechody ze souboru {file}|Importováno {n} přechodů ze souboru {file}
+@plural Imported {n} pattern from {file}|Imported {n} patterns from {file} Importován {n} vzorek ze souboru {file}|Importovány {n} vzorky ze souboru {file}|Importováno {n} vzorků ze souboru {file}
Data Set: {name} ({index}/{total}) Datová sada: {name} ({index}/{total})
(none) (žádná)
navigator Zoom Zvětšení
diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv
index 2a0eace59..70617d1c3 100644
--- a/crates/ui-egui/src/i18n/hu.tsv
+++ b/crates/ui-egui/src/i18n/hu.tsv
@@ -31,6 +31,7 @@
@plural Imported {n} brush from {file}|Imported {n} brushes from {file} {n} ecset importálva. Forrás: {file}
@plural Imported {n} brush from {group}|Imported {n} brushes from {group} {n} ecset importálva. Csoport: {group}
@plural Imported {n} gradient from {file}|Imported {n} gradients from {file} {n} színátmenet importálva. Forrás: {file}
+@plural Imported {n} pattern from {file}|Imported {n} patterns from {file} {n} mintázat importálva. Forrás: {file}
@plural Imported {n} swatch from {file}|Imported {n} swatches from {file} {n} színminta importálva. Forrás: {file}
@plural Played {n} step|Played {n} steps {n} lépés lejátszva
@plural Saved for Web: {n} file|Saved for Web: {n} files Mentés webre: {n} fájl
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 9f10a8fc3..ec937b1ca 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -4036,6 +4036,7 @@ layerLabel No Color Nessun colore
gradients sfumature
@plural Imported {n} brush from {file}|Imported {n} brushes from {file} {n} pennello importato da {file}|{n} pennelli importati da {file}
@plural Imported {n} gradient from {file}|Imported {n} gradients from {file} {n} sfumatura importata da {file}|{n} sfumature importate da {file}
+@plural Imported {n} pattern from {file}|Imported {n} patterns from {file} {n} pattern importato da {file}|{n} pattern importati da {file}
Data Set: {name} ({index}/{total}) Set di dati: {name} ({index}/{total})
(none) (nessuno)
navigator Zoom Zoom
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 7cda48e82..83e24a229 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -2351,7 +2351,7 @@ impl PhotocraftApp {
let r = photocraft_geom::Rect::new(0, 0, w as i32, h as i32);
let mut surface = photocraft_raster::Surface::from_interleaved(photocraft_color::PixelFormat::RGBA8, r, &bytes);
surface.prune();
- self.session.clipboard = Some(photocraft_engine::edit_cmds::Clip { surface, bounds: r, layers: None });
+ self.session.clipboard = Some(photocraft_engine::edit_cmds::Clip { surface, bounds: r, layers: None, resolution: None });
self.os_clip_sig = Some(sig);
self.clip_external = true;
true
diff --git a/crates/ui-egui/src/preset_files_ui.rs b/crates/ui-egui/src/preset_files_ui.rs
index 26a84bd85..6138c0884 100644
--- a/crates/ui-egui/src/preset_files_ui.rs
+++ b/crates/ui-egui/src/preset_files_ui.rs
@@ -2,7 +2,8 @@
//! Import Brushes…, the Preset Manager's Load…): Photoshop brushes (`.abr`) go to the brush
//! library through `brush.presets.importAbr`, gradients (`.grd`) to the Gradients panel through
//! `gradient.presets.importGrd`, swatches (`.aco`, `.ase`) to the Swatches panel through
-//! `swatches.import`, keyboard shortcut sets (`.kys`) to Edit › Keyboard Shortcuts through
+//! `swatches.import`, patterns (`.pat`) to the Patterns panel through `pattern.import`, keyboard
+//! shortcut sets (`.kys`) to Edit › Keyboard Shortcuts through
//! [`crate::kys_import`], instead of opening as documents.
use serde_json::{Value, json};
@@ -13,7 +14,7 @@ use crate::PhotocraftApp;
/// the Swatches panel through [`crate::swatches_ui::import_bytes`]).
/// `.psp` is Photoshop's live `Keyboard Shortcuts.psp` (the same XML as a `.kys`); other `.psp`
/// settings files are refused with a clear message.
-pub const PRESET_EXTS: &[&str] = &["abr", "grd", "aco", "ase", "kys", "psp"];
+pub const PRESET_EXTS: &[&str] = &["abr", "grd", "pat", "aco", "ase", "kys", "psp"];
fn ext(name: &str) -> String {
std::path::Path::new(name).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default()
@@ -56,6 +57,7 @@ pub fn open(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Option<Result<
let (cmd, what) = match ext(name).as_str() {
"abr" => ("brush.presets.importAbr", "brushes"),
"grd" => ("gradient.presets.importGrd", "gradients"),
+ "pat" => ("pattern.import", "patterns"),
"aco" | "ase" => return Some(crate::swatches_ui::import_bytes(app, name, bytes, false).map(|_| ())),
"kys" | "psp" => return Some(crate::kys_import::open_bytes(app, name, bytes).map(|_| ())),
_ => return None,
@@ -77,10 +79,10 @@ pub fn open(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Option<Result<
let n = r.get("count").and_then(Value::as_u64).unwrap_or(0);
let warnings: Vec<String> = r.get("warnings").and_then(|w| serde_json::from_value(w.clone()).ok()).unwrap_or_default();
app.ui.status_error = false;
- let (one, other) = if what == "brushes" {
- ("Imported {n} brush from {file}", "Imported {n} brushes from {file}")
- } else {
- ("Imported {n} gradient from {file}", "Imported {n} gradients from {file}")
+ let (one, other) = match what {
+ "brushes" => ("Imported {n} brush from {file}", "Imported {n} brushes from {file}"),
+ "patterns" => ("Imported {n} pattern from {file}", "Imported {n} patterns from {file}"),
+ _ => ("Imported {n} gradient from {file}", "Imported {n} gradients from {file}"),
};
let imported = crate::i18n::fmt(&crate::i18n::trn(crate::i18n::current(), n, one, other), &[("file", &stem)]);
app.ui.status = match warnings.first() {
@@ -108,6 +110,7 @@ mod tests {
assert!(is_preset_file("sunsets.grd"));
assert!(is_preset_file("Brand.ACO"));
assert!(is_preset_file("exchange.ase"));
+ assert!(is_preset_file("Debaser-ColourLibrary-Part6.PAT"));
assert!(!is_preset_file("photo.psd"));
assert!(!is_preset_file("abr"));
}
diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md
index 4cb21759e..daa8827c3 100644
--- a/docs/file-format-parity.md
+++ b/docs/file-format-parity.md
@@ -1,6 +1,6 @@
# File-format parity
-> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026
+> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (`.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026
Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity and
tests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write
@@ -131,7 +131,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.
| LUTs `.cube` / `.3dl` / `.look` | R/W (Export Color Lookup) | R/W / R / R | `cms/src/lutfile.rs` |
| Keyboard shortcuts `.kys` | R/W | R | `engine/src/kys.rs` |
| ICC profiles | R | R | Own CMS |
-| Actions `.atn` | R/W | R/W | `psd/src/atn.rs` (version 16 sets, exact round trip), `engine/src/atn_cmds.rs` (108 Photoshop events ↔ commands; other steps kept verbatim). Panel menu, CLI `batch --actions set.atn`, `actions.load`/`actions.save`. Photoshop 5-era version 12 files unsupported (AUTO-219-2) |
+| Actions `.atn` | R/W | R/W | `psd/src/atn.rs` (version 16 sets, exact round trip), `engine/src/atn_cmds.rs` (112 Photoshop events ↔ commands; other steps kept verbatim). Panel menu, CLI `batch --actions set.atn`, `actions.load`/`actions.save`. Photoshop 5-era version 12 files unsupported (AUTO-219-2) |
| Styles `.asl` | R/W | no | #1693 |
| Contours `.shc` | R/W | R/W | `psd/src/shc.rs`; Contour Editor Load…/Save… (FILE-215-15). No user contour library; not yet checked against a Photoshop-written file |
| Custom shapes `.csh`, tool presets `.tpl` | R/W | no | |
@@ -142,6 +142,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.
| Date | Change | Summary |
|---|---|---|
+| 2026-10-12 | minor | `.atn`: 112 events mapped (Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, points, Bitmap) |
| 2026-10-12 | minor | DDS textures open, read-only (#1327) |
| 2026-10-12 | minor | #2465 fixed: Photoshop CS2 placed layers (`PlLd` only, file in `lnkD`) open as editable smart objects and save their edits |
| 2026-10-12 | minor | DPX read and write (#1049); Cineon still missing |
diff --git a/docs/gaps.md b/docs/gaps.md
index 4b8d7283f..71169ab22 100644
--- a/docs/gaps.md
+++ b/docs/gaps.md
@@ -1,6 +1,6 @@
# Where PhotoCraft falls short of Photoshop
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026
+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026
Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact
on the way to beta. This is the work list agents pick from: take the highest-ranked entry that
@@ -90,14 +90,24 @@ what an agent can't finish alone.
### G11. Actions and scripting
- **Missing:** document-independent action recording (AUTO-219-1), Batch recursion and naming
(AUTO-219-5), ExtendScript/UXP compatibility. `.atn` steps outside the
- mapped events (paths, scripts, Generative Fill, offsets in points…) load as kept Photoshop
- steps that fail at playback by name.
+ mapped events (paths, scripts, Generative Fill, Filter Gallery effects other than Spatter,
+ Duplicate Layers into a new document, Bitmap halftone screens…) load as kept Photoshop steps
+ that fail at playback by name.
- **Done 2026-10-12:** Load/Save Actions `.atn` in the panel menu, `batch --actions set.atn`
- and `actions.load`/`actions.save`; 108 Photoshop events map to commands both ways (Transform,
+ and `actions.load`/`actions.save`; 112 Photoshop events map to commands both ways (Transform,
Apply Image, Save for Web, smart-object edits, Gradient Map, Quick Mask, polygon selections,
Place, Open, Image Size in percent, the Paint Bucket and Insert Conditional since the third
- and fourth PRs), Play, Stop and conditional steps included; layer steps replay by layer name in any
- document. The panel groups actions
+ and fourth PRs; Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill
+ layers, targeting the layer mask or composite channel, loading the targeted channel, Step
+ Backward/Forward, removing a layer from the selection, nudges in points, Layer From Background,
+ Grayscale and Bitmap mode objects and Image Size with Resample keeping the print size since the
+ fifth), Play, Stop and conditional steps included; layer steps replay by layer name in any
+ document. Four TrueGrit Texture Supply sets (Debaser, Distress Press, Halftone Zine Machine,
+ Transparency) import with 3 of 533 steps unmapped and play end to end. Filter Gallery Spatter's Smoothness
+ now smooths the spray's displacement, so high values tear an edge without detaching specks, as
+ Photoshop's does (calibrated by eye on the Distress Press guide's screenshots). Crystallize
+ fills each cell with the colour at its point instead of the cell's average, so a black-and-white
+ mask keeps hard edges (not yet checked against a Photoshop render). The panel groups actions
in set folders, has the dialog toggle column (playback pauses on the step's dialog and resumes
on OK) and Insert Stop…; `actions.insert`, `actions.dialog`, `actions.assignSet` for agents
(AUTO-219-2 done).
@@ -243,6 +253,7 @@ what an agent can't finish alone.
| Date | Change | Summary |
|---|---|---|
| 2026-10-12 | minor | G5: Free Transform options bar H/V skew fields done |
+| 2026-10-12 | minor | G11: `.atn` import maps 112 events (Select and Mask, Spatter, Ripple, Crystallize, Pattern Fill, mask targeting, Step Backward, points, Bitmap) |
| 2026-10-12 | minor | G9: toolbar tool shortcut editing (#4086); the remaining workspace gaps stay open |
| 2026-10-12 | minor | G1: #2465 (CS2 `PlLd`-only smart objects) marked fixed |
| 2026-10-12 | minor | G5: spring-loaded tool letters done (#2672) |
diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md
index 7fbd5bdc9..f6209c58d 100644
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@ -1,6 +1,6 @@
# PhotoCraft vs Adobe Photoshop: target-app parity
-> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment) · **Target:** Adobe Photoshop 2026
+> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (`.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment) · **Target:** Adobe Photoshop 2026
The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". The
one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md);
@@ -66,7 +66,7 @@ architecture and the PSD writer are the serial parts.
| Filters and adjustments | 10% | every Filter and Image › Adjustments item live; Filter Gallery 47 looks | 100% | measured (menu catalog) |
| File formats (usage-weighted) | 15% | 13 of 31 Photoshop formats supported in Photoshop's directions, 4 partial; the common ones (PSD/PSB, TIFF, JPEG, PNG, WebP) all present | ~80% (48% by count) | measured list, estimated weights ([file-format-parity.md](file-format-parity.md)) |
| AI / generative | 10% | classical Select Subject/Sky, Remove tool, Content-Aware; no Generative Fill/Expand, Neural Filters, Sky Replacement, Super Zoom | ~15% | estimated |
-| Ecosystem (plug-ins, scripting, libraries) | 10% | WebAssembly plug-ins, CLI, MCP, actions, `.atn` load/save (108 events); no .8BF, UXP/ExtendScript, Libraries | ~20% | estimated |
+| Ecosystem (plug-ins, scripting, libraries) | 10% | WebAssembly plug-ins, CLI, MCP, actions, `.atn` load/save (112 events); no .8BF, UXP/ExtendScript, Libraries | ~20% | estimated |
| **Weighted** | 100% | | **~76%** | |
## Ready for real work: ~45% (weighted)
@@ -83,7 +83,7 @@ Weights reflect what a working Photoshop user depends on (photographers, retouch
| Hardware | 5% | 50% | 80–150 | GPU compositor (wgpu), pen pressure on all desktops but tilt/rotation not on Windows, Wayland pen broken (#2622), no HDR/EDR output, monitor profile auto-detected on macOS only | [hardware-parity.md](hardware-parity.md) |
| Localization | 5% | 55% | 80–140 | 7 of the 12 key languages at 100% of measured UI keys; Hindi and Arabic absent, Vietnamese catalog added 2026-10-12 (#2636, coverage not re-measured); no RTL UI; engine messages English | [localization-parity.md](localization-parity.md) |
| Platforms | 5% | 80% | 30–60 | macOS (notarized), Windows (unsigned), Linux (AppImage/deb/rpm/Flatpak), web, FreeBSD partial; Windows ARM64 is packaged and install-checked by `.github/workflows/windows-arm64.yml` (DIST-220-2); no in-app updates | [scorecard.md](scorecard.md#distribution) |
-| Ecosystem (plug-ins, scripting, presets, libraries) | 5% | 15% | 250–450 | No .8BF hosting (#2647), no UXP/ExtendScript; .atn load/save (2026-10-12, 108 events, the rest kept verbatim), .abr/.grd/.pat/.aco/.ase/.cube supported | [gaps.md](gaps.md) |
+| Ecosystem (plug-ins, scripting, presets, libraries) | 5% | 15% | 250–450 | No .8BF hosting (#2647), no UXP/ExtendScript; .atn load/save (2026-10-12, 112 events, the rest kept verbatim), .abr/.grd/.pat/.aco/.ase/.cube supported | [gaps.md](gaps.md) |
| AI features | 5% | 10% | 300–600 | No ML runtime at all (scorecard AUTO-219-7); classical substitutes only. Needs an owner decision and openly licensed models (#41) | [gaps.md](gaps.md) |
| **Weighted** | 100% | **~46%** | **2,340–4,100** | | |
@@ -177,7 +177,7 @@ parity for the area and are already contained in the dimension rows above.
| Vector shapes and paths | 55% | 80–140 | Pen, Direct/Path Selection, shapes, shape strokes. Freeform and Curvature Pen (#1054). Add/Delete Anchor Point and Convert Point tools exist (`Tool` enum); missing on-canvas corner radius (TOOL-214-12), path-point nudge; shape parity tracking issue #2496 |
| Colour management and modes | 70% | 60–100 | Own ICC engine, soft proof, CMYK/Lab/Indexed/Duotone/Multichannel; no Adobe CMYK profiles, no spot plates (FILE-215-17), monitor profile only at launch |
| Camera Raw and computational photo (Photomerge, HDR, lens) | 45% | 120–200 | Raw for DNG/CR2/NEF/ARW/RW2/ORF/RAF(uncompressed)/PEF; no CR3; ACR dialog partial (no masking, calibration); generic lens profiles only |
-| Automation, actions, batch, scripting | 45% | 120–200 | CLI/MCP/control channel ahead of Photoshop; Actions panel and recording not document-independent (AUTO-219-1/2); `.atn` load/save since 2026-10-12 (108 events mapped, the rest kept verbatim); no ExtendScript/UXP |
+| Automation, actions, batch, scripting | 45% | 120–200 | CLI/MCP/control channel ahead of Photoshop; Actions panel and recording not document-independent (AUTO-219-1/2); `.atn` load/save since 2026-10-12 (112 events mapped, the rest kept verbatim); no ExtendScript/UXP |
| File I/O | 60% | 300–500 | See [file-format-parity.md](file-format-parity.md) |
| Print, export, Save for Web | 50% | 60–100 | JPEG Options dialog missing (FILE-215-19), no Photoshop PDF, no separations, Save for Web settings not remembered |
| Video / timeline, data-driven graphics | 30% | 100–200 | Menu items live; frame model persists in `.pcraft`; no PSD video-layer mapping |
@@ -564,6 +564,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md).
| Date | Change | Summary |
|---|---|---|
| 2026-10-12 | minor | Free Transform options bar H/V skew fields; percentages unchanged |
+| 2026-10-12 | minor | `.atn` import: 112 events mapped (TrueGrit Texture Supply sets play end to end); percentages unchanged |
| 2026-10-12 | minor | Photoshop Actions `.atn` load and save (90 events mapped both ways); percentages unchanged |
| 2026-10-12 | minor | Rows checked against `main` and the regenerated scorecard: menu count 631, Workspace checklist and preference count, transform context menu, Puppet Warp mesh, Select and Mask, anchor-point tools, Smart Object conversion, Stamp Visible, mask targeting, Free Transform commit/cancel, Vietnamese catalog, Windows ARM64; percentages, weights and hours not re-measured |
| 2026-10-10 | minor | Added measured Tilt-Shift computation/filtered-proxy gains and inconclusive cases; parity percentages and budgets unchanged |