diff --git a/Cargo.lock b/Cargo.lock index b66bb8add0..f2ebdb2198 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5226,10 +5226,13 @@ dependencies = [ "photocraft-io", "photocraft-raster", "photocraft-raw", + "serde", "serde_json", + "tempfile", "thiserror 2.0.21", "tokio", "winresource", + "xtask", ] [[package]] @@ -9409,6 +9412,7 @@ dependencies = [ "chrono", "serde", "serde_json", + "tempfile", "toml", ] diff --git a/apps/photocraft-cli/Cargo.toml b/apps/photocraft-cli/Cargo.toml index 24c59e4e61..db256c2726 100644 --- a/apps/photocraft-cli/Cargo.toml +++ b/apps/photocraft-cli/Cargo.toml @@ -43,12 +43,16 @@ thiserror = { workspace = true } tokio = { version = "1", features = ["rt-multi-thread", "macros"] } [dev-dependencies] +serde = { workspace = true } +tempfile = "3" # Synthetic camera raws (#7789). photocraft-raw = { workspace = true, features = ["testgen"] } # Shell completions and man pages (examples/man-and-completions.rs, for the packages); not in # the binary. clap_complete = { workspace = true } clap_mangen = { workspace = true } +# The PSD write recipe runner (tests/it/psd_write_oracle.rs). +xtask = { path = "../../xtask" } [build-dependencies] # Icon + VERSIONINFO for photocraft-cli.exe; build.rs only uses it when targeting Windows. diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index d735641f2f..3f29309ad5 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -123,6 +123,9 @@ pub(crate) struct InfoArgs { /// Explicitly approve high-memory PSD/PSB imports within the hard memory budget #[arg(long)] pub(crate) approve_high_memory: bool, + /// Also list every text run and paragraph run, anti-aliasing and full layer-effect settings + #[arg(long)] + pub(crate) detail: bool, } /// Open a file (or start a new document), run engine commands in order, save the result diff --git a/apps/photocraft-cli/src/document.rs b/apps/photocraft-cli/src/document.rs index c015a5ed74..b71fc19c56 100644 --- a/apps/photocraft-cli/src/document.rs +++ b/apps/photocraft-cli/src/document.rs @@ -57,7 +57,10 @@ pub(crate) fn info(a: &InfoArgs, out: &mut dyn Write) -> Result { let file = &a.file; let mut h = Headless::trusted_local(); let opened = h.open_with_approval(file, a.approve_high_memory)?; - let mut doc = h.inspect(None)?; + let mut doc = match (a.detail, h.session.active()) { + (true, Some(st)) => photocraft_engine::inspect::document_detail(st), + _ => h.inspect(None)?, + }; let mut warnings = opened["warnings"].as_array().cloned().unwrap_or_default(); if let Some(st) = h.session.active() { warnings.extend(missing_font_warnings(&st.doc).into_iter().map(Value::String)); diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index fcfaa8c742..87bfbd53d8 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -1721,3 +1721,30 @@ fn tiff_options_choose_compression_transparency_and_pyramid() { assert!(!out.exists(), "{flag} {bad} wrote a file"); } } + +#[test] +fn info_detail_adds_text_runs_and_antialiasing() { + fn type_layer(doc: &Value) -> Option<&Value> { + let mut stack: Vec<&Value> = doc["layers"].as_array()?.iter().collect(); + while let Some(l) = stack.pop() { + if l["kind"] == "Type" { + return Some(l); + } + stack.extend(l["children"].as_array().into_iter().flatten()); + } + None + } + let dir = tmp("info-detail"); + let file = dir.join("t.psd"); + ok(bin() + .args(["run", "--new", r#"{"width":64,"height":64}"#, "--cmd", "type.create", "--params", r#"{"text":"Hi","x":4,"y":30,"name":"T"}"#, "--out"]) + .arg(&file)); + let plain: Value = serde_json::from_str(&ok(bin().arg("info").arg(&file).arg("--compact")).stdout).unwrap(); + let text = &type_layer(&plain).expect("type layer")["text"]; + assert!(text.get("runs").is_none() && text.get("antialias").is_none(), "{text}"); + let detail: Value = serde_json::from_str(&ok(bin().arg("info").arg(&file).args(["--compact", "--detail"])).stdout).unwrap(); + let text = &type_layer(&detail).expect("type layer")["text"]; + assert!(text.get("antialias").is_some(), "{text}"); + assert!(text["runs"].as_array().is_some_and(|r| !r.is_empty()), "{text}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/apps/photocraft-cli/tests/it/main.rs b/apps/photocraft-cli/tests/it/main.rs index 4237f43610..411791d94c 100644 --- a/apps/photocraft-cli/tests/it/main.rs +++ b/apps/photocraft-cli/tests/it/main.rs @@ -7,6 +7,7 @@ mod malloc_tuning; mod man_and_completions; mod orientation; +mod psd_write_oracle; /// Nextest archives relocate binaries; plain Cargo keeps the compile-time path valid. fn binary() -> std::ffi::OsString { diff --git a/apps/photocraft-cli/tests/it/psd_write_oracle.rs b/apps/photocraft-cli/tests/it/psd_write_oracle.rs new file mode 100644 index 0000000000..524f476fa1 --- /dev/null +++ b/apps/photocraft-cli/tests/it/psd_write_oracle.rs @@ -0,0 +1,45 @@ +//! Exercise the recipe runner with the real CLI and a synthetic editable PSD. + +use std::fs; +use std::path::Path; +use std::process::Command; + +use serde_json::{Value, json}; + +#[test] +fn edited_psd_roundtrip_is_checked_and_bad_expectations_fail() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let base = root.join("base.psd"); + let cli = crate::binary(); + let made = Command::new(&cli) + .args(["run", "--new", r#"{"width":64,"height":64}"#, "--cmd", "type.create", "--params", r#"{"text":"Oracle","x":4,"y":30,"name":"Oracle"}"#, "--out"]) + .arg(&base) + .output() + .unwrap(); + assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr)); + let hash = xtask::sha256::hex(&fs::read(&base).unwrap()); + let mut recipe = json!({"version":1,"corpus_revision":"synthetic","cases":[{ + "id":"style", "base":"base.psd", "base_sha256":hash, "target":{"kind":"Type","name":"Oracle"}, + "commands":[{"command":"type.antiAlias.crisp","params":{}}], + "checks":[{"op":"changed_to","path":"/text/antialias","value":"Crisp"},{"op":"unchanged","path":"/text/text"}] + }]}); + let recipe_path = root.join("recipes.json"); + let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + fs::write(&recipe_path, serde_json::to_vec(&recipe).unwrap()).unwrap(); + let cli_path = Path::new(&cli).to_str().unwrap(); + let corpus = root.to_str().unwrap(); + let recipe_name = recipe_path.to_str().unwrap(); + let output = root.join("success"); + let args = [recipe_name, corpus, cli_path, output.to_str().unwrap()]; + xtask::psd_write_oracle::run(&src, &args).unwrap(); + let report: Value = serde_json::from_slice(&fs::read(output.join("report.json")).unwrap()).unwrap(); + assert_eq!(report["cases"][0]["status"], "pass"); + assert_eq!(report["cases"][0]["photoshop"]["opens"], "not_run"); + recipe["cases"][0]["checks"][0]["value"] = json!("Sharp"); + fs::write(&recipe_path, serde_json::to_vec(&recipe).unwrap()).unwrap(); + let bad_output = root.join("failure"); + assert!(xtask::psd_write_oracle::run(&src, &[recipe_name, corpus, cli_path, bad_output.to_str().unwrap()]).is_err()); + let bad: Value = serde_json::from_slice(&fs::read(bad_output.join("report.json")).unwrap()).unwrap(); + assert_eq!(bad["cases"][0]["status"], "fail"); +} diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index dc681b7d8e..722e8b5c6d 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -27,6 +27,16 @@ pub fn session(s: &Session) -> Value { } pub fn document(d: &DocState) -> Value { + document_with(d, false) +} + +/// [`document`] plus every text run and paragraph run, anti-aliasing and the full serialized +/// layer-effect settings, for format round-trip checks (`photocraft-cli info --detail`). +pub fn document_detail(d: &DocState) -> Value { + document_with(d, true) +} + +fn document_with(d: &DocState, detail: bool) -> Value { let doc = &d.doc; let selected = d.selected_layers(); let instances = smart_instances(&doc.layers); @@ -43,7 +53,7 @@ pub fn document(d: &DocState) -> Value { "isolatedLayers": d.isolated_layers.iter().map(|l| l.0).collect::>(), "hasSelection": doc.selection.is_some(), "selectionBounds": doc.selection.as_ref().map(|s| { let r = s.content_bounds(); [r.x0, r.y0, r.width() as i32, r.height() as i32] }), - "layers": doc.layers.iter().rev().map(|l| layer_sel(l, &selected, &instances, Some(&doc.metadata))).collect::>(), + "layers": doc.layers.iter().rev().map(|l| layer_sel(l, &selected, &instances, Some(&doc.metadata), detail)).collect::>(), "history": d.history.entries(), "historySource": crate::history_source_cmds::source_json(d), "snapshots": d.snapshots.iter().map(|snap| json!({"id": snap.id, "name": snap.name})).collect::>(), @@ -69,7 +79,13 @@ pub fn document(d: &DocState) -> Value { /// Layer tree top-to-bottom (display order). Smart object instances are counted within `l`. pub fn layer(l: &Layer) -> Value { - layer_sel(l, &[], &smart_instances(std::slice::from_ref(l)), None) + layer_sel(l, &[], &smart_instances(std::slice::from_ref(l)), None, false) +} + +/// [`layer`] plus every text run and paragraph run, anti-aliasing and the full serialized +/// layer-effect settings, for format round-trip checks (`photocraft-cli info --detail`). +pub fn layer_detail(l: &Layer) -> Value { + layer_sel(l, &[], &smart_instances(std::slice::from_ref(l)), None, true) } /// How many smart objects in `layers`, groups included, share each contents identity. @@ -87,7 +103,13 @@ fn smart_instances(layers: &[Layer]) -> HashMap { } /// [`layer`] with a `selected` flag on every node (Layers panel multi-selection). -fn layer_sel(l: &Layer, selected: &[photocraft_doc::LayerId], instances: &HashMap, meta: Option<&photocraft_doc::Metadata>) -> Value { +fn layer_sel( + l: &Layer, + selected: &[photocraft_doc::LayerId], + instances: &HashMap, + meta: Option<&photocraft_doc::Metadata>, + detail: bool, +) -> Value { let bounds = l.surface().map(|s| { let r = s.content_bounds(); [r.x0, r.y0, r.width() as i32, r.height() as i32] @@ -112,7 +134,7 @@ fn layer_sel(l: &Layer, selected: &[photocraft_doc::LayerId], instances: &HashMa }); match &l.content { LayerContent::Group(g) => { - v["children"] = Value::Array(g.children.iter().rev().map(|c| layer_sel(c, selected, instances, meta)).collect()); + v["children"] = Value::Array(g.children.iter().rev().map(|c| layer_sel(c, selected, instances, meta, detail)).collect()); v["expanded"] = json!(g.expanded); if let Some(a) = &g.artboard { v["artboard"] = json!({"rect": [a.rect.x0, a.rect.y0, a.rect.width(), a.rect.height()], "background": a.background.name(), "preset": a.preset}); @@ -153,6 +175,11 @@ fn layer_sel(l: &Layer, selected: &[photocraft_doc::LayerId], instances: &HashMa } LayerContent::Text(t) => { v["text"] = json!({"text": t.text, "font": t.font_family, "sizePt": t.size_pt}); + if detail { + v["text"]["antialias"] = serde_json::to_value(t.antialias).unwrap_or(Value::Null); + v["text"]["runs"] = serde_json::to_value(t.char_runs()).unwrap_or(Value::Null); + v["text"]["paragraphs"] = serde_json::to_value(t.paragraph_runs()).unwrap_or(Value::Null); + } } _ => {} } @@ -182,6 +209,9 @@ fn layer_sel(l: &Layer, selected: &[photocraft_doc::LayerId], instances: &HashMa "enabled": l.effects.enabled, "items": l.effects.items.iter().map(|e| json!({"kind": e.label(), "enabled": e.enabled()})).collect::>(), }); + if detail { + v["effects"]["data"] = serde_json::to_value(&l.effects.items).unwrap_or(Value::Null); + } } // Video layer (Layer › Video Layers): the frame stack behind the displayed content. if let Some(vid) = &l.video { @@ -200,6 +230,55 @@ mod tests { use photocraft_color::PixelFormat; use photocraft_doc::{LayerMask, Path, VectorMask}; + #[test] + fn layer_inspect_reports_text_runs_and_full_effect_data() { + let text = photocraft_doc::TextLayer { + text: "Hi".into(), + font_family: "Fixture Sans".into(), + size_pt: 18.0, + antialias: photocraft_doc::text::AntiAlias::Crisp, + ..Default::default() + }; + let mut lyr = Layer::new("Styled text", LayerContent::Text(text)); + lyr.effects.enabled = true; + lyr.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); + + let plain = layer(&lyr); + for key in ["antialias", "runs", "paragraphs"] { + assert!(plain["text"].get(key).is_none(), "{key}"); + } + assert!(plain["effects"].get("data").is_none()); + + let inspected = layer_detail(&lyr); + let text_json = &inspected["text"]; + assert_eq!(text_json["text"], "Hi"); + assert_eq!(text_json["font"], "Fixture Sans"); + assert_eq!(text_json["sizePt"], 18.0); + assert_eq!(text_json["antialias"], serde_json::to_value(photocraft_doc::text::AntiAlias::Crisp).unwrap()); + assert_eq!( + text_json["runs"], + serde_json::to_value(match &lyr.content { + LayerContent::Text(t) => t.char_runs(), + _ => Vec::new(), + }) + .unwrap() + ); + assert_eq!( + text_json["paragraphs"], + serde_json::to_value(match &lyr.content { + LayerContent::Text(t) => t.paragraph_runs(), + _ => Vec::new(), + }) + .unwrap() + ); + + let effects = &inspected["effects"]; + assert_eq!(effects["enabled"], true); + assert_eq!(effects["items"][0]["kind"], "Drop Shadow"); + assert_eq!(effects["data"], serde_json::to_value(&lyr.effects.items).unwrap()); + assert!(effects["data"][0]["DropShadow"]["distance"].is_number(), "{effects}"); + } + #[test] fn an_adjustment_layer_is_reported_with_the_params_its_command_takes() { let mut s = Session::new(); diff --git a/docs/development.md b/docs/development.md index 1fe3750533..0d73368277 100644 --- a/docs/development.md +++ b/docs/development.md @@ -250,6 +250,7 @@ See `docs/control-protocol.md` for every method. Tips: ```sh cargo run -p photocraft-cli -- convert in.psd out.pcraft # any supported format -> any cargo run -p photocraft-cli -- info out.pcraft # JSON: size, mode, depth, layer tree +cargo run -p photocraft-cli -- info out.psd --detail # also text runs, anti-aliasing, full layer-effect settings cargo run -p photocraft-cli -- run in.png --cmd layer.new.layer --params '{"name":"Ink"}' \ --cmd filter.blur.gaussianBlur --params '{"radius":3}' --out out.psd cargo run -p photocraft-cli -- run --new '{"width":800,"height":600}' --cmd document.inspect @@ -945,6 +946,46 @@ scripts/fetch-corpus.sh # the same as cargo xtask corpus --all - The third-party sets (psd-tools, ag-psd, PngSuite) are fetched from their upstreams the same way, and are never copied into photocraft-corpus. +## PSD write recipes + +The PSD write oracle exercises actual edits before export. The recipe runner opens each +base with `photocraft-cli`, applies its commands to a uniquely selected layer, exports +and reopens the PSD, and checks the specified properties (it reads layers with +`photocraft-cli info --detail`). It records the generated +files and results for a later independent Photoshop verification (#6130). + +```sh +cargo xtask corpus --photoshop +cargo build -p photocraft-cli --release +cargo xtask psd-write-oracle xtask/psd-write-oracle/starter.json corpus/photoshop target/release/photocraft-cli target/psd-write-oracle +``` + +The output directory must not exist. It contains `report.json`, `manifest.json`, a +candidate PSD per successful export, and CLI stdout/stderr for diagnosis. A failed +case does not prevent the other cases from running, but the command exits nonzero. +The manifest records the checkout revision, whether tracked files were modified, the +CLI binary hash, recipe hash, corpus revision and candidate hashes (revision and +dirty state are `unknown` outside a git checkout). The checkout +revision does not establish where a supplied binary was built; use a binary built from +that revision and preserve the CI run's provenance. Missing fonts and other warnings +are recorded. The runner never overwrites its input PSDs. + +Recipes are versioned JSON (`version` must be `1`; any other value is rejected). Unknown keys anywhere in a recipe are an error, so a typo never passes as "nothing to check". A case has a unique `id`, a relative `base` PSD path, +its `base_sha256`, a `target` with layer `kind` and optional `name`, and `checks`. +An optional list of `commands` contains a `command` id and `params`; the runner +supplies the resolved `layer` id. Targets that match zero or multiple layers fail. +Only `type.*` and `layer.layerStyle.*` commands are accepted. Checks use JSON pointers +relative to the inspected layer: `unchanged` requires a present, equal value before +and after; `equals` checks the exported value; `changed_to` requires the exported +value to match and differ from the base. Every edited case needs a `changed_to` check. +Every check is run and reported (not only the first failure), each result naming the layer and the property path. See the starter recipes for examples. Regenerate hashes when deliberately changing +the corpus pin, and review them against `xtask/photoshop-corpus.sha256`. + +These checks use PhotoCraft's own importer and inspector; they do **not** prove that +Photoshop can open the output or interprets it correctly. The report marks those +stages `not_run`. The ordinary CI corpus job does not yet run this recipe command or +upload its artifacts; that integration and the Photoshop judge are separate work. + ## Rendering fidelity (PSD oracle) `cargo xtask test-corpus -p io -- --nocapture` compares our composite of every corpus PSD with diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index b879946a6e..0ec2248474 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -14,3 +14,7 @@ serde = { workspace = true } chrono = { workspace = true } # perf/budgets.toml and scorecard/*.toml (MIT OR Apache-2.0). toml = "1" + +[dev-dependencies] +tempfile = "3" + diff --git a/xtask/psd-write-oracle/starter.json b/xtask/psd-write-oracle/starter.json new file mode 100644 index 0000000000..ca4666a86e --- /dev/null +++ b/xtask/psd-write-oracle/starter.json @@ -0,0 +1,170 @@ +{ + "version": 1, + "corpus_revision": "f5b1178cab15309e05b7b504545df3c701f6d8fd", + "cases": [ + { + "id": "control-1", + "base": "text/antialias-none.psd", + "base_sha256": "8d03faba9e0c0bf8b416669eababff8060bd2601c89932769088401da241f62c", + "target": { + "kind": "Type" + }, + "checks": [ + { + "op": "unchanged", + "path": "/text/text" + }, + { + "op": "unchanged", + "path": "/text/antialias" + } + ] + }, + { + "id": "control-2", + "base": "text/paragraph-justify-left.psd", + "base_sha256": "15f2e504f7c06bcc6df4ec1e17215babf300230af5575e18221705c86da383c0", + "target": { + "kind": "Type" + }, + "checks": [ + { + "op": "unchanged", + "path": "/text/text" + }, + { + "op": "unchanged", + "path": "/text/antialias" + } + ] + }, + { + "id": "control-3", + "base": "text/tracking-plus200.psd", + "base_sha256": "110e0c73f1dba131eaae97ac828001f347e957a2a0e4b81eb9b146af3c211829", + "target": { + "kind": "Type" + }, + "checks": [ + { + "op": "unchanged", + "path": "/text/text" + }, + { + "op": "unchanged", + "path": "/text/antialias" + } + ] + }, + { + "id": "text-antialias-crisp", + "base": "text/antialias-none.psd", + "base_sha256": "8d03faba9e0c0bf8b416669eababff8060bd2601c89932769088401da241f62c", + "target": { + "kind": "Type" + }, + "commands": [ + { + "command": "type.antiAlias.crisp", + "params": {} + } + ], + "checks": [ + { + "op": "unchanged", + "path": "/text/text" + }, + { + "op": "changed_to", + "path": "/text/antialias", + "value": "Crisp" + } + ] + }, + { + "id": "paragraph-justify-all", + "base": "text/paragraph-justify-left.psd", + "base_sha256": "15f2e504f7c06bcc6df4ec1e17215babf300230af5575e18221705c86da383c0", + "target": { + "kind": "Type" + }, + "commands": [ + { + "command": "type.setStyle", + "params": { + "align": "justifyAll" + } + } + ], + "checks": [ + { + "op": "unchanged", + "path": "/text/text" + }, + { + "op": "changed_to", + "path": "/text/paragraphs/0/style/align", + "value": "JustifyAll" + } + ] + }, + { + "id": "tracking-split", + "base": "text/tracking-plus200.psd", + "base_sha256": "110e0c73f1dba131eaae97ac828001f347e957a2a0e4b81eb9b146af3c211829", + "target": { + "kind": "Type" + }, + "commands": [ + { + "command": "type.setStyle", + "params": { + "range": [ + 1, + 3 + ], + "tracking": -60 + } + } + ], + "checks": [ + { + "op": "unchanged", + "path": "/text/text" + }, + { + "op": "changed_to", + "path": "/text/runs/1/style/tracking", + "value": -60.0 + } + ] + }, + { + "id": "text-drop-shadow", + "base": "text/antialias-none.psd", + "base_sha256": "8d03faba9e0c0bf8b416669eababff8060bd2601c89932769088401da241f62c", + "target": { + "kind": "Type" + }, + "commands": [ + { + "command": "layer.layerStyle.dropShadow", + "params": { + "distance": 17 + } + } + ], + "checks": [ + { + "op": "unchanged", + "path": "/text/text" + }, + { + "op": "changed_to", + "path": "/effects/data/0/DropShadow/distance", + "value": 17.0 + } + ] + } + ] +} diff --git a/xtask/src/lib.rs b/xtask/src/lib.rs new file mode 100644 index 0000000000..b5503d82fb --- /dev/null +++ b/xtask/src/lib.rs @@ -0,0 +1,4 @@ +//! Pieces of `cargo xtask` that other workspace tests reuse. + +pub mod psd_write_oracle; +pub mod sha256; diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 0a90684252..49068c3cbe 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -11,13 +11,14 @@ mod layers; mod perf; mod pinned; mod scorecard; -mod sha256; mod stats; mod version; use std::path::{Path, PathBuf}; use std::process::{Command, ExitCode, Stdio}; +use xtask::{psd_write_oracle, sha256}; + const USAGE: &str = "\ usage: cargo xtask @@ -51,6 +52,8 @@ commands: print the workspace version, or set it (Cargo.toml + Cargo.lock) ico ... pack square PNGs (<= 256 px) into a Windows .ico (see packaging/icons.sh) + psd-write-oracle + run PSD export recipes and write a JSON report and manifest "; fn main() -> ExitCode { @@ -70,6 +73,7 @@ fn main() -> ExitCode { Some("scorecard") => scorecard::run(&root(), &rest), Some("version") => version::run(&root(), &rest), Some("ico") => ico::run(&rest), + Some("psd-write-oracle") => psd_write_oracle::run(&root(), &rest), Some("-h" | "--help" | "help") | None => { print!("{USAGE}"); Ok(()) diff --git a/xtask/src/psd_write_oracle.rs b/xtask/src/psd_write_oracle.rs new file mode 100644 index 0000000000..455b3999ae --- /dev/null +++ b/xtask/src/psd_write_oracle.rs @@ -0,0 +1,446 @@ +//! Execute small PSD export recipes with the headless CLI. Photoshop is a separate judge. + +use std::collections::HashSet; +use std::fs::{self, File, OpenOptions}; +use std::path::{Component, Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +const MAX_FILE: u64 = 64 * 1024 * 1024; +const MAX_RECIPES: usize = 1000; +const TIMEOUT: Duration = Duration::from_secs(120); + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Recipes { + version: u32, + corpus_revision: String, + cases: Vec, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Recipe { + id: String, + base: String, + base_sha256: String, + target: Target, + #[serde(default)] + commands: Vec, + checks: Vec, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Target { + kind: String, + #[serde(default)] + name: Option, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Step { + command: String, + #[serde(default = "empty_object")] + params: Value, +} + +/// Fallback serde default producing an empty JSON object. +fn empty_object() -> Value { + json!({}) +} + +#[derive(Deserialize, Serialize)] +#[serde(tag = "op", deny_unknown_fields)] +enum Check { + #[serde(rename = "changed_to")] + ChangedTo { path: String, value: Value }, + #[serde(rename = "unchanged")] + Unchanged { path: String }, + #[serde(rename = "equals")] + Equals { path: String, value: Value }, +} + +/// Reject nonregular files and files whose metadata exceeds the caller’s byte limit. +fn read_limited_to(path: &Path, max: u64) -> Result, String> { + let meta = fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?; + if !meta.is_file() || meta.len() > max { + return Err(format!("{} is not a regular file of at most {max} bytes", path.display())); + } + fs::read(path).map_err(|e| format!("{}: {e}", path.display())) +} + +/// Read one recipe artifact within the runner’s file-size limit. +fn read_limited(path: &Path) -> Result, String> { + read_limited_to(path, MAX_FILE) +} + +/// Accept a case identifier that can safely name one output subdirectory. +fn valid_id(id: &str) -> bool { + !id.is_empty() && id.len() <= 100 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +/// Reject unsupported recipes, unsafe paths, duplicate IDs, and incomplete checks. +fn validate(recipes: &Recipes) -> Result<(), String> { + if recipes.version != 1 || recipes.corpus_revision.is_empty() || recipes.cases.is_empty() || recipes.cases.len() > MAX_RECIPES { + return Err("expected version 1, a corpus revision and 1..=1000 cases".into()); + } + let mut seen = HashSet::new(); + for case in &recipes.cases { + if !valid_id(&case.id) || !seen.insert(&case.id) { + return Err(format!("invalid or duplicate case id: {}", case.id)); + } + let path = Path::new(&case.base); + if path.components().any(|c| !matches!(c, Component::Normal(_))) || path.extension().is_none_or(|e| e != "psd") { + return Err(format!("{}: base must be a relative PSD path", case.id)); + } + if case.base_sha256.len() != 64 || !case.base_sha256.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) { + return Err(format!("{}: invalid SHA-256", case.id)); + } + if case.target.kind.is_empty() || case.checks.is_empty() || case.commands.len() > 50 { + return Err(format!("{}: target, checks and at most 50 commands are required", case.id)); + } + if !case.commands.is_empty() && !case.checks.iter().any(|c| matches!(c, Check::ChangedTo { .. })) { + return Err(format!("{}: an edit needs a changed_to assertion", case.id)); + } + for step in &case.commands { + if !(step.command.starts_with("type.") || step.command.starts_with("layer.layerStyle.")) + || !step.params.is_object() + || step.params.get("layer").is_some() + || step.params.get("layers").is_some() + { + return Err(format!("{}: invalid command or explicit layer in params", case.id)); + } + } + for check in &case.checks { + let path = match check { + Check::ChangedTo { path, .. } | Check::Unchanged { path } | Check::Equals { path, .. } => path, + }; + if !path.starts_with('/') || path.len() > 512 { + return Err(format!("{}: check path must be a JSON pointer", case.id)); + } + } + } + Ok(()) +} + +/// Resolve a corpus input and reject paths escaping the canonical corpus root. +fn input_path(root: &Path, relative: &str) -> Result { + let p = root.join(relative).canonicalize().map_err(|e| format!("{relative}: {e}"))?; + if !p.starts_with(root) { + return Err(format!("{relative}: path escapes corpus directory")); + } + Ok(p) +} + +/// Find exactly one layer matching the recipe’s kind and optional name. +fn target<'a>(doc: &'a Value, wanted: &Target) -> Result<&'a Value, String> { + let mut stack = vec![(doc.get("layers").and_then(Value::as_array).ok_or("missing layers")?, 0usize)]; + let mut found = Vec::new(); + while let Some((layers, depth)) = stack.pop() { + if depth > 128 { + return Err("layer nesting exceeds 128".into()); + } + for layer in layers { + if layer.get("kind").and_then(Value::as_str) == Some(wanted.kind.as_str()) + && wanted.name.as_ref().is_none_or(|name| layer.get("name").and_then(Value::as_str) == Some(name.as_str())) + { + found.push(layer); + } + if let Some(children) = layer.get("children").and_then(Value::as_array) { + stack.push((children, depth + 1)); + } + } + } + if found.len() != 1 { + return Err(format!("target matched {} layers, expected exactly one", found.len())); + } + found.into_iter().next().ok_or_else(|| "missing target".into()) +} + +fn verify(checks: &[Check], before: &Value, after: &Value) -> Vec { + let mut results = Vec::new(); + let layer = after.get("name").or_else(|| before.get("name")); + for check in checks { + let (path, op, expected) = match check { + Check::ChangedTo { path, value } => (path, "changed_to", Some(value)), + Check::Equals { path, value } => (path, "equals", Some(value)), + Check::Unchanged { path } => (path, "unchanged", None), + }; + let old = before.pointer(path); + let new = after.pointer(path); + let pass = match check { + Check::ChangedTo { value, .. } => new == Some(value) && old != new, + Check::Equals { value, .. } => new == Some(value), + Check::Unchanged { .. } => old.is_some() && old == new, + }; + results.push( + json!({"layer": layer, "path": path, "op": op, "expected": expected, "before": old, "after": new, "status": if pass { "pass" } else { "fail" }}), + ); + } + results +} + +/// Capture into files to avoid pipe deadlocks. Terminate a stuck CLI instead of blocking a batch. +fn invoke(cli: &Path, args: &[String], dir: &Path, tag: &str) -> Result<(String, String), String> { + let stdout = dir.join(format!("{tag}.stdout")); + let stderr = dir.join(format!("{tag}.stderr")); + let out = File::create(&stdout).map_err(|e| e.to_string())?; + let err = File::create(&stderr).map_err(|e| e.to_string())?; + let mut child = Command::new(cli).args(args).stdin(Stdio::null()).stdout(out).stderr(err).spawn().map_err(|e| format!("start CLI: {e}"))?; + let start = Instant::now(); + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) if start.elapsed() < TIMEOUT => std::thread::sleep(Duration::from_millis(50)), + Ok(None) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!("CLI timed out after {}s", TIMEOUT.as_secs())); + } + Err(e) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!("wait for CLI: {e}")); + } + } + }; + let out = String::from_utf8(read_limited(&stdout)?).map_err(|e| e.to_string())?; + let err = String::from_utf8(read_limited(&stderr)?).map_err(|e| e.to_string())?; + if !status.success() { + return Err(format!("CLI {tag} failed ({status}): {err}")); + } + Ok((out, err)) +} + +/// Request detailed CLI inspection and parse the returned document JSON. +fn inspect(cli: &Path, file: &Path, dir: &Path, tag: &str) -> Result { + let path = file.to_str().ok_or("non-UTF-8 path")?; + let (out, _) = invoke(cli, &["info".into(), path.into(), "--compact".into(), "--detail".into()], dir, tag)?; + serde_json::from_str(&out).map_err(|e| format!("invalid CLI inspection: {e}")) +} + +/// Export and check one case, retaining candidate provenance after export succeeds. +fn execute(case: &Recipe, corpus: &Path, cli: &Path, output: &Path) -> Result { + let input = input_path(corpus, &case.base)?; + let input_bytes = read_limited(&input)?; + if crate::sha256::hex(&input_bytes) != case.base_sha256 { + return Err("base SHA-256 mismatch".into()); + } + let dir = output.join(&case.id); + fs::create_dir(&dir).map_err(|e| e.to_string())?; + let before = inspect(cli, &input, &dir, "before")?; + let layer = target(&before, &case.target)?; + let layer_id = layer.get("id").and_then(Value::as_u64).ok_or("target lacks numeric id")?; + let candidate = dir.join("candidate.psd"); + let mut args = vec!["run".to_string(), input.to_str().ok_or("non-UTF-8 input path")?.to_string()]; + for step in &case.commands { + let mut params = step.params.clone(); + params.as_object_mut().ok_or("params must be an object")?.insert("layer".into(), json!(layer_id)); + args.extend(["--cmd".into(), step.command.clone(), "--params".into(), params.to_string()]); + } + args.extend(["--out".into(), candidate.to_str().ok_or("non-UTF-8 output path")?.to_string()]); + let (_, warnings) = invoke(cli, &args, &dir, "export")?; + let bytes = read_limited(&candidate)?; + let after = inspect(cli, &candidate, &dir, "after")?; + let checks = verify(&case.checks, layer, target(&after, &case.target)?); + let passed = checks.iter().all(|v| v.get("status").and_then(Value::as_str) == Some("pass")); + Ok(json!({"id": case.id, "status": if passed { "pass" } else { "fail" }, "base": case.base, "base_sha256": case.base_sha256, + "candidate": format!("{}/candidate.psd", case.id), "candidate_sha256": crate::sha256::hex(&bytes), "checks": checks, + "warnings": {"input": before.get("warnings"), "export": warnings, "output": after.get("warnings")}, + "photoshop": {"opens": "not_run", "meaning": "not_run", "rendering": "not_run"}})) +} + +/// Create a report artifact without overwriting an existing file. +fn write_json(path: &Path, value: &Value) -> Result<(), String> { + use std::io::Write; + let mut f = OpenOptions::new().write(true).create_new(true).open(path).map_err(|e| e.to_string())?; + serde_json::to_writer_pretty(&mut f, value).map_err(|e| e.to_string())?; + writeln!(f).map_err(|e| e.to_string()) +} + +/// Trimmed stdout of `git args` in `root`; `None` outside a checkout or without git. +fn git(root: &Path, args: &[&str]) -> Option { + let out = Command::new("git").current_dir(root).args(args).output().ok()?; + if !out.status.success() { + return None; + } + String::from_utf8(out.stdout).ok().map(|s| s.trim().to_string()) +} + +/// Execute a batch of recipes against an oracle corpus and write a verification report. +pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { + let [recipe_path, corpus, cli, output] = args else { + return Err("usage: cargo xtask psd-write-oracle ".into()); + }; + let recipe_bytes = read_limited(Path::new(recipe_path))?; + let recipes: Recipes = serde_json::from_slice(&recipe_bytes).map_err(|e| format!("invalid recipes: {e}"))?; + validate(&recipes)?; + let corpus = Path::new(corpus).canonicalize().map_err(|e| format!("corpus: {e}"))?; + let cli = Path::new(cli).canonicalize().map_err(|e| format!("CLI: {e}"))?; + let cli_sha = crate::sha256::hex(&read_limited_to(&cli, 512 * 1024 * 1024)?); + let output = Path::new(output); + fs::create_dir(output).map_err(|e| format!("output directory must be new: {e}"))?; + let revision = git(root, &["rev-parse", "HEAD"]).unwrap_or_else(|| "unknown".into()); + let dirty = match git(root, &["status", "--porcelain", "--untracked-files=no"]) { + Some(s) => json!(!s.is_empty()), + None => json!("unknown"), + }; + let mut cases = Vec::new(); + for case in &recipes.cases { + let result = execute(case, &corpus, &cli, output).unwrap_or_else(|e| { + json!({"id": case.id, "status": "fail", "error": e, + "photoshop": {"opens": "not_run", "meaning": "not_run", "rendering": "not_run"}}) + }); + cases.push(result); + } + let passed = cases.iter().all(|c| c.get("status").and_then(Value::as_str) == Some("pass")); + let report = json!({"version": 1, "source_revision": revision, "source_dirty": dirty, "corpus_revision": recipes.corpus_revision, + "recipe_sha256": crate::sha256::hex(&recipe_bytes), "cli_sha256": cli_sha, "cases": cases}); + write_json(&output.join("report.json"), &report)?; + write_json( + &output.join("manifest.json"), + &json!({"version": 1, "source_revision": revision, "source_dirty": dirty, "corpus_revision": recipes.corpus_revision, + "recipe_sha256": crate::sha256::hex(&recipe_bytes), "cli_sha256": cli_sha, + "candidates": report["cases"].as_array().into_iter().flatten().filter_map(|c| Some(json!({"id": c.get("id")?, "path": c.get("candidate")?, "sha256": c.get("candidate_sha256")?}))).collect::>() }), + )?; + if passed { Ok(()) } else { Err(format!("one or more recipes failed; see {}/report.json", output.display())) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn git_is_optional() { + assert!(git(&std::env::temp_dir().join("psd-write-oracle-no-such-dir"), &["rev-parse", "HEAD"]).is_none()); + } + + #[test] + fn detects_wrong_or_unchanged_edits_and_missing_fields() { + let before = json!({"text":{"tracking":0,"value":"hello"}}); + let after = json!({"text":{"tracking":30,"value":"hello"}}); + let checks = [Check::ChangedTo { path: "/text/tracking".into(), value: json!(30) }, Check::Unchanged { path: "/text/value".into() }]; + assert!(verify(&checks, &before, &after).iter().all(|c| c["status"] == "pass")); + assert_eq!(verify(&checks, &before, &before)[0]["status"], "fail"); + let missing = [Check::Unchanged { path: "/missing".into() }]; + assert_eq!(verify(&missing, &before, &after)[0]["status"], "fail"); + } + + #[test] + fn every_failed_check_is_reported_with_layer_name_and_property() { + let before = json!({"name":"Title","text":{"tracking":0,"value":"a"}}); + let after = json!({"name":"Title","text":{"tracking":0,"value":"b"}}); + let checks = [ + Check::ChangedTo { path: "/text/tracking".into(), value: json!(30) }, + Check::Unchanged { path: "/text/value".into() }, + Check::Equals { path: "/text/value".into(), value: json!("c") }, + ]; + let results = verify(&checks, &before, &after); + assert_eq!(results.len(), 3); + assert!(results.iter().all(|r| r["status"] == "fail" && r["layer"] == "Title")); + assert_eq!(results[0]["path"], "/text/tracking"); + assert_eq!(results[1]["path"], "/text/value"); + } + + #[test] + fn wrong_layer_count_and_unsupported_version_are_errors() { + let selector = Target { kind: "Text".into(), name: None }; + let none = json!({"layers":[{"kind":"Raster"}]}); + assert!(target(&none, &selector).unwrap_err().contains("matched 0 layers")); + let two = json!({"layers":[{"kind":"Text"},{"kind":"Text"}]}); + assert!(target(&two, &selector).unwrap_err().contains("matched 2 layers")); + let recipe = json!({"version":2,"corpus_revision":"pin","cases":[{"id":"x","base":"x.psd","base_sha256":"a".repeat(64),"target":{"kind":"Type"},"checks":[{"op":"unchanged","path":"/name"}]}]}); + assert!(validate(&serde_json::from_value(recipe).unwrap()).unwrap_err().contains("version 1")); + } + + #[test] + fn unknown_keys_are_rejected_in_every_object() { + let case = |extra: Value| { + let mut c = json!({"id":"x","base":"x.psd","base_sha256":"a".repeat(64),"target":{"kind":"Type"},"checks":[{"op":"unchanged","path":"/name"}]}); + c.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + json!({"version":1,"corpus_revision":"pin","cases":[c]}) + }; + assert!(serde_json::from_value::(case(json!({"target":{"kind":"Type","nmae":"x"}}))).is_err()); + assert!(serde_json::from_value::(case(json!({"checks":[{"op":"unchanged","path":"/name","extra":1}]}))).is_err()); + assert!(serde_json::from_value::(case(json!({"commands":[{"command":"type.x","parms":{}}]}))).is_err()); + let mut top = case(json!({})); + top["extra"] = json!(1); + assert!(serde_json::from_value::(top).is_err()); + } + + #[test] + fn layer_selection_rejects_ambiguity_and_finds_nested_layers() { + let doc = json!({"layers":[{"kind":"Group","children":[{"kind":"Text","id":7,"name":"A"}]}]}); + let selector = Target { kind: "Text".into(), name: None }; + assert_eq!(target(&doc, &selector).unwrap()["id"], 7); + let ambiguous = json!({"layers":[{"kind":"Text"},{"kind":"Text"}]}); + assert!(target(&ambiguous, &selector).is_err()); + } + + #[test] + fn schema_rejects_unsafe_paths_duplicate_ids_and_unverified_edits() { + let recipe = json!({"version":1,"corpus_revision":"pin","cases":[{"id":"case","base":"../x.psd","base_sha256":"a".repeat(64),"target":{"kind":"Text"},"checks":[{"op":"unchanged","path":"/name"}]}]}); + let parsed: Recipes = serde_json::from_value(recipe).unwrap(); + assert!(validate(&parsed).is_err()); + let duplicate = json!({"version":1,"corpus_revision":"pin","cases":[{"id":"x","base":"x.psd","base_sha256":"a".repeat(64),"target":{"kind":"Text"},"checks":[{"op":"unchanged","path":"/name"}]},{"id":"x","base":"x.psd","base_sha256":"a".repeat(64),"target":{"kind":"Text"},"checks":[{"op":"unchanged","path":"/name"}]}]}); + assert!(validate(&serde_json::from_value(duplicate).unwrap()).is_err()); + let edit = json!({"version":1,"corpus_revision":"pin","cases":[{"id":"x","base":"x.psd","base_sha256":"a".repeat(64),"target":{"kind":"Text"},"commands":[{"command":"type.setStyle"}],"checks":[{"op":"unchanged","path":"/name"}]}]}); + assert!(validate(&serde_json::from_value(edit).unwrap()).is_err()); + } + + #[cfg(unix)] + #[test] + fn export_batch_checks_reopened_result_and_propagates_command_failure() { + use std::os::unix::fs::PermissionsExt; + let tmp = tempfile::Builder::new().prefix("psd-write-oracle-").tempdir().unwrap(); + let root = tmp.path().to_path_buf(); + let corpus = root.join("corpus"); + let output = root.join("output"); + fs::create_dir(&corpus).unwrap(); + let corpus = corpus.canonicalize().unwrap(); + fs::create_dir(&output).unwrap(); + fs::write(corpus.join("base.psd"), b"base").unwrap(); + let cli = root.join("fake-cli"); + fs::write( + &cli, + r##"#!/bin/sh +if [ "$1" = info ]; then + case "$2" in + */candidate.psd) echo '{"layers":[{"kind":"Type","id":4,"text":{"antialias":"Crisp"}}]}' ;; + *) echo '{"layers":[{"kind":"Type","id":4,"text":{"antialias":"None"}}]}' ;; + esac + exit 0 +fi +if [ "$3" = --cmd ] && [ "$4" = type.bad ]; then + echo 'bad command' >&2 + exit 1 +fi +input="$2" +while [ "$#" -gt 0 ]; do + if [ "$1" = --out ]; then cp "$input" "$2"; exit 0; fi + shift +done +exit 1 +"##, + ) + .unwrap(); + fs::set_permissions(&cli, fs::Permissions::from_mode(0o755)).unwrap(); + let make_case = |id: &str, command: &str| Recipe { + id: id.into(), + base: "base.psd".into(), + base_sha256: crate::sha256::hex(b"base"), + target: Target { kind: "Type".into(), name: None }, + commands: vec![Step { command: command.into(), params: json!({}) }], + checks: vec![Check::ChangedTo { path: "/text/antialias".into(), value: json!("Crisp") }], + }; + let good = execute(&make_case("good", "type.antiAlias.crisp"), &corpus, &cli, &output).unwrap(); + assert_eq!(good["status"], "pass"); + assert_eq!(good["photoshop"]["opens"], "not_run"); + assert!(execute(&make_case("bad", "type.bad"), &corpus, &cli, &output).unwrap_err().contains("bad command")); + } +}