Preserve recorded ATN settings across load and save

This commit is contained in:
yoriswind committed 2026-11-01 05:58:42 -08:00
1 parent 84732d09bc
commit 04cf63f68c
13 files changed
+523 -50

No files matched your search

+22 -5
View File
@@ -305,11 +305,28 @@ fn build() -> Vec<CommandSpec> {
Ok(json!({ "document": i }))
}
),
cmd!("file.close", "Close", ["File"], Some("Cmd+W"), r##"{"document":index?}"##, has_doc, |s, p| {
let i = p.get("document").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?;
s.close(i).ok_or(EngineError::NoDocument)?;
Ok(Value::Null)
}),
cmd!(
"file.close",
"Close",
["File"],
Some("Cmd+W"),
r##"{"document":index?,"save":"discard|ask"="discard"} (ask refuses to close a changed document in headless playback)"##,
has_doc,
|s, p| {
let i = p.get("document").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?;
match p.get("save").filter(|v| !v.is_null()) {
Some(v) if v == "ask" => {
if s.documents().get(i).ok_or(EngineError::NoDocument)?.is_dirty() {
return Err(bad("file.close", "the document has unsaved changes; save it or explicitly discard them"));
}
}
Some(v) if v != "discard" => return Err(bad("file.close", "`save` must be ask or discard")),
_ => {}
}
s.close(i).ok_or(EngineError::NoDocument)?;
Ok(Value::Null)
}
),
// Edit
cmd!("edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{}", can_undo, |s, _| Ok(json!(s.undo()))),
cmd!("edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, |s, _| Ok(json!(s.redo()))),
+13 -2
View File
@@ -1,4 +1,6 @@
use super::descriptors::{color_desc, color_hex, desc, enm, get_bool, get_enum, get_list, get_num, get_obj, jbool, jnum, jstr, long, num, pct, text};
use super::descriptors::{
color_desc, color_hex, desc, enm, get_bool, get_enum, get_list, get_num, get_obj, jbool, jnum, jstr, lab_color_hex, long, num, pct, text,
};
use super::fields::{F, Kind, Mapped, fields_from, fields_to, step};
use super::tables::{CHANNELS, channel_key, channel_ref, lookup, lookup_back};
use super::{D, Descriptor, Map, Value, json};
@@ -406,7 +408,7 @@ const ADJUSTMENTS: &[Adjustment] = &[
Adjustment { class: "ClrB", suffix: "colorBalance", from: color_balance_from, to: color_balance_to },
adj_fields!("Vbrn", "vibrance", &[F("vibrance", "vibrance", Kind::Long), F("Strt", "saturation", Kind::Long)]),
adj_fields!("Exps", "exposure", &[F("Exps", "exposure", Kind::Dbl), F("Ofst", "offset", Kind::Dbl), F("gammaCorrection", "gamma", Kind::Dbl)]),
Adjustment { class: "PhtF", suffix: "photoFilter", from: |d| fields_from(d, PHOTO_FILTER_FIELDS).map(Value::Object), to: photo_filter_to },
Adjustment { class: "PhtF", suffix: "photoFilter", from: photo_filter_from, to: photo_filter_to },
adj_fields!("BanW", "blackWhite", BW),
Adjustment { class: "ChnM", suffix: "channelMixer", from: channel_mixer_from, to: channel_mixer_to },
Adjustment { class: "SlcC", suffix: "selectiveColor", from: selective_from, to: selective_to },
@@ -428,6 +430,15 @@ pub(super) fn adjustment_by_class(c: &str) -> Option<&'static Adjustment> {
const PHOTO_FILTER_FIELDS: &[F] = &[F("Clr ", "color", Kind::Color), F("Dnst", "density", Kind::Long), F("PrsL", "preserveLuminosity", Kind::Bool)];
/// Photo Filter records its default colour in Lab; other colour events retain their mappings.
fn photo_filter_from(d: &Descriptor) -> Option<Value> {
let mut p = fields_from(d, &PHOTO_FILTER_FIELDS[1..])?;
if let Some(c) = get_obj(d, "Clr ") {
p.insert("color".into(), color_hex(c).or_else(|| lab_color_hex(c))?.into());
}
Some(Value::Object(p))
}
/// A `PhtF` step whose params carry a `filter` preset without an explicit `color`: the descriptor
/// form is colour-only (Photoshop stores no preset key — the `phfl` notes in `crates/io` conclude
/// the same from its CS2 oracles), so the resolved colour must be written, or re-imported playback
+18 -1
View File
@@ -109,7 +109,7 @@ pub(super) fn layer_target(r: &[ReferenceItem]) -> Option<Map<String, Value>> {
m.insert("layer".into(), json!(n));
}
Target::Property(p) if p == "Bckg" => {
m.insert("layer".into(), json!("Background"));
m.insert("layer".into(), json!({"background": true}));
}
_ => return None,
}
@@ -177,6 +177,7 @@ pub(super) fn layer_ref(p: &Value) -> Option<D> {
match p.get("layer") {
None | Some(Value::Null) => Some(target_ref("Lyr ")),
Some(Value::String(n)) => Some(name_ref("Lyr ", n)),
Some(v) if *v == json!({"background": true}) => Some(D::Reference(vec![ReferenceItem::Property { class: class("Lyr "), key: code("Bckg") }])),
_ => None,
}
}
@@ -201,6 +202,22 @@ pub(super) fn jstr<'a>(p: &'a Value, k: &str) -> Option<&'a str> {
// ------------------------------------------------------------------ colours and enums
/// A recorded D50 Lab colour converted through the CMS to sRGB `#rrggbb`.
pub(super) fn lab_color_hex(c: &Descriptor) -> Option<String> {
use photocraft_cms::{Builtin, TransformOptions};
if !c.class_id.is("LbCl") {
return None;
}
let (l, a, b) = (get_num(c, "Lmnc")?, get_num(c, "A ")?, get_num(c, "B ")?);
let transform = photocraft_cms::cached(Builtin::LabD50.profile(), Builtin::Srgb.profile(), TransformOptions { bpc: false, ..Default::default() }).ok()?;
// ICC v4 Lab device values are normalized, unlike the recorded L*, a*, b*.
let input = [(l / 100.0) as f32, ((a + 128.0) / 255.0) as f32, ((b + 128.0) / 255.0) as f32];
let mut rgb = [0.0; 3];
transform.convert_f32(&input, 3, &mut rgb, 3, false);
let [r, g, b] = rgb.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
Some(format!("#{r:02x}{g:02x}{b:02x}"))
}
/// A Photoshop colour object as `#rrggbb`: `RGBC` (0..255), `HSBC`, `Grsc`.
pub(super) fn color_hex(c: &Descriptor) -> Option<String> {
let hex = |r: f64, g: f64, b: f64| {
+8 -1
View File
@@ -473,7 +473,14 @@ pub(super) const EVENTS: &[Event] = &[
ev!("", "placedLayerEditContents", "Edit Contents", "layer.smartObjects.editContents", &[]),
ev!("", "updatePlacedLayer", "Update Smart Objects", "layer.smartObjects.updateModifiedContent", &[]),
Event { code: "Hd ", name: "hide", label: "Hide", ids: &["layer.hideLayers"], from: |d| visibility_from(d, "layer.hideLayers"), to: visibility_to },
Event { code: "Shw ", name: "show", label: "Show", ids: &["layer.showLayers"], from: |d| visibility_from(d, "layer.showLayers"), to: visibility_to },
Event {
code: "Shw ",
name: "show",
label: "Show",
ids: &["layer.showLayers", "layer.showOnly"],
from: |d| visibility_from(d, "layer.showLayers"),
to: visibility_to,
},
Event {
code: "move",
name: "move",
+12 -3
View File
@@ -113,9 +113,14 @@ pub(super) fn conditional_to(_: &str, p: &Value) -> Option<Descriptor> {
Some(d)
}
/// `close`: Photoshop's Save prompt answer becomes a Save step before the Close.
/// Import Close's save policy: absent asks, Yes saves first, and No explicitly discards.
pub(super) fn close_from(d: &Descriptor) -> Mapped {
if get_enum(d, "Svng").as_deref() == Some("Ys") { steps(vec![("file.save", json!({})), ("file.close", json!({}))]) } else { none("file.close") }
match d.get("Svng") {
None => step("file.close", json!({"save": "ask"})),
Some(D::Enumerated { value, .. }) if value.is("Ys ") => steps(vec![("file.save", json!({})), ("file.close", json!({}))]),
Some(D::Enumerated { value, .. }) if value.is("N ") => none("file.close"),
_ => Mapped::Unsupported { harmless: false },
}
}
/// A Close of an explicit document has no mapping here: written as a plain Close it would
@@ -124,7 +129,11 @@ pub(super) fn close_to(_: &str, p: &Value) -> Option<Descriptor> {
if p.get("document").is_some_and(|d| !d.is_null()) {
return None;
}
Some(desc("null").with("Svng", enm("YsN ", "N ")))
match p.get("save").filter(|v| !v.is_null()) {
Some(v) if v == "ask" => Some(desc("null")),
Some(v) if v != "discard" => None,
_ => Some(desc("null").with("Svng", enm("YsN ", "N "))),
}
}
const WEB_FORMATS: &[(&str, &str)] = &[("PN24", "png24"), ("PN8", "png8"), ("JPEG", "jpeg"), ("GIFf", "gif"), ("WBMP", "wbmp")];
+29 -6
View File
@@ -7,6 +7,20 @@ use super::fields::{F, Kind, Mapped, fields_from, fields_to, step};
use super::tables::{CHANNELS, INTERPOLATION, RADIAL_METHOD, RADIAL_QUALITY, channel_of, lookup, lookup_back};
use super::{D, Descriptor, Map, ReferenceItem, UnicodeString, Value, json};
/// Photoshop's nine frame anchors and the average/centre anchor.
const TRANSFORM_REFERENCE: &[(&str, &str)] = &[
("Qcsa", "center"),
("Qcs0", "topLeft"),
("Qcs1", "top"),
("Qcs2", "topRight"),
("Qcs3", "left"),
("Qcs4", "center"),
("Qcs5", "right"),
("Qcs6", "bottomLeft"),
("Qcs7", "bottom"),
("Qcs8", "bottomRight"),
];
/// `transform`: Photoshop records a Free Transform relative to the frame (offset of its centre,
/// width/height in percent, angle). A layer moved only becomes `layer.translate`; anything
/// else is `edit.transform`'s relative form; the selection's frame is `select.transformSelection`.
@@ -40,6 +54,13 @@ pub(super) fn transform_from(d: &Descriptor) -> Mapped {
// to keep its sub-pixel placement and interpolation.
let whole_pixels = ["dx", "dy"].iter().all(|k| p.get(*k).and_then(Value::as_f64).is_none_or(|v| v.fract() == 0.0));
let geometry_only = p.keys().all(|k| k == "dx" || k == "dy") && whole_pixels;
if let Some(value) = d.get("FTcs") {
let D::Enumerated { type_id, value } = value else { return unsupported };
let Some(reference) = lookup(TRANSFORM_REFERENCE, &trimmed(value)).filter(|_| type_id.is("QCSt")) else { return unsupported };
if reference != "center" && !geometry_only {
p.insert("reference".into(), reference.into());
}
}
// The resampling applies to a selection as much as to a layer (#7515).
// Photoshop's bicubic variants are kept (the transforms render them as Bicubic, and they export
// back unchanged); Automatic and Preserve Details become the nearest bicubic choice. Dropping
@@ -74,17 +95,15 @@ pub(super) fn transform_from(d: &Descriptor) -> Mapped {
}
}
/// Export relative transforms with frame anchors, refusing unsupported geometry and targets.
pub(super) fn transform_to(id: &str, p: &Value) -> Option<Descriptor> {
let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null());
if ["quad", "corners", "matrix", "rect"].iter().any(|k| given(k)) {
return None;
}
// The descriptor scales and rotates about the centre (`FTcs` average) without skew or warp:
// another reference point, a skew or a warp would replay as a different transform (#7516,
// #7517, #7518, #7519).
// Skew and warp still have no descriptor mapping (#7517, #7518, #7519).
let nonzero = |k: &str| p.get(k).is_some_and(|v| !v.is_null() && v.as_f64() != Some(0.0));
let off_centre = p.get("reference").is_some_and(|v| !v.is_null() && *v != json!("center"));
if nonzero("skewX") || nonzero("skewY") || off_centre || ["warp", "style", "mesh", "grid"].iter().any(|k| given(k)) {
if nonzero("skewX") || nonzero("skewY") || ["warp", "style", "mesh", "grid"].iter().any(|k| given(k)) {
return None;
}
let target = match id {
@@ -95,7 +114,11 @@ pub(super) fn transform_to(id: &str, p: &Value) -> Option<Descriptor> {
"select.transformSelection" => D::Reference(vec![ReferenceItem::Property { class: class("Chnl"), key: code("fsel") }]),
_ => return None,
};
let mut d = desc("null").with("null", target).with("FTcs", enm("QCSt", "Qcsa"));
let reference = match p.get("reference").filter(|v| !v.is_null()) {
Some(v) => lookup_back(TRANSFORM_REFERENCE, v.as_str()?)?,
None => "Qcsa",
};
let mut d = desc("null").with("null", target).with("FTcs", enm("QCSt", reference));
d = d.with("Ofst", D::Descriptor(desc("Ofst").with("Hrzn", px(jnum(p, "dx").unwrap_or(0.0))).with("Vrtc", px(jnum(p, "dy").unwrap_or(0.0)))));
for (key, param) in [("Wdth", "scaleX"), ("Hght", "scaleY")] {
if let Some(v) = jnum(p, param) {
+30 -8
View File
@@ -9,11 +9,13 @@ use super::steps_make::is_tool_class;
use super::tables::{FILL_CONTENTS, INTERPOLATION, MENU_ITEMS, STROKE_LOCATION, blend_label, blend_ps, lookup, lookup_back};
use super::{D, Descriptor, Id, Map, ReferenceItem, UnicodeString, Value, json};
/// Resolve a recorded selection while retaining layer names, Background properties and modifiers.
pub(super) fn select_from(d: &Descriptor) -> Mapped {
let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } };
match (ref_class(r).as_deref(), target(r)) {
(Some("Lyr"), Target::Name(n)) => {
let mut p = json!({"layer": n});
(Some("Lyr"), Target::Name(_) | Target::Property(_)) => {
let Some(p) = layer_target(r) else { return Mapped::Unsupported { harmless: false } };
let mut p = Value::Object(p);
match get_enum(d, "selectionModifier").as_deref() {
Some("addToSelection") => p["mode"] = json!("add"),
Some("removeFromSelection") => p["mode"] = json!("remove"),
@@ -60,6 +62,7 @@ pub(super) fn select_from(d: &Descriptor) -> Mapped {
}
}
/// Write the supported layer, channel, document and history selection references.
pub(super) 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) }]);
@@ -68,8 +71,12 @@ pub(super) fn select_to(id: &str, p: &Value) -> Option<Descriptor> {
if p.get("occurrence").is_some() {
return None;
}
let name = jstr(p, "name").or_else(|| jstr(p, "layer"))?;
let mut d = desc("null").with("null", name_ref("Lyr ", name));
let reference = match jstr(p, "name") {
Some(name) => name_ref("Lyr ", name),
None if p.get("layer").is_some_and(|v| !v.is_null()) => layer_ref(p)?,
None => return None,
};
let mut d = desc("null").with("null", reference);
match jstr(p, "mode") {
None | Some("replace") => {}
Some("add") => d = d.with("selectionModifier", enm("selectionModifierType", "addToSelection")),
@@ -172,13 +179,23 @@ pub(super) fn delete_to(id: &str, p: &Value) -> Option<Descriptor> {
})
}
/// `hide` / `show` take a list of references (or one).
/// Import visibility references; a single Show with TglO is the reversible Show Only command.
pub(super) fn visibility_from(d: &Descriptor, id: &str) -> Mapped {
let refs: Vec<&[ReferenceItem]> = match d.get("null") {
Some(D::List(l)) => l.iter().filter_map(|v| if let D::Reference(r) = v { Some(r.as_slice()) } else { None }).collect(),
Some(D::List(l)) => {
let Some(refs) = l.iter().map(|v| if let D::Reference(r) = v { Some(r.as_slice()) } else { None }).collect() else {
return Mapped::Unsupported { harmless: false };
};
refs
}
Some(D::Reference(r)) => vec![r.as_slice()],
_ => return Mapped::Unsupported { harmless: false },
};
let id = match d.get("TglO") {
Some(D::Boolean(true)) if id == "layer.showLayers" && refs.len() == 1 => "layer.showOnly",
Some(D::Boolean(false)) | None => id,
_ => return Mapped::Unsupported { harmless: false },
};
let mut v = Vec::new();
for r in refs {
match layer_target(r) {
@@ -189,8 +206,13 @@ pub(super) fn visibility_from(d: &Descriptor, id: &str) -> Mapped {
if v.is_empty() { Mapped::Unsupported { harmless: false } } else { steps(v) }
}
pub(super) fn visibility_to(_: &str, p: &Value) -> Option<Descriptor> {
Some(desc("null").with("null", D::List(vec![layer_ref(p)?])))
/// Write the layer reference and preserve Show Only's toggle flag.
pub(super) fn visibility_to(id: &str, p: &Value) -> Option<Descriptor> {
let mut d = desc("null").with("null", D::List(vec![layer_ref(p)?]));
if id == "layer.showOnly" {
d = d.with("TglO", D::Boolean(true));
}
Some(d)
}
pub(super) fn move_from(d: &Descriptor) -> Mapped {
+69 -9
View File
@@ -92,13 +92,29 @@ fn mask_from_descriptor(d: &Descriptor) -> Option<Mapped> {
})
}
/// Import New Document and selection-based Copy/Cut, retaining the new layer's options.
fn new_document_from_descriptor(d: &Descriptor) -> Option<Mapped> {
let nw = get_obj(d, "Nw ")?;
if get_enum(d, "Usng").as_deref() == Some("Slct") {
let id = if get_bool(d, "Cpy ") == Some(true) { "layer.new.layerViaCopy" } else { "layer.new.layerViaCut" };
let mut mapped_steps = vec![(id, json!({}))];
let mut props = Map::new();
if let Some(n) = get_text(nw, "Nm ") {
mapped_steps.push(("layer.setProps", json!({"name": n})));
props.insert("name".into(), n.into());
}
if let Some(o) = get_num(nw, "Opct") {
props.insert("opacity".into(), (o / 100.0).into());
}
if let Some(m) = get_enum(nw, "Md ") {
let Some(mode) = blend_label(&m) else { return Some(Mapped::Unsupported { harmless: false }) };
props.insert("blend".into(), mode.into());
}
if let Some(c) = get_enum(nw, "Clr ") {
let Some(color) = lookup(LABEL_COLORS, &c) else { return Some(Mapped::Unsupported { harmless: false }) };
mapped_steps.push(("layer.setLabelColor", json!({"color": color})));
}
if !props.is_empty() {
mapped_steps.push(("layer.setProps", Value::Object(props)));
}
return Some(steps(mapped_steps));
}
@@ -139,6 +155,7 @@ fn new_document_from_descriptor(d: &Descriptor) -> Option<Mapped> {
/// New Snapshot's From: the full document, the layers merged, or the current layer.
const SNAPSHOT_FROM: &[(&str, &str)] = &[("FllD", "fullDocument"), ("MrgL", "mergedLayers"), ("CrnL", "currentLayer")];
/// Import Make events only when their geometry and options can be represented faithfully.
pub(super) fn make_from(d: &Descriptor) -> Mapped {
if let Some(mapped) = duplicate_layer_from_descriptor(d) {
return mapped;
@@ -165,13 +182,33 @@ pub(super) fn make_from(d: &Descriptor) -> Mapped {
if let Some(m) = get_enum(u, "Md ").and_then(|m| blend_label(&m)) {
p.insert("mode".into(), m.into());
}
match u.get("Grup") {
Some(D::Boolean(true)) => {
p.insert("clipToPrevious".into(), true.into());
}
Some(D::Boolean(false)) | None => {}
_ => return Mapped::Unsupported { harmless: false },
}
}
step("layer.new.layer", Value::Object(p))
}
Some("AdjL") => match type_desc.and_then(|t| adjustment_by_class(&trimmed(&t.class_id))) {
Some(a) => adjustment_steps(a, "layer.newAdjustmentLayer.", type_desc),
Some(a) => {
let mut mapped = adjustment_steps(a, "layer.newAdjustmentLayer.", type_desc);
if let Some(c) = using.and_then(|u| get_enum(u, "Clr ")) {
let Some(color) = lookup(LABEL_COLORS, &c) else { return Mapped::Unsupported { harmless: false } };
if let Mapped::Steps(steps) = &mut mapped {
steps.push(("layer.setLabelColor".into(), json!({"color": color})));
}
}
mapped
}
None => Mapped::Unsupported { harmless: false },
},
Some("contentLayer") if d.get("Shp ").is_some() || using.is_some_and(|u| u.get("Shp ").is_some() || u.get("strokeStyle").is_some()) => {
// A shape's geometry and stroke cannot be represented by a canvas-wide fill.
Mapped::Unsupported { harmless: false }
}
Some("contentLayer") => match type_desc {
Some(t) if t.class_id.is("solidColorLayer") => match get_obj(t, "Clr ").and_then(color_hex) {
Some(c) => step("layer.newFillLayer.solidColor", json!({"color": c})),
@@ -185,7 +222,7 @@ pub(super) fn make_from(d: &Descriptor) -> Mapped {
},
Some("layerSection") => {
let mut p = Map::new();
if let Some(n) = using.and_then(|u| get_text(u, "Nm ")) {
if let Some(n) = using.and_then(|u| get_text(u, "Nm ")).or_else(|| get_text(d, "Nm ")) {
p.insert("name".into(), n.into());
}
match get_ref(d, "From") {
@@ -223,6 +260,7 @@ pub(super) fn make_from(d: &Descriptor) -> Mapped {
}
}
/// Write a creation step, refusing native options the target descriptor cannot carry.
pub(super) fn make_to(id: &str, p: &Value) -> Option<Descriptor> {
let with_name = |cls: &str| {
let mut u = desc(cls);
@@ -233,12 +271,12 @@ pub(super) fn make_to(id: &str, p: &Value) -> Option<Descriptor> {
};
Some(match id {
"layer.new.layer" => {
// The descriptor carries the name, opacity and mode only. A step that also clips to
// the layer below, labels the layer, fills it with the neutral colour or places it
// The descriptor carries the name, opacity, mode and clipping flag. A step that
// labels the layer, fills it with the neutral colour or places it
// below the active layer would replay as a different layer, so it isn't exported
// (strict export fails, a partial one skips it: #7502, #7512, #7513, #7514).
// (strict export fails, a partial one skips it: #7512, #7513, #7514).
let set = |key: &str, default: Value| p.get(key).is_some_and(|v| !v.is_null() && *v != default);
if set("clipToPrevious", Value::Bool(false))
if p.get("clipToPrevious").is_some_and(|v| !v.is_null() && !v.is_boolean())
|| set("color", json!("none"))
|| set("fillNeutral", Value::Bool(false))
|| set("position", json!("above"))
@@ -246,6 +284,9 @@ pub(super) fn make_to(id: &str, p: &Value) -> Option<Descriptor> {
return None;
}
let mut u = with_name("Lyr ");
if jbool(p, "clipToPrevious") == Some(true) {
u = u.with("Grup", D::Boolean(true));
}
if let Some(o) = jnum(p, "opacity") {
u = u.with("Opct", pct(o * 100.0));
}
@@ -359,6 +400,7 @@ pub(super) fn make_to(id: &str, p: &Value) -> Option<Descriptor> {
})
}
/// Import selection geometry or a channel source, including its optional source layer.
fn selection_from(d: &Descriptor) -> Mapped {
let unsupported = Mapped::Unsupported { harmless: false };
match d.get("T ") {
@@ -369,7 +411,18 @@ fn selection_from(d: &Descriptor) -> Mapped {
_ => unsupported,
},
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"})),
(Some("Chnl"), Target::Ordinal(o)) if o == "Trsp" => {
let mut p = Map::new();
p.insert("channel".into(), "transparency".into());
if t.len() > 1 {
if t.len() != 2 || ref_class(&t[1..]).as_deref() != Some("Lyr") {
return unsupported;
}
let Some(layer) = layer_target(&t[1..]) else { return unsupported };
p.extend(layer);
}
step("select.loadSelection", Value::Object(p))
}
// ⌘-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})),
@@ -664,7 +717,14 @@ pub(super) fn set_to(id: &str, p: &Value) -> Option<Descriptor> {
return None;
}
"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") }])),
"transparency" => {
let mut r = vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: Id::new("Chnl"), value: Id::new("Trsp") }];
if p.get("layer").is_some_and(|v| !v.is_null()) {
let D::Reference(layer) = layer_ref(p)? else { return None };
r.extend(layer);
}
sel(D::Reference(r))
}
"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)),
},
+298 -6
View File
@@ -562,6 +562,7 @@ fn every_mapped_command_exports_and_imports_back() {
("layer.setProps", json!({"name": "Renamed", "opacity": 0.4, "blend": "Linear Light"})),
("layer.setProps", json!({"layer": "Shadow", "visible": false})),
("layer.setLabelColor", json!({"color": "red"})),
("layer.showOnly", json!({"layer": "Solo"})),
("layer.select", json!({"layer": "Shadow", "mode": "add"})),
("layer.select", json!({"layer": "Shadow", "mode": "range"})),
("layer.selectTop", json!({})),
@@ -2082,7 +2083,7 @@ fn minimum_and_maximum_with_roundness_are_not_exported_as_squareness() {
}
/// #7515: a Transform Selection's interpolation survives the round trip as a layer transform's
/// does. #7516-#7519: a reference point other than the centre, a skew or a warp can't be written,
/// does. An arbitrary coordinate reference, a skew or a warp can't be written,
/// so the step is refused instead of replaying as a plain scale.
#[test]
fn transform_selection_keeps_its_interpolation_and_refuses_what_it_cannot_carry() {
@@ -2094,7 +2095,6 @@ fn transform_selection_keeps_its_interpolation_and_refuses_what_it_cannot_carry(
assert_eq!(imported.actions[0].steps, vec![("select.transformSelection".to_string(), p)]);
for id in ["select.transformSelection", "edit.transform"] {
for p in [
json!({"scaleX": 140, "reference": "topLeft"}),
json!({"scaleX": 140, "reference": [3, 4]}),
json!({"scaleX": 140, "skewX": 12}),
json!({"scaleX": 140, "skewY": -5}),
@@ -2138,15 +2138,13 @@ fn canvas_bound_modify_and_placed_pattern_bucket_refuse_strict_export() {
}
}
/// #7502, #7512, #7513, #7514: a New Layer step that clips to the layer below, has a colour
/// label, fills with the neutral colour or goes below the active layer isn't exported, since the
/// descriptor carries only its name, opacity and mode. Those options at their defaults still
/// #7512, #7513, #7514: a New Layer step with a colour label, neutral fill or a position below
/// the active layer isn't exported. Invalid clipping values are also refused. Defaults still
/// export, and the step round-trips.
#[test]
fn new_layer_options_the_descriptor_cannot_carry_refuse_strict_export() {
let new_layer = |p: Value| Action { name: "Probe".into(), steps: vec![("layer.new.layer".into(), p)], ..Default::default() };
for p in [
json!({"name": "New", "clipToPrevious": true}),
json!({"name": "New", "color": "red"}),
json!({"name": "New", "mode": "Overlay", "fillNeutral": true}),
json!({"name": "New", "position": "below"}),
@@ -3175,3 +3173,297 @@ fn long_names_are_clipped_instead_of_copied_into_every_diagnostic() {
assert_eq!(imp.unsupported.len(), 50);
assert!(imp.unsupported.iter().all(|u| u.action.chars().count() == MAX_NAME_CHARS));
}
/// Newer Group from Layers recordings put the name outside Usng; existing nested names win.
#[test]
fn mapped_make_group_name_survives_load_and_save() {
for (top, nested, expected) in [(Some("Selected"), None, "Selected"), (None, Some("Nested"), "Nested"), (Some("Top"), Some("Nested"), "Nested")] {
let mut d = desc("null").with("null", class_ref("layerSection")).with("From", target_ref("Lyr "));
if let Some(name) = top {
d = d.with("Nm ", text(name));
}
if let Some(name) = nested {
d = d.with("Usng", D::Descriptor(desc("layerSection").with("Nm ", text(name))));
}
let source = one_action(vec![item("Mk ", "Group from Layers", Some(d))]);
let loaded = import(&atn::write(&source).unwrap()).unwrap();
assert_eq!(loaded.actions[0].steps, vec![("layer.groupLayers".into(), json!({"name": expected}))]);
let (saved, skipped) = export("Groups", &[&loaded.actions[0]], &[], false).unwrap();
assert!(skipped.is_empty());
assert_eq!(import(&saved).unwrap().actions[0].steps, loaded.actions[0].steps);
}
}
/// A recorded New Layer clipping flag must reach the command and survive strict export.
#[test]
fn mapped_make_clipping_flag_survives_load_and_save() {
for clip in [None, Some(false), Some(true)] {
let mut using = desc("Lyr ").with("Nm ", text("Clipped"));
if let Some(clip) = clip {
using = using.with("Grup", D::Boolean(clip));
}
let d = desc("null").with("null", class_ref("Lyr ")).with("Usng", D::Descriptor(using));
let loaded = import(&atn::write(&one_action(vec![item("Mk ", "New Layer", Some(d))])).unwrap()).unwrap();
let mut expected = json!({"name": "Clipped"});
if clip == Some(true) {
expected["clipToPrevious"] = json!(true);
}
assert_eq!(loaded.actions[0].steps, vec![("layer.new.layer".into(), expected)]);
let (saved, skipped) = export("Layers", &[&loaded.actions[0]], &[], false).unwrap();
assert!(skipped.is_empty());
assert_eq!(import(&saved).unwrap().actions[0].steps, loaded.actions[0].steps);
}
}
/// An unreadable clipping flag keeps the original step instead of creating an unclipped layer.
#[test]
fn mapped_make_invalid_clipping_flag_is_kept() {
let using = desc("Lyr ").with("Grup", long(1.0));
let d = desc("null").with("null", class_ref("Lyr ")).with("Usng", D::Descriptor(using));
let loaded = import(&atn::write(&one_action(vec![item("Mk ", "New Layer", Some(d))])).unwrap()).unwrap();
assert_eq!(loaded.actions[0].steps[0].0, PHOTOSHOP_STEP);
}
/// Load a recorded descriptor through the same parser as Load Actions.
fn mapped_recording(event: &str, descriptor: Descriptor) -> Imported {
import(&atn::write(&one_action(vec![item(event, event, Some(descriptor))])).unwrap()).unwrap()
}
/// Every frame anchor survives import/export; unknown anchors stay available verbatim.
#[test]
fn mapped_transform_reference_points_round_trip() {
for (code, reference) in [
("Qcsa", "center"),
("Qcs0", "topLeft"),
("Qcs1", "top"),
("Qcs2", "topRight"),
("Qcs3", "left"),
("Qcs4", "center"),
("Qcs5", "right"),
("Qcs6", "bottomLeft"),
("Qcs7", "bottom"),
("Qcs8", "bottomRight"),
] {
for target in [target_ref("Lyr "), D::Reference(vec![ReferenceItem::Property { class: class("Chnl"), key: Id::new("fsel") }])] {
let d = desc("null")
.with("null", target)
.with("FTcs", enm("QCSt", code))
.with("Wdth", pct(50.0))
.with("Hght", pct(50.0))
.with("Ofst", D::Descriptor(desc("Ofst").with("Hrzn", px(0.0)).with("Vrtc", px(0.0))));
let loaded = mapped_recording("Trnf", d);
let params = &loaded.actions[0].steps[0].1;
assert_eq!(params.get("reference").and_then(Value::as_str).unwrap_or("center"), reference);
let (bytes, _) = export("Anchors", &[&loaded.actions[0]], &[], false).unwrap();
assert_eq!(import(&bytes).unwrap().actions[0].steps, loaded.actions[0].steps);
if reference == "topLeft" && loaded.actions[0].steps[0].0 == "select.transformSelection" {
let mut s = Session::new();
s.execute("file.new", json!({"width":256,"height":256})).unwrap();
s.execute("select.rect", json!({"x":60,"y":60,"width":100,"height":100})).unwrap();
let (id, p) = &loaded.actions[0].steps[0];
s.execute(id, p.clone()).unwrap();
assert_eq!(s.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(), photocraft_geom::Rect::new(60, 60, 110, 110));
}
}
}
let d = desc("null").with("null", target_ref("Lyr ")).with("FTcs", enm("QCSt", "unknown")).with("Wdth", pct(50.0));
assert_eq!(mapped_recording("Trnf", d).actions[0].steps[0].0, PHOTOSHOP_STEP);
}
/// Alt-clicking an eye twice must isolate and then restore visibility, not just show a layer.
#[test]
fn mapped_show_only_round_trip_and_toggle() {
let d = desc("null").with("null", D::List(vec![name_ref("Lyr ", "Solo")])).with("TglO", D::Boolean(true));
let loaded = mapped_recording("Shw ", d);
assert_eq!(loaded.actions[0].steps, vec![("layer.showOnly".into(), json!({"layer": "Solo"}))]);
let (bytes, _) = export("Eyes", &[&loaded.actions[0]], &[], false).unwrap();
let saved = atn::parse(&bytes).unwrap();
assert_eq!(get_bool(saved.actions[0].items[0].descriptor.as_ref().unwrap(), "TglO"), Some(true));
assert_eq!(import(&bytes).unwrap().actions[0].steps, loaded.actions[0].steps);
let mut s = Session::new();
s.execute("file.new", json!({"width":4,"height":4})).unwrap();
s.execute("layer.new.layer", json!({"name":"Solo"})).unwrap();
let visible = |s: &Session| s.active().unwrap().doc.layers.iter().map(|l| l.visible).collect::<Vec<_>>();
let original = visible(&s);
let (id, params) = &loaded.actions[0].steps[0];
assert_eq!(s.execute(id, params.clone()).unwrap()["shownAlone"], true);
assert_ne!(visible(&s), original);
assert_eq!(s.execute(id, params.clone()).unwrap()["shownAlone"], false);
assert_eq!(visible(&s), original);
let malformed = desc("null").with("null", D::List(vec![name_ref("Lyr ", "Solo"), long(1.0)])).with("TglO", D::Boolean(true));
assert_eq!(mapped_recording("Shw ", malformed).actions[0].steps[0].0, PHOTOSHOP_STEP);
}
/// A layer label is separate from an adjustment's own colour parameter.
#[test]
fn mapped_adjustment_label_survives_export() {
let d = desc("null")
.with("null", class_ref("AdjL"))
.with("Usng", D::Descriptor(desc("AdjL").with("Type", D::Descriptor(desc("Invr"))).with("Clr ", enm("Clr ", "Rd "))));
let loaded = mapped_recording("Mk ", d);
assert_eq!(loaded.actions[0].steps, vec![("layer.newAdjustmentLayer.invert".into(), json!({})), ("layer.setLabelColor".into(), json!({"color":"red"}))]);
let (bytes, _) = export("Labels", &[&loaded.actions[0]], &[], false).unwrap();
assert_eq!(import(&bytes).unwrap().actions[0].steps, loaded.actions[0].steps);
let mut s = Session::new();
s.execute("file.new", json!({"width":4,"height":4})).unwrap();
for (id, params) in &loaded.actions[0].steps {
s.execute(id, params.clone()).unwrap();
}
let st = s.active().unwrap();
assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().label.id(), "red");
}
/// Keeping an unmapped shape is safer than creating a solid fill over the whole canvas.
#[test]
fn mapped_shape_creation_is_kept_with_its_geometry_and_stroke() {
let d = desc("null").with("null", class_ref("contentLayer")).with("Shp ", D::Descriptor(desc("Rctn").with("Wdth", px(20.0)))).with(
"Usng",
D::Descriptor(
desc("contentLayer")
.with("Type", D::Descriptor(desc("solidColorLayer")))
.with("strokeStyle", D::Descriptor(desc("strokeStyle").with("strokeStyleLineWidth", px(3.0)))),
),
);
let loaded = mapped_recording("Mk ", d.clone());
assert_eq!(loaded.actions[0].steps[0].0, PHOTOSHOP_STEP);
let (bytes, _) = export("Shapes", &[&loaded.actions[0]], &[], false).unwrap();
assert_eq!(atn::parse(&bytes).unwrap().actions[0].items[0].descriptor.as_ref(), Some(&d));
}
/// Copy and Cut retain all recorded layer options, including labels and fractional opacity.
#[test]
fn mapped_copy_cut_layer_options_survive_export() {
for (copy, id) in [(true, "layer.new.layerViaCopy"), (false, "layer.new.layerViaCut")] {
let options = desc("Lyr ").with("Nm ", text("Extracted")).with("Md ", enm("BlnM", "Mltp")).with("Opct", pct(37.5)).with("Clr ", enm("Clr ", "Bl "));
let d = desc("null").with("Nw ", D::Descriptor(options)).with("Usng", enm("ArSl", "Slct")).with("Cpy ", D::Boolean(copy));
let loaded = mapped_recording("Mk ", d);
assert_eq!(
loaded.actions[0].steps,
vec![
(id.into(), json!({})),
("layer.setLabelColor".into(), json!({"color":"blue"})),
("layer.setProps".into(), json!({"name":"Extracted","blend":"Multiply","opacity":0.375}))
]
);
let (bytes, _) = export("Extract", &[&loaded.actions[0]], &[], false).unwrap();
let saved = import(&bytes).unwrap();
assert_eq!(saved.actions[0].steps[..2], loaded.actions[0].steps[..2]);
let mut props = serde_json::Map::new();
for (id, p) in &saved.actions[0].steps[2..] {
assert_eq!(id, "layer.setProps");
props.extend(p.as_object().unwrap().clone());
}
assert_eq!(Value::Object(props), loaded.actions[0].steps[2].1);
let mut s = Session::new();
s.execute("file.new", json!({"width":4,"height":4,"background":"white"})).unwrap();
s.execute("select.rect", json!({"x":0,"y":0,"width":2,"height":2})).unwrap();
for (id, params) in &saved.actions[0].steps {
s.execute(id, params.clone()).unwrap();
}
let st = s.active().unwrap();
let layer = st.doc.layer(st.active_layer.unwrap()).unwrap();
assert_eq!(layer.name, "Extracted");
assert_eq!(layer.opacity, 0.375);
assert_eq!(layer.blend, photocraft_color::BlendMode::Multiply);
assert_eq!(layer.label.id(), "blue");
}
}
/// Loading transparency must keep the source layer instead of using the active layer.
#[test]
fn mapped_named_layer_transparency_survives_export() {
let source = D::Reference(vec![
ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: code("Trsp") },
ReferenceItem::Name { class: class("Lyr "), name: UnicodeString::new_nul("Source") },
]);
let d = desc("null").with("null", D::Reference(vec![ReferenceItem::Property { class: class("Chnl"), key: code("fsel") }])).with("T ", source);
let loaded = mapped_recording("setd", d);
assert_eq!(loaded.actions[0].steps, vec![("select.loadSelection".into(), json!({"channel":"transparency","layer":"Source"}))]);
let (bytes, _) = export("Transparency", &[&loaded.actions[0]], &[], false).unwrap();
assert_eq!(import(&bytes).unwrap().actions[0].steps, loaded.actions[0].steps);
let mut s = Session::new();
s.execute("file.new", json!({"width":4,"height":4,"background":"white"})).unwrap();
s.execute("layer.setProps", json!({"name":"Source"})).unwrap();
s.execute("layer.new.layer", json!({"name":"Empty"})).unwrap();
let (id, p) = &loaded.actions[0].steps[0];
s.execute(id, p.clone()).unwrap();
assert_eq!(s.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(), photocraft_geom::Rect::new(0, 0, 4, 4));
}
/// A localized Background and an ordinary layer named Background are distinct targets.
#[test]
fn mapped_background_property_survives_export_and_playback() {
let r = D::Reference(vec![ReferenceItem::Property { class: class("Lyr "), key: code("Bckg") }]);
let loaded = mapped_recording("Hd ", desc("null").with("null", D::List(vec![r.clone()])));
assert_eq!(loaded.actions[0].steps, vec![("layer.hideLayers".into(), json!({"layer":{"background":true}}))]);
let (bytes, _) = export("Background", &[&loaded.actions[0]], &[], false).unwrap();
assert_eq!(get_list(atn::parse(&bytes).unwrap().actions[0].items[0].descriptor.as_ref().unwrap(), "null"), Some(&[r][..]));
let mut s = Session::new();
s.execute("file.new", json!({"width":4,"height":4,"background":"white"})).unwrap();
std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).layers[0].name = "Hintergrund".into();
s.execute("layer.new.layer", json!({"name":"Background"})).unwrap();
let (id, p) = &loaded.actions[0].steps[0];
s.execute(id, p.clone()).unwrap();
let layers = &s.active().unwrap().doc.layers;
assert!(!layers[0].visible);
assert!(layers[1].visible);
s.execute("layer.hideLayers", json!({"layer":"Background"})).unwrap();
assert!(!s.active().unwrap().doc.layers[1].visible);
assert!(s.execute("layer.showLayers", json!({"layer":{"background":false}})).is_err());
s.execute("layer.setLabelColor", json!({"layer":{"background":true},"color":"red"})).unwrap();
assert_eq!(s.active().unwrap().doc.layers[0].label.id(), "red");
s.execute("select.loadSelection", json!({"channel":"transparency","layer":{"background":true}})).unwrap();
assert_eq!(s.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(), photocraft_geom::Rect::new(0, 0, 4, 4));
let selected = mapped_recording("slct", desc("null").with("null", D::Reference(vec![ReferenceItem::Property { class: class("Lyr "), key: code("Bckg") }])));
let (bytes, _) = export("Select Background", &[&selected.actions[0]], &[], false).unwrap();
assert_eq!(import(&bytes).unwrap().actions[0].steps, selected.actions[0].steps);
let (id, p) = &selected.actions[0].steps[0];
s.execute(id, p.clone()).unwrap();
assert_eq!(s.active().unwrap().active_layer, Some(s.active().unwrap().doc.layers[0].id));
let revision = s.active().unwrap().revision;
for selector in [json!({"background":false}), json!({"background":"true"}), json!({"background":true,"extra":0})] {
assert!(s.execute("select.loadSelection", json!({"channel":"transparency","layer":selector})).is_err());
assert_eq!(s.active().unwrap().revision, revision);
}
}
/// An unanswered Close must not turn into an explicit discard or close a changed document.
#[test]
fn mapped_close_keeps_ask_and_discard_distinct() {
let loaded = mapped_recording("Cls ", desc("null"));
assert_eq!(loaded.actions[0].steps, vec![("file.close".into(), json!({"save":"ask"}))]);
let (bytes, _) = export("Close", &[&loaded.actions[0]], &[], false).unwrap();
assert!(atn::parse(&bytes).unwrap().actions[0].items[0].descriptor.as_ref().unwrap().get("Svng").is_none());
assert_eq!(import(&bytes).unwrap().actions[0].steps, loaded.actions[0].steps);
let mut s = Session::new();
s.execute("file.new", json!({"width":4,"height":4})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
let (id, p) = &loaded.actions[0].steps[0];
assert!(s.execute(id, p.clone()).is_err());
assert_eq!(s.documents().len(), 1);
s.execute("file.close", json!({"save":"discard"})).unwrap();
assert!(s.documents().is_empty());
s.execute("file.new", json!({"width":4,"height":4})).unwrap();
s.execute(id, p.clone()).unwrap();
assert!(s.documents().is_empty());
}
/// Lab Photo Filter colours use the CMS conversion and remain mapped after saving as RGB.
#[test]
fn mapped_lab_photo_filter_imports_and_round_trips() {
for (lab, expected) in
[([0.0, 0.0, 0.0], "#000000"), ([100.0, 0.0, 0.0], "#ffffff"), ([50.0, 0.0, 0.0], "#777777"), ([54.2917, 80.8125, 69.8851], "#ff0000")]
{
let color = desc("LbCl").with("Lmnc", D::Double(lab[0])).with("A ", D::Double(lab[1])).with("B ", D::Double(lab[2]));
let loaded = mapped_recording("photoFilter", desc("null").with("Clr ", D::Descriptor(color)).with("Dnst", long(25.0)));
let (id, params) = &loaded.actions[0].steps[0];
assert_eq!(id, "image.adjustments.photoFilter");
assert_eq!(params["color"], expected);
assert_eq!(params["density"].as_f64(), Some(25.0));
let (bytes, _) = export("Lab", &[&loaded.actions[0]], &[], false).unwrap();
let saved = import(&bytes).unwrap();
assert_eq!(saved.actions[0].steps[0].0, *id);
assert_eq!(saved.actions[0].steps[0].1["color"], expected);
assert_eq!(saved.actions[0].steps[0].1["density"].as_f64(), Some(25.0));
}
}
+6 -1
View File
@@ -102,10 +102,15 @@ pub(super) fn native_pixels(doc: &Document, layer: Option<LayerId>) -> Result<(V
}
/// `"layer"` param of a source: a layer id, a layer name (the topmost of that name, as a loaded
/// Photoshop action refers to it), or `"merged"` (default). An unknown name is an error.
/// Photoshop action refers to it), `{"background":true}`, or `"merged"` (default).
/// An unknown name or a missing requested Background is an error.
fn source_layer(doc: &Document, p: &Value, cmd: &str) -> Result<Option<LayerId>> {
match p.get("layer") {
Some(Value::Number(n)) => Ok(n.as_u64().map(LayerId)),
Some(v) if *v == serde_json::json!({"background": true}) => {
doc.background().map(|l| Some(l.id)).ok_or_else(|| bad(cmd, "the source document has no Background layer"))
}
Some(Value::Object(_)) => Err(bad(cmd, "a source layer selector must be {\"background\":true}")),
Some(Value::String(name)) if !name.is_empty() && name != "merged" => doc
.walk()
.into_iter()
+10 -5
View File
@@ -1,7 +1,7 @@
//! Undoable layer colour labels. A group applies the label to its existing descendants,
//! without changing pixels, visibility, locks or the layer selection.
use photocraft_doc::{LabelColor, LayerId};
use photocraft_doc::LabelColor;
use serde_json::{Value, json};
use crate::commands::CommandSpec;
@@ -18,15 +18,19 @@ fn enabled(s: &Session) -> std::result::Result<(), String> {
if st.selected_layers().is_empty() { Err("no layer selected".into()) } else { Ok(()) }
}
/// Label an explicit layer or the selected layers, including a group's descendants.
fn set_label(s: &mut Session, p: &Value) -> Result<Value> {
let p = p.as_object().ok_or_else(|| bad("expected an object"))?;
p.as_object().ok_or_else(|| bad("expected an object"))?;
let color =
p.get("color").and_then(Value::as_str).and_then(LabelColor::from_id).ok_or_else(|| {
bad("`color` must be a layer colour id (none, red, orange, yellow, green, seafoam, blue, indigo, magenta, fuchsia, violet, gray)")
})?;
let st = s.active().ok_or(EngineError::NoDocument)?;
let roots = match p.get("layer") {
Some(v) => vec![LayerId(v.as_u64().ok_or_else(|| bad("`layer` must be an unsigned integer"))?)],
if p.get("layer") == Some(&Value::Null) {
return Err(bad("`layer` must name a layer when supplied"));
}
let roots = match crate::commands::explicit_layer(s, p)? {
Some(id) => vec![id],
None => st.selected_layers(),
};
if roots.is_empty() {
@@ -63,13 +67,14 @@ fn set_label(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"color": color.id(), "layers": targets.iter().map(|(_, id)| id.0).collect::<Vec<_>>(), "changed": changed}))
}
/// Register the undoable layer-label command and its target options.
pub fn specs() -> Vec<CommandSpec> {
vec![CommandSpec {
id: ID,
label: "Layer Color",
menu: &[],
shortcut: None,
params: r#"{"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray","layer":id?} (no layer: selected layers; groups include descendants)"#,
params: r#"{"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray","layer":id|name|{"background":true}?} (no layer: selected layers; groups include descendants)"#,
enabled,
run: set_label,
journal: true,
@@ -1,6 +1,6 @@
use super::*;
use photocraft_color::SampleType;
use photocraft_doc::{Layer, LayerContent};
use photocraft_doc::{Layer, LayerContent, LayerId};
fn fixture(depth: u8) -> (Session, [LayerId; 4]) {
let mut s = Session::new();
+7 -2
View File
@@ -4,7 +4,8 @@ use super::{BlendMode, Document, EngineError, Layer, LayerId, LayerMask, Result,
/// The layer a command's `"layer"` param names: an id, or a name (the topmost layer of that
/// name, as Photoshop's "select layer by name" action step finds it, so a loaded action replays
/// in another document; a name that matches no layer exactly matches regardless of case, so
/// `"background"` finds the Background). `None` when the param is absent.
/// `"background"` finds that name). `{"background":true}` targets the actual Background,
/// independently of its name. `None` when the param is absent.
pub(crate) fn explicit_layer(s: &Session, p: &Value) -> Result<Option<LayerId>> {
match p.get("layer") {
Some(Value::Number(n)) => {
@@ -21,8 +22,12 @@ pub(crate) fn explicit_layer(s: &Session, p: &Value) -> Result<Option<LayerId>>
.map(|(_, _, l)| Some(l.id))
.ok_or_else(|| EngineError::Other(format!("no layer named \"{name}\"; {}", layer_listing(&d.doc))))
}
Some(Value::Object(selector)) if selector.len() == 1 && selector.get("background") == Some(&Value::Bool(true)) => {
let d = s.active().ok_or(EngineError::NoDocument)?;
d.doc.background().map(|l| Some(l.id)).ok_or_else(|| EngineError::Other("the document has no Background layer".into()))
}
Some(Value::Null) | None => Ok(None),
Some(other) => Err(EngineError::Other(format!("`layer` must be an id or a name, not {other}"))),
Some(other) => Err(EngineError::Other(format!("`layer` must be an id, a name or {{\"background\":true}}, not {other}"))),
}
}