Merge PR #7642: Prefer an installed pattern ID over a colliding name in ATN import

This commit is contained in:
David Mann committed 2026-11-01 14:41:19 +01:00
commit f2fd6efdc0
4 files changed
+154 -16

No files matched your search

+18 -7
View File
@@ -9,14 +9,23 @@ use super::tables::{LABEL_COLORS, MODES, blend_label, blend_ps, lookup, lookup_b
use super::{D, Descriptor, Id, Map, ReferenceItem, Value, json};
/// 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.
/// `layer.newFillLayer.pattern` / `layer.fill.pattern.set`. A pattern recorded with both an id
/// and a name goes by the id with the name as `patternName`: ids differ between Photoshop's
/// library and one rebuilt from the same `.pat` file, while names may collide. 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());
let name = get_text(ptrn, "Nm ").filter(|n| !n.is_empty());
match (get_text(ptrn, "Idnt").filter(|i| !i.is_empty()), name) {
(Some(id), Some(name)) => {
p.insert("pattern".into(), id.into());
p.insert("patternName".into(), name.into());
}
(key, name) => {
p.insert("pattern".into(), key.or(name)?.into());
}
}
}
if let Some(s) = get_num(t, "Scl ") {
p.insert("scale".into(), s.into());
@@ -33,8 +42,10 @@ fn pattern_params(t: &Descriptor) -> Option<Map<String, Value>> {
/// 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))));
match (jstr(p, "pattern"), jstr(p, "patternName")) {
(Some(id), Some(n)) => t = t.with("Ptrn", D::Descriptor(desc("Ptrn").with("Nm ", text(n)).with("Idnt", text(id)))),
(Some(n), None) => 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));
+108
View File
@@ -659,6 +659,7 @@ fn every_mapped_command_exports_and_imports_back() {
("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"})),
("layer.newFillLayer.pattern", json!({"pattern": "b7a3c1d2-0000-4000-8000-000000000001", "patternName": "Twin", "scale": 50})),
("image.mode.bitmap", json!({"method": "threshold"})),
("image.imageSize", json!({"resolution": 1200, "resample": "preserveDetails", "keepPrintSize": true})),
("layer.new.layerFromBackground", json!({"ifPresent": true, "select": false})),
@@ -3510,3 +3511,110 @@ 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));
}
/// A Pattern Fill step whose `Ptrn` holds `id` and `name`, as the reference application records it.
fn pattern_fill_step(id: &str, name: &str) -> AtnItem {
let t = desc("patternLayer").with("Ptrn", D::Descriptor(desc("Ptrn").with("Idnt", text(id)).with("Nm ", text(name))));
item(
"Mk ",
"Make",
Some(desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t))))),
)
}
/// Defines a 4×4 pattern of `color` named `name` in `s`'s library from its active document.
fn define_pattern(s: &mut Session, color: &str, name: &str) -> String {
s.execute("edit.fill", json!({"contents": "color", "color": color})).unwrap();
s.execute("edit.definePattern", json!({"name": name})).unwrap()["pattern"].as_str().unwrap().to_string()
}
fn pixel(s: &mut Session) -> Vec<f64> {
let v = s.execute("document.pixel", json!({"x": 1, "y": 1})).unwrap();
v.as_array().unwrap().iter().map(|c| c.as_f64().unwrap()).collect()
}
/// A Pattern Fill step whose `Ptrn` names both an installed id and a display name shared by
/// another pattern plays the pattern with that id; a foreign id falls back to the name.
#[test]
fn pattern_fill_prefers_an_installed_id_over_a_colliding_name() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb", "depth": 8})).unwrap();
let mut define = |color: &str| {
s.execute("edit.fill", json!({"contents": "color", "color": color})).unwrap();
s.execute("edit.definePattern", json!({"name": "Twin"})).unwrap()["pattern"].as_str().unwrap().to_string()
};
let red = define("#ff0000");
let blue = define("#0000ff");
assert_ne!(red, blue);
s.patterns.items.retain(|p| p.id == red || p.id == blue);
s.patterns.items.sort_by_key(|p| p.id != blue);
let fill_step = |id: &str| {
let t = desc("patternLayer").with("Ptrn", D::Descriptor(desc("Ptrn").with("Idnt", text(id)).with("Nm ", text("Twin"))));
item(
"Mk ",
"Make",
Some(desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t))))),
)
};
let data = set_of("Pat", vec![("Installed", vec![fill_step(&red)]), ("Foreign", vec![fill_step("not-installed-id")])]);
let r = s.execute("actions.load", json!({"data": data})).unwrap();
assert!(r["unsupported"].as_array().is_none_or(|u| u.is_empty()), "{r}");
for (action, want) in [("Installed", [1.0, 0.0, 0.0, 1.0]), ("Foreign", [0.0, 0.0, 1.0, 1.0])] {
s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb", "depth": 8})).unwrap();
let r = s.execute("actions.play", json!({"action": action})).unwrap();
assert!(r.get("failed").is_none(), "{r}");
let v = s.execute("document.pixel", json!({"x": 1, "y": 1})).unwrap();
let got: Vec<f64> = v.as_array().unwrap().iter().map(|c| c.as_f64().unwrap()).collect();
assert_eq!(got, want, "{action}");
}
}
/// The recorded id is looked up by id alone, in the document and then the library, before any
/// name: a document pattern *named* like the id does not beat the library pattern with that id,
/// and a foreign id that happens to be another pattern's name falls back to the recorded name.
/// An id and a name of the same pattern play it.
#[test]
fn pattern_fill_ids_beat_names_across_document_and_library() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb", "depth": 8})).unwrap();
let red = define_pattern(&mut s, "#ff0000", "Red");
define_pattern(&mut s, "#0000ff", "Blue");
let green = define_pattern(&mut s, "#00ff00", &red);
let data = set_of(
"Pat",
vec![
("IdWins", vec![pattern_fill_step(&red, "Blue")]),
("NameFallback", vec![pattern_fill_step("Red", "Blue")]),
("Same", vec![pattern_fill_step(&red, "Red")]),
],
);
s.execute("actions.load", json!({"data": data})).unwrap();
// Only the playback document holds the green pattern named like the red one's id.
s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb", "depth": 8})).unwrap();
s.execute("layer.newFillLayer.pattern", json!({"pattern": green})).unwrap();
s.execute("pattern.delete", json!({"pattern": green})).unwrap();
assert!(s.active().unwrap().doc.patterns.iter().any(|p| p.id == green && p.name == red));
assert_eq!(pixel(&mut s), [0.0, 1.0, 0.0, 1.0]);
for (action, want) in [("IdWins", [1.0, 0.0, 0.0, 1.0]), ("NameFallback", [0.0, 0.0, 1.0, 1.0]), ("Same", [1.0, 0.0, 0.0, 1.0])] {
let r = s.execute("actions.play", json!({"action": action})).unwrap();
assert!(r.get("failed").is_none(), "{action}: {r}");
assert_eq!(pixel(&mut s), want, "{action}");
}
}
/// A recorded pattern installed neither by id nor by name fails with an error that names the
/// pattern, from the imported step and from the Pattern Fill dialog's command alike.
#[test]
fn pattern_fill_missing_everywhere_names_the_pattern() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb", "depth": 8})).unwrap();
define_pattern(&mut s, "#ff0000", "Red");
let data = set_of("Pat", vec![("Missing", vec![pattern_fill_step("5e1c0000-aaaa-4bbb-8ccc-000000000000", "My Wood")])]);
s.execute("actions.load", json!({"data": data})).unwrap();
let r = s.execute("actions.play", json!({"action": "Missing"})).unwrap();
let err = r["failed"]["error"].as_str().unwrap_or_default();
assert!(err.contains("\"My Wood\""), "{r}");
s.execute("layer.newFillLayer.pattern", json!({"pattern": "Red"})).unwrap();
let e = s.execute("layer.fill.pattern.set", json!({"pattern": "5e1c0000-aaaa-4bbb-8ccc-000000000000", "patternName": "My Wood"})).unwrap_err();
assert!(e.to_string().contains("\"My Wood\""), "{e}");
}
+26 -7
View File
@@ -182,12 +182,31 @@ pub fn resolve(s: &Session, key: &str) -> Option<Pattern> {
pub(crate) fn resolve_param(s: &Session, cmd: &str, p: &Value) -> Result<Pattern> {
let key = p.get("pattern").and_then(Value::as_str).unwrap_or("");
if let Some(pat) = resolve(s, key) {
return paintable(cmd, pat);
}
match library_pattern(s, key).map(|lp| full(s, lp)) {
Some(Err(e)) => Err(bad(cmd, e)),
_ => Err(bad(cmd, format!("no pattern \"{key}\" (see pattern.list)"))),
resolve_or_named(s, key, p).map_err(|e| bad(cmd, e)).and_then(|pat| paintable(cmd, pat))
}
/// The pattern `key` names, or with a `patternName` in `p` (an imported action's pattern recorded
/// with both an id and a name) the pattern with id `key`: the active document's, then the
/// library's, by id alone, and only when that id is installed nowhere the one `patternName`
/// names, as the reference application plays such a step. The error says why: no such pattern,
/// or a saved library pattern whose pixels can't be read.
pub(crate) fn resolve_or_named(s: &Session, key: &str, p: &Value) -> std::result::Result<Pattern, String> {
use photocraft_doc::pattern::find;
let name = p.get("patternName").and_then(Value::as_str).filter(|n| !n.is_empty());
// `find` with an empty name looks up the id alone; both empty find nothing.
let in_doc = |id: &str, name: &str| s.active().and_then(|d| find(&d.doc.patterns, id, name)).map(|p| (p, false));
let by_key = |k: &str| in_doc(k, k).or_else(|| library_pattern(s, k).map(|p| (p, true)));
let found = match name {
Some(n) => in_doc(key, "").or_else(|| find(&s.patterns.items, key, "").map(|p| (p, true))).or_else(|| by_key(n)),
None => by_key(key),
};
match found {
Some((pat, false)) => Ok(pat.clone()),
Some((pat, true)) => full(s, pat),
None => Err(match name {
Some(n) => format!("no pattern \"{n}\" (id \"{key}\"; see pattern.list)"),
None => format!("no pattern \"{key}\" (see pattern.list)"),
}),
}
}
@@ -588,7 +607,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Pattern…",
menu: &["Layer", "New Fill Layer"],
shortcut: None,
params: r##"{"pattern":id|name?=first library pattern,"scale":1..1000=100,"angle":deg=0,"link":bool=true,"phase":[x,y]?,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask)}"##,
params: r##"{"pattern":id|name?=first library pattern,"patternName":name? (then `pattern` is an id; the name is used when no pattern has that id),"scale":1..1000=100,"angle":deg=0,"link":bool=true,"phase":[x,y]?,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask)}"##,
enabled: has_doc,
journal: true,
run: new_fill_layer,
+2 -2
View File
@@ -37,7 +37,7 @@ fn edited(s: &Session, base: &Fill, p: &Value) -> Result<(Fill, Option<Pattern>)
let (mut scale, mut angle, mut link, mut phase, mut pat) = (*scale, *angle, *link, *phase, None);
if let Some(v) = p.get("pattern").filter(|v| !v.is_null()) {
let key = v.as_str().filter(|k| !k.is_empty()).ok_or_else(|| bad("`pattern` is a pattern id or name"))?;
pat = Some(crate::pattern_cmds::resolve(s, key).ok_or_else(|| bad(format!("no pattern \"{key}\" (see pattern.list)")))?);
pat = Some(crate::pattern_cmds::resolve_or_named(s, key, p).map_err(bad)?);
}
if let Some(v) = num("scale", SCALE_RANGE)? {
scale = v / 100.0;
@@ -139,7 +139,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Pattern Fill…",
menu: &[],
shortcut: None,
params: r##"{"layer":id? (default active; a Pattern Fill layer),"document":id? (reject a stale dialog),"pattern":id|name?,"scale":1..1000?,"angle":-180..180?,"link":bool?,"phase":[x,y]? (Snap to Origin: [0,0])}; omitted values keep the layer's"##,
params: r##"{"layer":id? (default active; a Pattern Fill layer),"document":id? (reject a stale dialog),"pattern":id|name?,"patternName":name? (then `pattern` is an id; the name is used when no pattern has that id),"scale":1..1000?,"angle":-180..180?,"link":bool?,"phase":[x,y]? (Snap to Origin: [0,0])}; omitted values keep the layer's"##,
enabled: |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()),
run: set,
journal: true,